Primary module in oslo_config.
oslo_config.cfg.
ArgsAlreadyParsedError
(msg=None)¶Bases: oslo_config.cfg.Error
Raised if a CLI opt is registered after parsing.
oslo_config.cfg.
BoolOpt
(name, **kwargs)¶Bases: oslo_config.cfg.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.
name – the option’s name
**kwargs – arbitrary keyword arguments passed to Opt
oslo_config.cfg.
ConfigDirNotFoundError
(config_dir)¶Bases: oslo_config.cfg.Error
Raised if the requested config-dir is not found.
oslo_config.cfg.
ConfigFileParseError
(config_file, msg)¶Bases: oslo_config.cfg.Error
Raised if there is an error parsing a config file.
oslo_config.cfg.
ConfigFileValueError
(msg=None)¶Bases: oslo_config.cfg.ConfigSourceValueError
Raised if a config file value does not match its opt type.
oslo_config.cfg.
ConfigFilesNotFoundError
(config_files)¶Bases: oslo_config.cfg.Error
Raised if one or more config files are not found.
oslo_config.cfg.
ConfigFilesPermissionDeniedError
(config_files)¶Bases: oslo_config.cfg.Error
Raised if one or more config files are not readable.
oslo_config.cfg.
ConfigOpts
¶Bases: collections.abc.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.
GroupAttr
(conf, group)¶Bases: collections.abc.Mapping
Helper class.
Represents the option values of a group as a mapping and attributes.
StrSubWrapper
(conf, group=None, namespace=None)¶Bases: object
Helper class.
Exposes opt values as a dict for string substitution.
SubCommandAttr
(conf, group, dest)¶Bases: object
Helper class.
Represents the name and arguments of an argparse sub-parser.
Template
(template)¶Bases: string.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 {(?P<braced>[_a-z][\\._a-z0-9]*), 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.
name – the name/dest of the opt
group – an option OptGroup object or group name
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.
name – the name/dest of the opt
group – an option OptGroup object or group name
NoSuchOptError, NoSuchGroupError
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.
name – the filename, for example ‘policy.json’
the path to a matching file, or None
get_location
(name, group=None)¶Return the location where the option is being set.
name (str) – The name of the option.
group (str) – The name of the group of the option. Defaults to
'DEFAULT'
.
LocationInfo
See also
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.
group – an option OptGroup object or group name
module_str – the name of a module to import
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.
name – the name/dest of the opt
module_str – the name of a module to import
group – an option OptGroup object or group name
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.
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.
{(None or ‘group’, ‘optname’): (old_value, new_value), … }
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
file – the File object (if None, output is on sys.stdout)
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
file – the File object (if None, output is on sys.stdout)
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.
opt – an instance of an Opt sub-class
group – an optional OptGroup object or group name
False if the opt was already registered, True otherwise
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.
group – an OptGroup object
register_mutate_hook
(hook)¶Registers a hook to be called by mutate_config_files.
hook – a function accepting this ConfigOpts object and a dict of config mutations, as returned by mutate_config_files.
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.
opt – an instance of an Opt sub-class
group – an optional OptGroup object or group name
cli – whether this is a CLI option
False if the opt was already registered, True otherwise
DuplicateOptError
register_opts
(opts, group=None)¶Register multiple option schemas at once.
reload_config_files
()¶Reload configure files and parse all options
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.
name – the name/dest of the opt
default – the default value
group – an option OptGroup object or group name
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.
name – the name/dest of the opt
override – the override value
group – an option OptGroup object or group name
NoSuchOptError, NoSuchGroupError
unregister_opt
(opt, group=None)¶Unregister an option.
opt – an Opt object
group – an optional OptGroup object or group name
ArgsAlreadyParsedError, NoSuchGroupError
unregister_opts
(opts, group=None)¶Unregister multiple CLI option schemas at once.
oslo_config.cfg.
ConfigParser
(filename, sections)¶Bases: oslo_config.iniparser.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)¶oslo_config.cfg.
ConfigSourceValueError
(msg=None)¶Bases: oslo_config.cfg.Error
, ValueError
Raised if a config source value does not match its opt type.
oslo_config.cfg.
DefaultValueError
(msg=None)¶Bases: oslo_config.cfg.Error
, ValueError
Raised if a default config type does not fit the opt type.
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.
oslo_config.cfg.
DictOpt
(name, **kwargs)¶Bases: oslo_config.cfg.Opt
Option with Dict(String) type
Option with type
oslo_config.types.Dict
name – the option’s name
**kwargs – arbitrary keyword arguments passed to Opt
New in version 1.2.
oslo_config.cfg.
DuplicateOptError
(opt_name)¶Bases: oslo_config.cfg.Error
Raised if multiple opts with the same name are registered.
oslo_config.cfg.
Error
(msg=None)¶Bases: Exception
Base class for cfg exceptions.
oslo_config.cfg.
FloatOpt
(name, min=None, max=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Option with Float type
Option with type
oslo_config.types.Float
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.
oslo_config.cfg.
HostAddressOpt
(name, version=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Option for either an IP or a hostname.
Accepts valid hostnames and valid IP addresses.
Option with type
oslo_config.types.HostAddress
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.
oslo_config.cfg.
HostnameOpt
(name, **kwargs)¶Bases: oslo_config.cfg.Opt
Option for a hostname. Only accepts valid hostnames.
Option with type
oslo_config.types.Hostname
name – the option’s name
**kwargs – arbitrary keyword arguments passed to Opt
New in version 3.8.
oslo_config.cfg.
IPOpt
(name, version=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Opt with IPAddress type
Option with type
oslo_config.types.IPAddress
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.
oslo_config.cfg.
IntOpt
(name, min=None, max=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Option with Integer type
Option with type
oslo_config.types.Integer
name – the option’s name
min – minimum value the integer can take
max – maximum value the integer can take
**kwargs – arbitrary keyword arguments passed to Opt
Changed in version 1.15: Added min and max parameters.
oslo_config.cfg.
ListOpt
(name, item_type=None, bounds=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Option with List(String) type
Option with type
oslo_config.types.List
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.
oslo_config.cfg.
LocationInfo
(location, detail)¶Bases: tuple
detail
¶Alias for field number 1
location
¶Alias for field number 0
oslo_config.cfg.
Locations
(num, is_user_controlled)¶Bases: enum.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)¶oslo_config.cfg.
MultiOpt
(name, item_type, **kwargs)¶Bases: oslo_config.cfg.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.
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¶oslo_config.cfg.
MultiStrOpt
(name, **kwargs)¶Bases: oslo_config.cfg.MultiOpt
MultiOpt with a MultiString item_type
.
MultiOpt with a default oslo_config.types.MultiString
item
type.
name – the option’s name
**kwargs – arbitrary keyword arguments passed to MultiOpt
oslo_config.cfg.
NoSuchGroupError
(group_name)¶Bases: oslo_config.cfg.Error
Raised if a group which doesn’t exist is referenced.
oslo_config.cfg.
NoSuchOptError
(opt_name, group=None)¶Bases: oslo_config.cfg.Error
, AttributeError
Raised if an opt which doesn’t exist is referenced.
oslo_config.cfg.
NotInitializedError
(msg=None)¶Bases: oslo_config.cfg.Error
Raised if parser is not initialized yet.
oslo_config.cfg.
Opt
(name, type=None, dest=None, short=None, default=None, positional=False, metavar=None, help=None, secret=False, required=False, 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.
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¶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
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.
oslo_config.cfg.
ParseError
(msg, lineno, line, filename)¶oslo_config.cfg.
PortOpt
(name, min=None, max=None, choices=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Option for a TCP/IP port number. Ports can range from 0 to 65535.
Option with type
oslo_config.types.Integer
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)
oslo_config.cfg.
RequiredOptError
(opt_name, group=None)¶Bases: oslo_config.cfg.Error
Raised if an option is required but no value is supplied by the user.
oslo_config.cfg.
StrOpt
(name, choices=None, quotes=None, regex=None, ignore_case=False, max_length=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Option with String type
Option with type
oslo_config.types.String
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)
oslo_config.cfg.
SubCommandOpt
(name, dest=None, handler=None, title=None, description=None, help=None)¶Bases: oslo_config.cfg.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.
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
oslo_config.cfg.
TemplateSubstitutionError
(msg=None)¶Bases: oslo_config.cfg.Error
Raised if an error occurs substituting a variable in an opt value.
oslo_config.cfg.
URIOpt
(name, max_length=None, schemes=None, **kwargs)¶Bases: oslo_config.cfg.Opt
Opt with URI type
Option with type
oslo_config.types.URI
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.
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.
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)¶DEPRECATED: This module is deprecated and scheduled for removal in the U cycle.
There are three use cases for the ConfigFilter class:
Help enforce that a given module does not access options registered by another module, without first declaring those cross-module dependencies using import_opt().
Prevent private configuration opts from being visible to modules other than the one which registered it.
Limit the options on a Cfg object that can be accessed.
New in version 1.4.
When using the global cfg.CONF object, it is quite common for a module to require the existence of configuration options registered by other modules.
For example, if module ‘foo’ registers the ‘blaa’ option and the module ‘bar’ uses the ‘blaa’ option then ‘bar’ might do:
import foo
print(CONF.blaa)
However, it’s completely non-obvious why foo is being imported (is it unused, can we remove the import) and where the ‘blaa’ option comes from.
The CONF.import_opt() method allows such a dependency to be explicitly declared:
CONF.import_opt('blaa', 'foo')
print(CONF.blaa)
However, import_opt() has a weakness - if ‘bar’ imports ‘foo’ using the import builtin and doesn’t use import_opt() to import ‘blaa’, then ‘blaa’ can still be used without problems. Similarly, where multiple options are registered a module imported via import_opt(), a lazy programmer can get away with only declaring a dependency on a single option.
The ConfigFilter class provides a way to ensure that options are not available unless they have been registered in the module or imported using import_opt() for example with:
CONF = ConfigFilter(cfg.CONF)
CONF.import_opt('blaa', 'foo')
print(CONF.blaa)
no other options other than ‘blaa’ are available via CONF.
Libraries which register configuration options typically do not want users of the library API to access those configuration options. If API users do access private configuration options, those users will be disrupted if and when a configuration option is renamed. In other words, one does not typically wish for the name of the private config options to be part of the public API.
The ConfigFilter class provides a way for a library to register options such that they are not visible via the ConfigOpts instance which the API user supplies to the library. For example:
from __future__ import print_function
from oslo_config.cfg import *
from oslo_config.cfgfilter import *
class Widget(object):
def __init__(self, conf):
self.conf = conf
self._private_conf = ConfigFilter(self.conf)
self._private_conf.register_opt(StrOpt('foo'))
@property
def foo(self):
return self._private_conf.foo
conf = ConfigOpts()
widget = Widget(conf)
print(widget.foo)
print(conf.foo) # raises NoSuchOptError
It may be required that when passing a CONF object to other functions we want to filter that the receiving code is only able to access a restricted subset of the options that are available on the CONF object. This is essentially a more general case of the Private Configuration Options and Cross-Module Options whereby we expose an option that is already present on the underlying CONF object without providing any means to load it if not present.
So given a CONF object with options defined:
CONF.register_opt(StrOpt('foo'))
CONF.register_opt(StrOpt('bar'))
we can expose options such that only those options are present:
restricted_conf = CfgFilter(CONF)
restricted_conf.expose_opt('foo')
print(restricted_conf.foo)
print(restricted_conf.bar) # raises NoSuchOptError
oslo_config.cfgfilter.
CliOptRegisteredError
(msg=None)¶Bases: oslo_config.cfg.Error
Raised when registering cli opt not in original ConfigOpts.
New in version 1.12.
oslo_config.cfgfilter.
ConfigFilter
(conf)¶Bases: collections.abc.Mapping
A helper class which wraps a ConfigOpts object.
ConfigFilter enforces the explicit declaration of dependencies on external options and allows private options which are not registered with the wrapped Configopts object.
GroupAttr
(conf, group)¶Bases: collections.abc.Mapping
Helper class to wrap a group object.
Represents the option values of a group as a mapping and attributes.
expose_group
(group)¶Expose all option from a group in the underlying conf object.
This allows an object that has already been imported or used from the base conf object to be seen from the filter object.
group – an option OptGroup object or group name
expose_opt
(opt_name, group=None)¶Expose an option from the underlying conf object.
This allows an object that has already been imported or used from the base conf object to be seen from the filter object.
opt_name – the name/dest of the opt
group – an option OptGroup object or group name
import_group
(group, module_str)¶Import an option group from a module.
Note that this allows access to all options registered with the group whether or not those options were registered by the given module.
group – an option OptGroup object or group name
module_str – the name of a module to import
ImportError, NoSuchGroupError
import_opt
(opt_name, module_str, group=None)¶Import an option definition from a module.
name – the name/dest of the opt
module_str – the name of a module to import
group – an option OptGroup object or group name
NoSuchOptError, NoSuchGroupError
register_cli_opt
(opt, group=None)¶Register a CLI option schema.
opt – an instance of an Opt sub-class
group – an optional OptGroup object or group name
False if the opt was already register, True otherwise
DuplicateOptError, ArgsAlreadyParsedError
register_cli_opts
(opts, group=None)¶Register multiple CLI option schemas at once.
register_group
(group)¶Register an option group.
group – an OptGroup object
register_opt
(opt, group=None)¶Register an option schema.
opt – an instance of an Opt sub-class
group – an optional OptGroup object or group name
False if the opt was already registered, True otherwise
DuplicateOptError
register_opts
(opts, group=None)¶Register multiple option schemas at once.
oslo_config.fixture.
Config
(conf=<oslo_config.cfg.ConfigOpts object>)¶Bases: fixtures.fixture.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).
MultipleExceptions if _setUp fails. The last exception captured within the MultipleExceptions will be a SetupError exception.
None.
The recommendation to override setUp has been reversed - before 1.3, setUp() should be overridden, now it should not be.
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()
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.
conf – a ConfigOpts instance containing the generator’s configuration
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.
conf – a ConfigOpts instance
DuplicateOptError, ArgsAlreadyParsedError
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
oslo_config.iniparser.
ParseError
(message, lineno, line)¶Bases: Exception
oslo_config.sphinxconfiggen.
generate_sample
(app)¶oslo_config.sphinxconfiggen.
setup
(app)¶oslo_config.sphinxext.
ConfigDomain
(env: BuildEnvironment)¶Bases: sphinx.domains.Domain
oslo.config domain.
directives
= {'group': <class 'oslo_config.sphinxext.ConfigGroup'>, 'option': <class 'oslo_config.sphinxext.ConfigOption'>}¶initial_data
= {'groups': {}, 'options': {}}¶label
= 'oslo.config'¶name
= 'oslo.config'¶object_types
= {'configoption': <sphinx.domains.ObjType object>}¶resolve_xref
(env, fromdocname, builder, typ, target, node, contnode)¶Resolve cross-references
roles
= {'group': <oslo_config.sphinxext.ConfigGroupXRefRole object>, 'option': <oslo_config.sphinxext.ConfigOptXRefRole object>}¶oslo_config.sphinxext.
ConfigGroup
(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)¶Bases: docutils.parsers.rst.Directive
has_content
= True¶option_spec
= {'namespace': <function unchanged>}¶optional_arguments
= 0¶required_arguments
= 1¶run
()¶oslo_config.sphinxext.
ConfigGroupXRefRole
¶Bases: sphinx.roles.XRefRole
Handles :oslo.config:group: roles pointing to configuration groups.
process_link
(env, refnode, has_explicit_title, title, target)¶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.
oslo_config.sphinxext.
ConfigOptXRefRole
¶Bases: sphinx.roles.XRefRole
Handles :oslo.config:option: roles pointing to configuration options.
process_link
(env, refnode, has_explicit_title, title, target)¶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.
oslo_config.sphinxext.
ConfigOption
(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)¶Bases: sphinx.directives.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.
oslo_config.sphinxext.
ShowOptionsDirective
(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine)¶Bases: docutils.parsers.rst.Directive
has_content
= True¶option_spec
= {'config-file': <function unchanged>, 'split-namespaces': <function flag>}¶run
()¶oslo_config.sphinxext.
setup
(app)¶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.
oslo_config.types.
Boolean
(type_name='boolean value')¶Bases: oslo_config.types.ConfigType
Boolean type.
Values are case insensitive and can be set using 1/0, yes/no, true/false or on/off.
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']¶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)¶oslo_config.types.
Dict
(value_type=None, bounds=False, type_name='dict value')¶Bases: oslo_config.types.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.
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.
oslo_config.types.
Float
(min=None, max=None, type_name='floating point value')¶Bases: oslo_config.types.Number
Float type.
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.
oslo_config.types.
HostAddress
(version=None, type_name='host address value')¶Bases: oslo_config.types.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.
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.
oslo_config.types.
HostDomain
(version=None, type_name='host address value')¶Bases: oslo_config.types.HostAddress
Host Domain type.
Like HostAddress with the support of _ character.
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}(?<!-)$'¶oslo_config.types.
Hostname
(type_name='hostname value')¶Bases: oslo_config.types.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.
type_name – Type name to be used in the sample config file.
HOSTNAME_REGEX
= '(?!-)[A-Z0-9-]{1,63}(?<!-)$'¶oslo_config.types.
IPAddress
(version=None, type_name='IP address value')¶Bases: oslo_config.types.ConfigType
IP address type
Represents either ipv4 or ipv6. Without specifying version parameter both versions are checked
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.
oslo_config.types.
Integer
(min=None, max=None, type_name='integer value', choices=None)¶Bases: oslo_config.types.Number
Integer type.
Converts value to an integer optionally doing range checking. If value is whitespace or empty string will return None.
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)
oslo_config.types.
List
(item_type=None, bounds=False, type_name='list value')¶Bases: oslo_config.types.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.
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.
oslo_config.types.
MultiString
(type_name='multi valued')¶Bases: oslo_config.types.String
Multi-valued string.
NONE_DEFAULT
= ['']¶format_defaults
(default, sample_default=None)¶Return a list of formatted default values.
oslo_config.types.
Number
(num_type, type_name, min=None, max=None, choices=None)¶Bases: oslo_config.types.ConfigType
Number class, base for Integer and Float.
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)
oslo_config.types.
Port
(min=None, max=None, type_name='port', choices=None)¶Bases: oslo_config.types.Integer
Port type
Represents a L4 Port.
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¶oslo_config.types.
Range
(min=None, max=None, inclusive=True, type_name='range value')¶Bases: oslo_config.types.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.
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.
oslo_config.types.
String
(choices=None, quotes=False, regex=None, ignore_case=False, max_length=None, type_name='string value')¶Bases: oslo_config.types.ConfigType
String type.
String values do not get transformed and are returned as str objects.
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)
oslo_config.types.
URI
(max_length=None, schemes=None, type_name='uri value')¶Bases: oslo_config.types.ConfigType
URI type
Represents URI. Value will be validated as RFC 3986.
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
¶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.
Except where otherwise noted, this document is licensed under Creative Commons Attribution 3.0 License. See all OpenStack Legal Documents.