oslo_config package

Subpackages

Submodules

oslo_config.cfg module

Primary module in oslo_config.

exception oslo_config.cfg.ArgsAlreadyParsedError(msg=None)

Bases: Error

Raised if a CLI opt is registered after parsing.

class oslo_config.cfg.BoolOpt(name, **kwargs)

Bases: Opt

Boolean options.

Bool opts are set to True or False on the command line using –optname or –nooptname respectively.

In config files, boolean values are cast with Boolean type.

Parameters:
  • name – the option’s name

  • **kwargs – arbitrary keyword arguments passed to Opt

exception oslo_config.cfg.ConfigDirNotFoundError(config_dir)

Bases: Error

Raised if the requested config-dir is not found.

exception oslo_config.cfg.ConfigFileParseError(config_file, msg)

Bases: Error

Raised if there is an error parsing a config file.

exception oslo_config.cfg.ConfigFileValueError(msg=None)

Bases: ConfigSourceValueError

Raised if a config file value does not match its opt type.

exception oslo_config.cfg.ConfigFilesNotFoundError(config_files)

Bases: Error

Raised if one or more config files are not found.

exception oslo_config.cfg.ConfigFilesPermissionDeniedError(config_files)

Bases: Error

Raised if one or more config files are not readable.

class oslo_config.cfg.ConfigOpts

Bases: Mapping

Config options which may be set on the command line or in config files.

ConfigOpts is a configuration option manager with APIs for registering option schemas, grouping options, parsing option values and retrieving the values of options.

It has built-in support for config_file and config_dir options.

class GroupAttr(conf, group)

Bases: Mapping

Helper class.

Represents the option values of a group as a mapping and attributes.

class StrSubWrapper(conf, group=None, namespace=None)

Bases: object

Helper class.

Exposes opt values as a dict for string substitution.

class SubCommandAttr(conf, group, dest)

Bases: object

Helper class.

Represents the name and arguments of an argparse sub-parser.

class Template(template)

Bases: Template

idpattern = '[_a-z][\\._a-z0-9]*'
pattern = re.compile('\n            \\$(?:\n              (?P<escaped>\\$)  |   # Escape sequence of two delimiters\n              (?P<named>[_a-z][\\._a-z0-9]*)       |   # delimiter and a Python identifier\n            , re.IGNORECASE|re.VERBOSE)
clear()

Reset the state of the object to before options were registered.

This method removes all registered options and discards the data from the command line and configuration files.

Any subparsers added using the add_cli_subparsers() will also be removed as a side-effect of this method.

clear_default(name, group=None)

Clear an override an opt’s default value.

Clear a previously set override of the default value of given option.

Parameters:
  • name – the name/dest of the opt

  • group – an option OptGroup object or group name

Raises:

NoSuchOptError, NoSuchGroupError

clear_override(name, group=None)

Clear an override an opt value.

Clear a previously set override of the command line, config file and default values of a given option.

Parameters:
  • name – the name/dest of the opt

  • group – an option OptGroup object or group name

Raises:

NoSuchOptError, NoSuchGroupError

property config_dirs
disallow_names = ('project', 'prog', 'version', 'usage', 'default_config_files', 'default_config_dirs')
find_file(name)

Locate a file located alongside the config files.

Search for a file with the supplied basename in the directories which we have already loaded config files from and other known configuration directories.

The directory, if any, supplied by the config_dir option is searched first. Then the config_file option is iterated over and each of the base directories of the config_files values are searched. Failing both of these, the standard directories searched by the module level find_config_files() function is used. The first matching file is returned.

Parameters:

name – the filename, for example ‘policy.json’

Returns:

the path to a matching file, or None

get_location(name, group=None)

Return the location where the option is being set.

Parameters:
  • name (str) – The name of the option.

  • group (str) – The name of the group of the option. Defaults to 'DEFAULT'.

Returns:

LocationInfo

New in version 5.3.0.

import_group(group, module_str)

Import an option group from a module.

Import a module and check that a given option group is registered.

This is intended for use with global configuration objects like cfg.CONF where modules commonly register options with CONF at module load time. If one module requires an option group defined by another module it can use this method to explicitly declare the dependency.

Parameters:
  • group – an option OptGroup object or group name

  • module_str – the name of a module to import

Raises:

ImportError, NoSuchGroupError

import_opt(name, module_str, group=None)

Import an option definition from a module.

Import a module and check that a given option is registered.

This is intended for use with global configuration objects like cfg.CONF where modules commonly register options with CONF at module load time. If one module requires an option defined by another module it can use this method to explicitly declare the dependency.

Parameters:
  • name – the name/dest of the opt

  • module_str – the name of a module to import

  • group – an option OptGroup object or group name

Raises:

NoSuchOptError, NoSuchGroupError

list_all_sections()

List all sections from the configuration.

Returns a sorted list of all section names found in the configuration files, whether declared beforehand or not.

log_opt_values(logger, lvl)

Log the value of all registered opts.

It’s often useful for an app to log its configuration to a log file at startup for debugging. This method dumps to the entire config state to the supplied logger at a given log level.

Parameters:
  • logger – a logging.Logger object

  • lvl – the log level (for example logging.DEBUG) arg to logger.log()

mutate_config_files()

Reload configure files and parse all options.

Only options marked as ‘mutable’ will appear to change.

Hooks are called in a NON-DETERMINISTIC ORDER. Do not expect hooks to be called in the same order as they were added.

Returns:

{(None or ‘group’, ‘optname’): (old_value, new_value), … }

Raises:

Error if reloading fails

print_help(file=None)

Print the help message for the current program.

This method is for use after all CLI options are known registered using __call__() method. If this method is called before the __call__() is invoked, it throws NotInitializedError

Parameters:

file – the File object (if None, output is on sys.stdout)

Raises:

NotInitializedError

print_usage(file=None)

Print the usage message for the current program.

This method is for use after all CLI options are known registered using __call__() method. If this method is called before the __call__() is invoked, it throws NotInitializedError

Parameters:

file – the File object (if None, output is on sys.stdout)

Raises:

NotInitializedError

register_cli_opt(opt, group=None)

Register a CLI option schema.

CLI option schemas must be registered before the command line and config files are parsed. This is to ensure that all CLI options are shown in –help and option validation works as expected.

Parameters:
  • opt – an instance of an Opt sub-class

  • group – an optional OptGroup object or group name

Returns:

False if the opt was already registered, True otherwise

Raises:

DuplicateOptError, ArgsAlreadyParsedError

register_cli_opts(opts, group=None)

Register multiple CLI option schemas at once.

register_group(group)

Register an option group.

An option group must be registered before options can be registered with the group.

Parameters:

group – an OptGroup object

register_mutate_hook(hook)

Registers a hook to be called by mutate_config_files.

Parameters:

hook – a function accepting this ConfigOpts object and a dict of config mutations, as returned by mutate_config_files.

Returns:

None

register_opt(opt, group=None, cli=False)

Register an option schema.

Registering an option schema makes any option value which is previously or subsequently parsed from the command line or config files available as an attribute of this object.

Parameters:
  • opt – an instance of an Opt sub-class

  • group – an optional OptGroup object or group name

  • cli – whether this is a CLI option

Returns:

False if the opt was already registered, True otherwise

Raises:

DuplicateOptError

register_opts(opts, group=None)

Register multiple option schemas at once.

reload_config_files()

Reload configure files and parse all options

Returns:

False if reload configure files failed or else return True

reset()

Clear the object state and unset overrides and defaults.

set_default(name, default, group=None)

Override an opt’s default value.

Override the default value of given option. A command line or config file value will still take precedence over this default.

Parameters:
  • name – the name/dest of the opt

  • default – the default value

  • group – an option OptGroup object or group name

Raises:

NoSuchOptError, NoSuchGroupError

set_override(name, override, group=None)

Override an opt value.

Override the command line, config file and default values of a given option.

Parameters:
  • name – the name/dest of the opt

  • override – the override value

  • group – an option OptGroup object or group name

Raises:

NoSuchOptError, NoSuchGroupError

unregister_opt(opt, group=None)

Unregister an option.

Parameters:
  • opt – an Opt object

  • group – an optional OptGroup object or group name

Raises:

ArgsAlreadyParsedError, NoSuchGroupError

unregister_opts(opts, group=None)

Unregister multiple CLI option schemas at once.

class oslo_config.cfg.ConfigParser(filename, sections)

Bases: BaseParser

Parses a single config file, populating ‘sections’ to look like:

{'DEFAULT': {'key': [value, ...], ...},
 ...}

Also populates self._normalized which looks the same but with normalized section names.

assignment(key, value)

Called when a full assignment is parsed.

error_no_section()
new_section(section)

Called when a new section is started.

parse()
parse_exc(msg, lineno, line=None)

Common base class for all non-exit exceptions.

exception oslo_config.cfg.ConfigSourceValueError(msg=None)

Bases: Error, ValueError

Raised if a config source value does not match its opt type.

exception oslo_config.cfg.DefaultValueError(msg=None)

Bases: Error, ValueError

Raised if a default config type does not fit the opt type.

class oslo_config.cfg.DeprecatedOpt(name, group=None)

Bases: object

Represents a Deprecated option.

Here’s how you can use it:

oldopts = [cfg.DeprecatedOpt('oldopt1', group='group1'),
           cfg.DeprecatedOpt('oldopt2', group='group2')]
cfg.CONF.register_group(cfg.OptGroup('group1'))
cfg.CONF.register_opt(cfg.StrOpt('newopt', deprecated_opts=oldopts),
                      group='group1')

For options which have a single value (like in the example above), if the new option is present (“[group1]/newopt” above), it will override any deprecated options present (“[group1]/oldopt1” and “[group2]/oldopt2” above).

If no group is specified for a DeprecatedOpt option (i.e. the group is None), lookup will happen within the same group the new option is in. For example, if no group was specified for the second option ‘oldopt2’ in oldopts list:

oldopts = [cfg.DeprecatedOpt('oldopt1', group='group1'),
           cfg.DeprecatedOpt('oldopt2')]
cfg.CONF.register_group(cfg.OptGroup('group1'))
cfg.CONF.register_opt(cfg.StrOpt('newopt', deprecated_opts=oldopts),
                      group='group1')

then lookup for that option will happen in group ‘group1’.

If the new option is not present and multiple deprecated options are present, the option corresponding to the first element of deprecated_opts will be chosen.

Multi-value options will return all new and deprecated options. So if we have a multi-value option “[group1]/opt1” whose deprecated option is “[group2]/opt2”, and the conf file has both these options specified like so:

[group1]
opt1=val10,val11

[group2]
opt2=val21,val22

Then the value of “[group1]/opt1” will be [‘val10’, ‘val11’, ‘val21’, ‘val22’].

New in version 1.2.

class oslo_config.cfg.DictOpt(name, **kwargs)

Bases: Opt

Option with Dict(String) type

Option with type oslo_config.types.Dict

Parameters:
  • name – the option’s name

  • **kwargs – arbitrary keyword arguments passed to Opt

New in version 1.2.

exception oslo_config.cfg.DuplicateOptError(opt_name)

Bases: Error

Raised if multiple opts with the same name are registered.

exception oslo_config.cfg.Error(msg=None)

Bases: Exception

Base class for cfg exceptions.

class oslo_config.cfg.FloatOpt(name, min=None, max=None, **kwargs)

Bases: Opt

Option with Float type

Option with type oslo_config.types.Float

Parameters:
  • name – the option’s name

  • min – minimum value the float can take

  • max – maximum value the float can take

  • **kwargs – arbitrary keyword arguments passed to Opt

Changed in version 3.14: Added min and max parameters.

class oslo_config.cfg.HostAddressOpt(name, version=None, **kwargs)

Bases: Opt

Option for either an IP or a hostname.

Accepts valid hostnames and valid IP addresses.

Option with type oslo_config.types.HostAddress

Parameters:
  • name – the option’s name

  • version – one of either 4, 6, or None to specify either version.

  • **kwargs – arbitrary keyword arguments passed to Opt

New in version 3.22.

class oslo_config.cfg.HostDomainOpt(name, version=None, **kwargs)

Bases: Opt

Option for either an IP or a hostname.

Like HostAddress with the support of _ character.

Option with type oslo_config.types.HostDomain

Parameters:
  • name – the option’s name

  • version – one of either 4, 6, or None to specify either version.

  • **kwargs – arbitrary keyword arguments passed to Opt

New in version 8.6.

class oslo_config.cfg.HostnameOpt(name, **kwargs)

Bases: Opt

Option for a hostname. Only accepts valid hostnames.

Option with type oslo_config.types.Hostname

Parameters:
  • name – the option’s name

  • **kwargs – arbitrary keyword arguments passed to Opt

New in version 3.8.

class oslo_config.cfg.IPOpt(name, version=None, **kwargs)

Bases: Opt

Opt with IPAddress type

Option with type oslo_config.types.IPAddress

Parameters:
  • name – the option’s name

  • version – one of either 4, 6, or None to specify either version.

  • **kwargs – arbitrary keyword arguments passed to Opt

New in version 1.4.

class oslo_config.cfg.IntOpt(name, min=None, max=None, choices=None, **kwargs)

Bases: Opt

Option with Integer type

Option with type oslo_config.types.Integer

Parameters:
  • name – the option’s name

  • min – minimum value the integer can take

  • max – maximum value the integer can take

  • choices – Optional sequence of either valid values or tuples of valid values with descriptions.

  • **kwargs – arbitrary keyword arguments passed to Opt

Changed in version 1.15: Added min and max parameters.

Changed in version 9.3.0: Added choices parameter.

class oslo_config.cfg.ListOpt(name, item_type=None, bounds=None, **kwargs)

Bases: Opt

Option with List(String) type

Option with type oslo_config.types.List

Parameters:
  • name – the option’s name

  • item_type – type of items (see oslo_config.types)

  • bounds – if True the value should be inside “[” and “]” pair

  • **kwargs – arbitrary keyword arguments passed to Opt

Changed in version 2.5: Added item_type and bounds parameters.

class oslo_config.cfg.LocationInfo(location, detail)

Bases: tuple

detail

Alias for field number 1

location

Alias for field number 0

class oslo_config.cfg.Locations(value)

Bases: Enum

An enumeration.

command_line = (5, True)
environment = (6, True)
opt_default = (1, False)
set_default = (2, False)
set_override = (3, False)
user = (4, True)
class oslo_config.cfg.MultiOpt(name, item_type, **kwargs)

Bases: Opt

Multi-value option.

Multi opt values are typed opts which may be specified multiple times. The opt value is a list containing all the values specified.

Parameters:
  • name – the option’s name

  • item_type – Type of items (see oslo_config.types)

  • **kwargs – arbitrary keyword arguments passed to Opt

For example:

cfg.MultiOpt('foo',
             item_type=types.Integer(),
             default=None,
             help="Multiple foo option")

The command line --foo=1 --foo=2 would result in cfg.CONF.foo containing [1,2]

New in version 1.3.

multi = True
class oslo_config.cfg.MultiStrOpt(name, **kwargs)

Bases: MultiOpt

MultiOpt with a MultiString item_type.

MultiOpt with a default oslo_config.types.MultiString item type.

Parameters:
  • name – the option’s name

  • **kwargs – arbitrary keyword arguments passed to MultiOpt

exception oslo_config.cfg.NoSuchGroupError(group_name)

Bases: Error

Raised if a group which doesn’t exist is referenced.

exception oslo_config.cfg.NoSuchOptError(opt_name, group=None)

Bases: Error, AttributeError

Raised if an opt which doesn’t exist is referenced.

exception oslo_config.cfg.NotInitializedError(msg=None)

Bases: Error

Raised if parser is not initialized yet.

class oslo_config.cfg.Opt(name, type=None, dest=None, short=None, default=None, positional=False, metavar=None, help=None, secret=False, required=None, deprecated_name=None, deprecated_group=None, deprecated_opts=None, sample_default=None, deprecated_for_removal=False, deprecated_reason=None, deprecated_since=None, mutable=False, advanced=False)

Bases: object

Base class for all configuration options.

The only required parameter is the option’s name. However, it is common to also supply a default and help string for all options.

Parameters:
  • name – the option’s name

  • type – the option’s type. Must be a callable object that takes string and returns converted and validated value

  • dest – the name of the corresponding ConfigOpts property

  • short – a single character CLI option name

  • default – the default value of the option

  • positional – True if the option is a positional CLI argument

  • metavar – the option argument to show in –help

  • help – an explanation of how the option is used

  • secret – true if the value should be obfuscated in log output

  • required – true if a value must be supplied for this option

  • deprecated_name – deprecated name option. Acts like an alias

  • deprecated_group – the group containing a deprecated alias

  • deprecated_opts – list of DeprecatedOpt

  • sample_default – a default string for sample config files

  • deprecated_for_removal – indicates whether this opt is planned for removal in a future release

  • deprecated_reason – indicates why this opt is planned for removal in a future release. Silently ignored if deprecated_for_removal is False

  • deprecated_since – indicates which release this opt was deprecated in. Accepts any string, though valid version strings are encouraged. Silently ignored if deprecated_for_removal is False

  • mutable – True if this option may be reloaded

  • advanced – a bool True/False value if this option has advanced usage and is not normally used by the majority of users

An Opt object has no public methods, but has a number of public properties:

name

the name of the option, which may include hyphens

type

a callable object that takes string and returns converted and validated value. Default types are available from oslo_config.types

dest

the (hyphen-less) ConfigOpts property which contains the option value

short

a single character CLI option name

default

the default value of the option

sample_default

a sample default value string to include in sample config files

positional

True if the option is a positional CLI argument

metavar

the name shown as the argument to a CLI option in –help output

help

a string explaining how the option’s value is used

advanced

in sample files, a bool value indicating the option is advanced

Changed in version 1.2: Added deprecated_opts parameter.

Changed in version 1.4: Added sample_default parameter.

Changed in version 1.9: Added deprecated_for_removal parameter.

Changed in version 2.7: An exception is now raised if the default value has the wrong type.

Changed in version 3.2: Added deprecated_reason parameter.

Changed in version 3.5: Added mutable parameter.

Changed in version 3.12: Added deprecated_since parameter.

Changed in version 3.15: Added advanced parameter and attribute.

multi = False
class oslo_config.cfg.OptGroup(name, title=None, help=None, dynamic_group_owner='', driver_option='')

Bases: object

Represents a group of opts.

CLI opts in the group are automatically prefixed with the group name.

Each group corresponds to a section in config files.

An OptGroup object has no public methods, but has a number of public string properties:

name

the name of the group

title

the group title as displayed in –help

help

the group description as displayed in –help

Parameters:
  • name (str) – the group name

  • title (str) – the group title for –help

  • help (str) – the group description for –help

  • dynamic_group_owner (str) – The name of the option that controls repeated instances of this group.

  • driver_option (str) – The name of the option within the group that controls which driver will register options.

exception oslo_config.cfg.ParseError(msg, lineno, line, filename)

Bases: ParseError

class oslo_config.cfg.PortOpt(name, min=None, max=None, choices=None, **kwargs)

Bases: Opt

Option for a TCP/IP port number. Ports can range from 0 to 65535.

Option with type oslo_config.types.Integer

Parameters:
  • name – the option’s name

  • min – minimum value the port can take

  • max – maximum value the port can take

  • choices – Optional sequence of either valid values or tuples of valid values with descriptions.

  • **kwargs – arbitrary keyword arguments passed to Opt

New in version 2.6.

Changed in version 3.2: Added choices parameter.

Changed in version 3.4: Allow port number with 0.

Changed in version 3.16: Added min and max parameters.

Changed in version 5.2: The choices parameter will now accept a sequence of tuples, where each tuple is of form (choice, description)

exception oslo_config.cfg.RequiredOptError(opt_name, group=None)

Bases: Error

Raised if an option is required but no value is supplied by the user.

class oslo_config.cfg.StrOpt(name, choices=None, quotes=None, regex=None, ignore_case=False, max_length=None, **kwargs)

Bases: Opt

Option with String type

Option with type oslo_config.types.String

Parameters:
  • name – the option’s name

  • choices – Optional sequence of either valid values or tuples of valid values with descriptions.

  • quotes – If True and string is enclosed with single or double quotes, will strip those quotes.

  • regex – Optional regular expression (string or compiled regex) that the value must match on an unanchored search.

  • ignore_case – If True case differences (uppercase vs. lowercase) between ‘choices’ or ‘regex’ will be ignored.

  • max_length – If positive integer, the value must be less than or equal to this parameter.

  • **kwargs – arbitrary keyword arguments passed to Opt

Changed in version 2.7: Added quotes parameter

Changed in version 2.7: Added regex parameter

Changed in version 2.7: Added ignore_case parameter

Changed in version 2.7: Added max_length parameter

Changed in version 5.2: The choices parameter will now accept a sequence of tuples, where each tuple is of form (choice, description)

class oslo_config.cfg.SubCommandOpt(name, dest=None, handler=None, title=None, description=None, help=None)

Bases: Opt

Sub-command options.

Sub-command options allow argparse sub-parsers to be used to parse additional command line arguments.

The handler argument to the SubCommandOpt constructor is a callable which is supplied an argparse subparsers object. Use this handler callable to add sub-parsers.

The opt value is SubCommandAttr object with the name of the chosen sub-parser stored in the ‘name’ attribute and the values of other sub-parser arguments available as additional attributes.

Parameters:
  • name – the option’s name

  • dest – the name of the corresponding ConfigOpts property

  • handler – callable which is supplied subparsers object when invoked

  • title – title of the sub-commands group in help output

  • description – description of the group in help output

  • help – a help string giving an overview of available sub-commands

exception oslo_config.cfg.TemplateSubstitutionError(msg=None)

Bases: Error

Raised if an error occurs substituting a variable in an opt value.

class oslo_config.cfg.URIOpt(name, max_length=None, schemes=None, **kwargs)

Bases: Opt

Opt with URI type

Option with type oslo_config.types.URI

Parameters:
  • name – the option’s name

  • max_length – If positive integer, the value must be less than or equal to this parameter.

  • schemes – list of valid URI schemes, e.g. ‘https’, ‘ftp’, ‘git’

  • **kwargs – arbitrary keyword arguments passed to Opt

New in version 3.12.

Changed in version 3.14: Added max_length parameter

Changed in version 3.18: Added schemes parameter

oslo_config.cfg.find_config_dirs(project=None, prog=None, extension='.conf.d')

Return a list of default configuration dirs.

Parameters:
  • project – an optional project name

  • prog – the program name, defaulting to the basename of sys.argv[0], without extension .py

  • extension – the type of the config directory. Defaults to ‘.conf.d’

We default to two config dirs: [${project}.conf.d/, ${prog}.conf.d/]. If no project name is supplied, we only look for ${prog.conf.d/}.

And we look for those config dirs in the following directories:

~/.${project}/
~/
/etc/${project}/
/etc/
${SNAP_COMMON}/etc/${project}
${SNAP}/etc/${project}

We return an absolute path for each of the two config dirs, in the first place we find it (iff we find it).

For example, if project=foo, prog=bar and /etc/foo/foo.conf.d/, /etc/bar.conf.d/ and ~/.foo/bar.conf.d/ all exist, then we return [‘/etc/foo/foo.conf.d/’, ‘~/.foo/bar.conf.d/’]

oslo_config.cfg.find_config_files(project=None, prog=None, extension='.conf')

Return a list of default configuration files.

Parameters:
  • project – an optional project name

  • prog – the program name, defaulting to the basename of sys.argv[0], without extension .py

  • extension – the type of the config file

We default to two config files: [${project}.conf, ${prog}.conf]

And we look for those config files in the following directories:

~/.${project}/
~/
/etc/${project}/
/etc/
${SNAP_COMMON}/etc/${project}
${SNAP}/etc/${project}

We return an absolute path for (at most) one of each the default config files, for the topmost directory it exists in.

For example, if project=foo, prog=bar and /etc/foo/foo.conf, /etc/bar.conf and ~/.foo/bar.conf all exist, then we return [‘/etc/foo/foo.conf’, ‘~/.foo/bar.conf’]

If no project name is supplied, we only look for ${prog}.conf.

oslo_config.cfg.set_defaults(opts, **kwargs)

oslo_config.fixture module

class oslo_config.fixture.Config(conf=<oslo_config.cfg.ConfigOpts object>)

Bases: Fixture

Allows overriding configuration settings for the test.

conf will be reset on cleanup.

config(**kw)

Override configuration values.

The keyword arguments are the names of configuration options to override and their values.

If a group argument is supplied, the overrides are applied to the specified configuration option group, otherwise the overrides are applied to the default group.

load_raw_values(group=None, **kwargs)

Load raw values into the configuration without registering them.

This method adds a series of parameters into the current config instance, as if they had been loaded by a ConfigParser. This method does not require that you register the configuration options first, however the values loaded will not be accessible until you do.

register_cli_opt(opt, group=None)

Register a single CLI option for the test run.

Options registered in this manner will automatically be unregistered during cleanup.

If a group argument is supplied, it will register the new option to that group, otherwise the option is registered to the default group.

CLI options must be registered before the command line and config files are parsed. This is to ensure that all CLI options are shown in –help and option validation works as expected.

register_cli_opts(opts, group=None)

Register multiple CLI options for the test run.

This works in the same manner as register_opt() but takes a list of options as the first argument. All arguments will be registered to the same group if the group argument is supplied, otherwise all options will be registered to the default group.

CLI options must be registered before the command line and config files are parsed. This is to ensure that all CLI options are shown in –help and option validation works as expected.

register_opt(opt, group=None)

Register a single option for the test run.

Options registered in this manner will automatically be unregistered during cleanup.

If a group argument is supplied, it will register the new option to that group, otherwise the option is registered to the default group.

register_opts(opts, group=None)

Register multiple options for the test run.

This works in the same manner as register_opt() but takes a list of options as the first argument. All arguments will be registered to the same group if the group argument is supplied, otherwise all options will be registered to the default group.

setUp()

Prepare the Fixture for use.

This should not be overridden. Concrete fixtures should implement _setUp. Overriding of setUp is still supported, just not recommended.

After setUp has completed, the fixture will have one or more attributes which can be used (these depend totally on the concrete subclass).

Raises:

MultipleExceptions if _setUp fails. The last exception captured within the MultipleExceptions will be a SetupError exception.

Returns:

None.

Changed in 1.3:

The recommendation to override setUp has been reversed - before 1.3, setUp() should be overridden, now it should not be.

Changed in 1.3.1:

BaseException is now caught, and only subclasses of Exception are wrapped in MultipleExceptions.

set_config_dirs(config_dirs)

Specify a list of config dirs to read.

This method allows you to predefine the list of configuration dirs that are loaded by oslo_config. It will ensure that your tests do not attempt to autodetect, and accidentally pick up config files from locally installed services.

set_config_files(config_files)

Specify a list of config files to read.

This method allows you to predefine the list of configuration files that are loaded by oslo_config. It will ensure that your tests do not attempt to autodetect, and accidentally pick up config files from locally installed services.

set_default(name, default, group=None)

Set a default value for an option.

This method is not necessarily meant to be invoked directly. It is here to allow the set_defaults() functions in various Oslo libraries to work with a Config fixture instead of a ConfigOpts instance.

Use it like:

class MyTest(testtools.TestCase):

    def setUp(self):
        super(MyTest, self).setUp()
        self.conf = self.useFixture(fixture.Config())

    def test_something(self):
        some_library.set_defaults(self.conf, name='value')
        some_library.do_something_exciting()

oslo_config.generator module

Sample configuration generator

Tool for generating a sample configuration file. See ../doc/source/cli/generator.rst for details.

New in version 1.4.

oslo_config.generator.generate(conf, output_file=None)

Generate a sample config file.

List all of the options available via the namespaces specified in the given configuration and write a description of them to the specified output file.

Parameters:

conf – a ConfigOpts instance containing the generator’s configuration

oslo_config.generator.i18n_representer(dumper, data)

oslo_i18n yaml representer

Returns a translated to the default locale string for yaml.safe_dump

Parameters:
  • dumper – a SafeDumper instance passed by yaml.safe_dump

  • data – a oslo_i18n._message.Message instance

oslo_config.generator.main(args=None)

The main function of oslo-config-generator.

oslo_config.generator.on_load_failure_callback(*args, **kwargs)
oslo_config.generator.register_cli_opts(conf)

Register the formatter’s CLI options with a ConfigOpts instance.

Note, this must be done before the ConfigOpts instance is called to parse the configuration.

Parameters:

conf – a ConfigOpts instance

Raises:

DuplicateOptError, ArgsAlreadyParsedError

oslo_config.iniparser module

class oslo_config.iniparser.BaseParser

Bases: object

assignment(key, value)

Called when a full assignment is parsed.

comment(comment)

Called when a comment is parsed.

error_empty_key(line)
error_invalid_assignment(line)
error_no_section_end_bracket(line)
error_no_section_name(line)
error_unexpected_continuation(line)
lineno = 0
new_section(section)

Called when a new section is started.

parse(lineiter)
parse_exc

alias of ParseError

exception oslo_config.iniparser.ParseError(message, lineno, line)

Bases: Exception

oslo_config.sphinxconfiggen module

oslo_config.sphinxconfiggen.generate_sample(app)
oslo_config.sphinxconfiggen.setup(app)

oslo_config.sphinxext module

class oslo_config.sphinxext.ConfigDomain(env: BuildEnvironment)

Bases: Domain

oslo.config domain.

directives: dict[str, type[Directive]] = {'group': <class 'oslo_config.sphinxext.ConfigGroup'>, 'option': <class 'oslo_config.sphinxext.ConfigOption'>}

directive name -> directive class

initial_data: dict = {'groups': {}, 'options': {}}

data value for a fresh environment

label = 'oslo.config'

domain label: longer, more descriptive (used in messages)

merge_domaindata(docnames, otherdata)

Merge in data regarding docnames from a different domaindata inventory (coming from a subprocess in parallel builds).

name = 'oslo.config'

domain name: should be short, but unique

object_types: dict[str, ObjType] = {'configoption': <sphinx.domains.ObjType object>}

type (usually directive) name -> ObjType instance

resolve_xref(env, fromdocname, builder, typ, target, node, contnode)

Resolve cross-references

roles: dict[str, RoleFunction | XRefRole] = {'group': <oslo_config.sphinxext.ConfigGroupXRefRole object>, 'option': <oslo_config.sphinxext.ConfigOptXRefRole object>}

role name -> role callable

class oslo_config.sphinxext.ConfigGroup(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)

Bases: Directive

has_content = True

May the directive have content?

option_spec = {'namespace': <function unchanged>}

Mapping of option names to validator functions.

optional_arguments = 0

Number of optional arguments after the required arguments.

required_arguments = 1

Number of required directive arguments.

run()
class oslo_config.sphinxext.ConfigGroupXRefRole

Bases: XRefRole

Handles :oslo.config:group: roles pointing to configuration groups.

Called after parsing title and target text, and creating the reference node (given in refnode). This method can alter the reference node and must return a new (or the same) (title, target) tuple.

class oslo_config.sphinxext.ConfigOptXRefRole

Bases: XRefRole

Handles :oslo.config:option: roles pointing to configuration options.

Called after parsing title and target text, and creating the reference node (given in refnode). This method can alter the reference node and must return a new (or the same) (title, target) tuple.

class oslo_config.sphinxext.ConfigOption(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)

Bases: ObjectDescription

Description of a configuration option (.. option).

add_target_and_index(firstname, sig, signode)

Add cross-reference IDs and entries to self.indexnode, if applicable.

name is whatever handle_signature() returned.

handle_signature(sig, signode)

Transform an option description into RST nodes.

class oslo_config.sphinxext.ShowOptionsDirective(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)

Bases: Directive

has_content = True

May the directive have content?

option_spec = {'config-file': <function unchanged>, 'split-namespaces': <function flag>}

Mapping of option names to validator functions.

run()
oslo_config.sphinxext.setup(app)

oslo_config.types module

Type conversion and validation classes for configuration options.

Use these classes as values for the type argument to oslo_config.cfg.Opt and its subclasses.

New in version 1.3.

class oslo_config.types.Boolean(type_name='boolean value')

Bases: ConfigType

Boolean type.

Values are case insensitive and can be set using 1/0, yes/no, true/false or on/off.

Parameters:

type_name – Type name to be used in the sample config file.

Changed in version 2.7: Added type_name parameter.

FALSE_VALUES = ['false', '0', 'off', 'no']
TRUE_VALUES = ['true', '1', 'on', 'yes']
class oslo_config.types.ConfigType(type_name='unknown type')

Bases: object

NONE_DEFAULT = '<None>'
format_defaults(default, sample_default=None)

Return a list of formatted default values.

quote_trailing_and_leading_space(str_val)
class oslo_config.types.Dict(value_type=None, bounds=False, type_name='dict value')

Bases: ConfigType

Dictionary type.

Dictionary type values are key:value pairs separated by commas. The resulting value is a dictionary of these key/value pairs. Type of dictionary key is always string, but dictionary value type can be customized.

Parameters:
  • value_type – type of values in dictionary

  • bounds – if True, value should be inside “{” and “}” pair

  • type_name – Type name to be used in the sample config file.

Changed in version 2.7: Added type_name parameter.

class oslo_config.types.Float(min=None, max=None, type_name='floating point value')

Bases: Number

Float type.

Parameters:
  • min – Optional check that value is greater than or equal to min.

  • max – Optional check that value is less than or equal to max.

  • type_name – Type name to be used in the sample config file.

Changed in version 2.7: Added type_name parameter.

Changed in version 3.14: Added min and max parameters. If choices are also supplied, they must be within the range.

class oslo_config.types.HostAddress(version=None, type_name='host address value')

Bases: ConfigType

Host Address type.

Represents both valid IP addresses and valid host domain names including fully qualified domain names. Performs strict checks for both IP addresses and valid hostnames, matching the opt values to the respective types as per RFC1912.

Parameters:
  • version – defines which version should be explicitly checked (4 or 6) in case of an IP address

  • type_name – Type name to be used in the sample config file.

class oslo_config.types.HostDomain(version=None, type_name='host domain value')

Bases: HostAddress

Host Domain type.

Like HostAddress with the support of _ character.

Parameters:
  • version – defines which version should be explicitly checked (4 or 6) in case of an IP address

  • type_name – Type name to be used in the sample config file.

DOMAIN_REGEX = '(?!-)[A-Z0-9-_]{1,63}(?<!-)$'
class oslo_config.types.Hostname(type_name='hostname value')

Bases: ConfigType

Host domain name type.

A hostname refers to a valid DNS or hostname. It must not be longer than 253 characters, have a segment greater than 63 characters, nor start or end with a hyphen.

Parameters:

type_name – Type name to be used in the sample config file.

HOSTNAME_REGEX = '(?!-)[A-Z0-9-]{1,63}(?<!-)$'
class oslo_config.types.IPAddress(version=None, type_name='IP address value')

Bases: ConfigType

IP address type

Represents either ipv4 or ipv6. Without specifying version parameter both versions are checked

Parameters:
  • version – defines which version should be explicitly checked (4 or 6)

  • type_name – Type name to be used in the sample config file.

Changed in version 2.7: Added type_name parameter.

class oslo_config.types.Integer(min=None, max=None, type_name='integer value', choices=None)

Bases: Number

Integer type.

Converts value to an integer optionally doing range checking. If value is whitespace or empty string will return None.

Parameters:
  • min – Optional check that value is greater than or equal to min.

  • max – Optional check that value is less than or equal to max.

  • type_name – Type name to be used in the sample config file.

  • choices – Optional sequence of either valid values or tuples of valid values with descriptions.

Changed in version 2.4: The class now honors zero for min and max parameters.

Changed in version 2.7: Added type_name parameter.

Changed in version 3.2: Added choices parameter.

Changed in version 3.16: choices is no longer mutually exclusive with min/max. If those are supplied, all choices are verified to be within the range.

Changed in version 5.2: The choices parameter will now accept a sequence of tuples, where each tuple is of form (choice, description)

class oslo_config.types.List(item_type=None, bounds=False, type_name='list value')

Bases: ConfigType

List type.

Represent values of other (item) type, separated by commas. The resulting value is a list containing those values.

List doesn’t know if item type can also contain commas. To workaround this it tries the following: if the next part fails item validation, it appends comma and next item until validation succeeds or there is no parts left. In the later case it will signal validation error.

Parameters:
  • item_type – Type of list items. Should be an instance of ConfigType.

  • bounds – if True, value should be inside “[” and “]” pair

  • type_name – Type name to be used in the sample config file.

Changed in version 2.7: Added type_name parameter.

class oslo_config.types.MultiString(type_name='multi valued')

Bases: String

Multi-valued string.

NONE_DEFAULT = ['']
format_defaults(default, sample_default=None)

Return a list of formatted default values.

class oslo_config.types.Number(num_type, type_name, min=None, max=None, choices=None)

Bases: ConfigType

Number class, base for Integer and Float.

Parameters:
  • num_type – the type of number used for casting (i.e int, float)

  • type_name – Type name to be used in the sample config file.

  • min – Optional check that value is greater than or equal to min.

  • max – Optional check that value is less than or equal to max.

  • choices – Optional sequence of either valid values or tuples of valid values with descriptions.

New in version 3.14.

Changed in version 5.2: The choices parameter will now accept a sequence of tuples, where each tuple is of form (choice, description)

class oslo_config.types.Port(min=None, max=None, type_name='port', choices=None)

Bases: Integer

Port type

Represents a L4 Port.

Parameters:
  • min – Optional check that value is greater than or equal to min.

  • max – Optional check that value is less than or equal to max.

  • type_name – Type name to be used in the sample config file.

  • choices – Optional sequence of either valid values or tuples of valid values with descriptions.

New in version 3.16.

Changed in version 5.2: The choices parameter will now accept a sequence of tuples, where each tuple is of form (choice, description)

PORT_MAX = 65535
PORT_MIN = 0
class oslo_config.types.Range(min=None, max=None, inclusive=True, type_name='range value')

Bases: ConfigType

Range type.

Represents a range of integers. A range is identified by an integer both sides of a ‘-’ character. Negatives are allowed. A single number is also a valid range.

Parameters:
  • min – Optional check that lower bound is greater than or equal to min.

  • max – Optional check that upper bound is less than or equal to max.

  • inclusive – True if the right bound is to be included in the range.

  • type_name – Type name to be used in the sample config file.

New in version 3.18.

class oslo_config.types.String(choices=None, quotes=False, regex=None, ignore_case=False, max_length=None, type_name='string value')

Bases: ConfigType

String type.

String values do not get transformed and are returned as str objects.

Parameters:
  • choices – Optional sequence of either valid values or tuples of valid values with descriptions. Mutually exclusive with ‘regex’.

  • quotes – If True and string is enclosed with single or double quotes, will strip those quotes. Will signal error if string have quote at the beginning and no quote at the end. Turned off by default. Useful if used with container types like List.

  • regex – Optional regular expression (string or compiled regex) that the value must match on an unanchored search. Mutually exclusive with ‘choices’.

  • ignore_case – If True case differences (uppercase vs. lowercase) between ‘choices’ or ‘regex’ will be ignored; defaults to False.

  • max_length – Optional integer. If a positive value is specified, a maximum length of an option value must be less than or equal to this parameter. Otherwise no length check will be done.

  • type_name – Type name to be used in the sample config file.

Changed in version 2.1: Added regex parameter.

Changed in version 2.5: Added ignore_case parameter.

Changed in version 2.7: Added max_length parameter. Added type_name parameter.

Changed in version 5.2: The choices parameter will now accept a sequence of tuples, where each tuple is of form (choice, description)

class oslo_config.types.URI(max_length=None, schemes=None, type_name='uri value')

Bases: ConfigType

URI type

Represents URI. Value will be validated as RFC 3986.

Parameters:
  • max_length – Optional integer. If a positive value is specified, a maximum length of an option value must be less than or equal to this parameter. Otherwise no length check will be done.

  • schemes – List of valid schemes.

  • type_name – Type name to be used in the sample config file.

Changed in version 3.14: Added max_length parameter.

Changed in version 3.18: Added schemes parameter.

value

oslo_config.validator module

Configuration Validator

Uses the sample config generator configuration file to retrieve a list of all the available options in a project, then compares it to what is configured in the provided file. If there are any options set that are not defined in the project then it returns those errors.

oslo_config.validator.load_opt_data(conf)
oslo_config.validator.main()

The main function of oslo-config-validator.

oslo_config.version module

Module contents