Table Of Contents

Previous topic

Fake Drivers

This Page

Psst... hey. You're reading the latest content, but it might be out of sync with code. You can read Cinder 2011.2 docs or all OpenStack docs too.

Common and Misc Libraries

Libraries common throughout Cinder or just ones that haven’t been categorized very well yet.

The cinder.adminclient Module

The cinder.context Module

RequestContext: context for requests that persist through all of cinder.

class RequestContext(user_id, project_id, is_admin=None, read_deleted='no', roles=None, remote_address=None, timestamp=None, request_id=None, auth_token=None, overwrite=True, quota_class=None, **kwargs)

Bases: object

Security context and request information.

Represents the user taking a given action within the system.

RequestContext.elevated(read_deleted=None, overwrite=False)

Return a version of this context with admin flag set.

classmethod RequestContext.from_dict(values)
RequestContext.read_deleted
RequestContext.to_dict()
RequestContext.update_store()
generate_request_id()
get_admin_context(read_deleted='no')

The cinder.exception Module

Cinder base exception handling.

Includes decorator for re-raising Cinder-type exceptions.

SHOULD include dedicated exception logging.

exception AdminRequired(message=None, **kwargs)

Bases: cinder.exception.NotAuthorized

exception BadHTTPResponseStatus(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception CinderException(message=None, **kwargs)

Bases: exceptions.Exception

Base Cinder Exception

To correctly use this class, inherit from it and define a ‘message’ property. That message will get printf’d with the keyword arguments provided to the constructor.

exception ClassNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ConfigNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ConvertedException(code=0, title='', explanation='')

Bases: webob.exc.WSGIHTTPException

exception DBError(inner_exception=None)

Bases: cinder.exception.Error

Wraps an implementation specific exception.

exception DeprecatedConfig(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception DiskNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception Duplicate(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception DuplicateSfVolumeNames(message=None, **kwargs)

Bases: cinder.exception.Duplicate

exception Error

Bases: exceptions.Exception

exception FailedCmdWithDump(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception FileNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception GlanceConnectionFailed(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception HostBinaryNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception HostNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ISCSITargetCreateFailed(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception ISCSITargetNotFoundForVolume(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ISCSITargetRemoveFailed(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception ImageNotAuthorized(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception ImageNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ImageUnacceptable(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InstanceNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception Invalid(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception InvalidContentType(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidImageRef(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidInput(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidParameterValue(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidPortRange(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidQuotaValue(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidRequest(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidReservationExpiration(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidResults(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidSnapshot(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidUUID(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidUnicodeParameter(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidVolume(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception InvalidVolumeType(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception KeyPairExists(message=None, **kwargs)

Bases: cinder.exception.Duplicate

exception MalformedRequestBody(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception MalformedResponse(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception MigrationError(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception MigrationNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception MigrationNotFoundByStatus(message=None, **kwargs)

Bases: cinder.exception.MigrationNotFound

exception NfsException(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception NfsNoSharesMounted(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception NfsNoSuitableShareFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception NoValidHost(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception NotAllowed(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception NotAuthorized(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception NotFound(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception OverQuota(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception PasteAppNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception PersistentVolumeFileNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception PolicyNotAuthorized(message=None, **kwargs)

Bases: cinder.exception.NotAuthorized

exception ProcessExecutionError(stdout=None, stderr=None, exit_code=None, cmd=None, description=None)

Bases: exceptions.IOError

exception ProjectQuotaNotFound(message=None, **kwargs)

Bases: cinder.exception.QuotaNotFound

exception QuotaClassNotFound(message=None, **kwargs)

Bases: cinder.exception.QuotaNotFound

exception QuotaError(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception QuotaNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception QuotaResourceUnknown(message=None, **kwargs)

Bases: cinder.exception.QuotaNotFound

exception QuotaUsageNotFound(message=None, **kwargs)

Bases: cinder.exception.QuotaNotFound

exception ReservationNotFound(message=None, **kwargs)

Bases: cinder.exception.QuotaNotFound

exception ServiceNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ServiceUnavailable(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception SfAccountNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception SfJsonEncodeFailure(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception SnapshotIsBusy(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception SnapshotNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception SolidFireAPIDataException(message=None, **kwargs)

Bases: cinder.exception.SolidFireAPIException

exception SolidFireAPIException(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception UnknownCmd(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception VolumeAttached(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception VolumeBackendAPIException(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception VolumeIsBusy(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception VolumeLimitExceeded(message=None, **kwargs)

Bases: cinder.exception.QuotaError

exception VolumeMetadataNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception VolumeNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception VolumeNotFoundForInstance(message=None, **kwargs)

Bases: cinder.exception.VolumeNotFound

exception VolumeSizeExceedsAvailableQuota(message=None, **kwargs)

Bases: cinder.exception.QuotaError

exception VolumeSizeExceedsQuota(message=None, **kwargs)

Bases: cinder.exception.QuotaError

exception VolumeTypeCreateFailed(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception VolumeTypeExists(message=None, **kwargs)

Bases: cinder.exception.Duplicate

exception VolumeTypeExtraSpecsNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception VolumeTypeNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception VolumeTypeNotFoundByName(message=None, **kwargs)

Bases: cinder.exception.VolumeTypeNotFound

exception WillNotSchedule(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception ZadaraAttachmentsNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ZadaraInvalidAttachmentInfo(message=None, **kwargs)

Bases: cinder.exception.Invalid

exception ZadaraServerCreateFailure(message=None, **kwargs)

Bases: cinder.exception.CinderException

exception ZadaraServerNotFound(message=None, **kwargs)

Bases: cinder.exception.NotFound

exception ZadaraVPSANoActiveController(message=None, **kwargs)

Bases: cinder.exception.CinderException

wrap_db_error(f)

The cinder.flags Module

Command-line flag library.

Emulates gflags by wrapping cfg.ConfigOpts.

The idea is to move fully to cfg eventually, and this wrapper is a stepping stone.

DECLARE(name, module_string, flag_values=<cinder.openstack.common.cfg.CommonConfigOpts object at 0x9f18d6c>)
exception UnrecognizedFlag

Bases: exceptions.Exception

parse_args(argv, default_config_files=None)

The cinder.process Module

The cinder.rpc Module

The cinder.server Module

The cinder.test Module

The cinder.utils Module

Utilities and helper functions.

class LazyPluggable(pivot, **backends)

Bases: object

A pluggable backend loaded lazily based on some value.

class LoopingCall(f=None, *args, **kw)

Bases: object

LoopingCall.start(interval, initial_delay=None)
LoopingCall.stop()
LoopingCall.wait()
exception LoopingCallDone(retvalue=True)

Bases: exceptions.Exception

Exception to break out and stop a LoopingCall.

The poll-function passed to LoopingCall can raise this exception to break out of the loop normally. This is somewhat analogous to StopIteration.

An optional return-value can be included as the argument to the exception; this return-value will be returned by LoopingCall.wait()

class UndoManager

Bases: object

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

UndoManager.rollback_and_reraise(msg=None, **kwargs)

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

Note

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

UndoManager.undo_with(undo_func)
bool_from_str(val)

Convert a string representation of a bool into a bool value

check_isinstance(obj, cls)

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

cinderdir()
convert_to_list_dict(lst, label)

Convert a value or list into a list of dicts

debug(arg)
delete_if_exists(pathname)

delete a file, but ignore file not found error

ensure_tree(path)

Create a directory (and any ancestor directories required)

Parameters:path – Directory to create
execute(*cmd, **kwargs)

Helper method to execute command with optional retry.

If you add a run_as_root=True command, don’t forget to add the corresponding filter to etc/cinder/rootwrap.d !

Parameters:
  • cmd – Passed to subprocess.Popen.
  • process_input – Send to opened process.
  • check_exit_code – Single bool, int, or list of allowed exit codes. Defaults to [0]. Raise exception.ProcessExecutionError unless program exits with one of these code.
  • delay_on_retry – True | False. Defaults to True. If set to True, wait a short amount of time before retrying.
  • attempts – How many times to retry cmd.
  • run_as_root – True | False. Defaults to False. If set to True, the command is prefixed by the command specified in the root_helper FLAG.
Raises:
  • exception.Error – on receiving unknown arguments
  • exception.ProcessExecutionError
Returns:

a tuple, (stdout, stderr) from the spawned process, or None if the command fails.

fetchfile(url, target)
file_open(*args, **kwargs)

Open file

see built-in file() documentation for more details

Note: The reason this is kept in a separate module is to easily
be able to provide a stub module that doesn’t alter system state at all (for unit tests)
find_config(config_path)

Find a configuration file using the given hint.

Parameters:config_path – Full or relative path to the config.
Returns:Full path of the config, if it exists.
Raises :cinder.exception.ConfigNotFound
flatten_dict(dict_, flattened=None)

Recursively flatten a nested dictionary.

gen_uuid()
generate_glance_url()

Generate the URL to glance.

generate_mac_address()

Generate an Ethernet MAC address.

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

Generate a random password from the supplied symbol groups.

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

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

generate_uid(topic, size=8)
get_from_path(items, path)

Returns a list of items matching the specified path.

Takes an XPath-like expression e.g. prop1/prop2/prop3, and for each item in items, looks up items[prop1][prop2][prop3]. Like XPath, if any of the intermediate results are lists it will treat each list item individually. A ‘None’ in items or any child expressions will be ignored, this function will not throw because of None (anywhere) in items. The returned list will contain no None values.

get_my_linklocal(interface)
hash_file(file_like_object)

Generate a hash for the contents of a file.

is_uuid_like(val)

For our purposes, a UUID is a string in canonical form:

aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa

is_valid_boolstr(val)

Check if the provided string is a valid bool string or not.

is_valid_ipv4(address)

valid the address strictly as per format xxx.xxx.xxx.xxx. where xxx is a value between 0 and 255.

last_completed_audit_period(unit=None)

This method gives you the most recently completed audit period.

arguments:
units: string, one of ‘hour’, ‘day’, ‘month’, ‘year’
Periods normally begin at the beginning (UTC) of the period unit (So a ‘day’ period begins at midnight UTC, a ‘month’ unit on the 1st, a ‘year’ on Jan, 1) unit string may be appended with an optional offset like so: 'day@18‘ This will begin the period at 18:00 UTC. 'month@15‘ starts a monthly period on the 15th, and year@3 begins a yearly one on March 1st.
returns: 2 tuple of datetimes (begin, end)
The begin timestamp of this audit period is the same as the end of the previous.
last_octet(address)
logging_error(*args, **kwds)

Catches exception, write message to the log, re-raise. This is a common refinement of save_and_reraise that writes a specific message to the log.

make_dev_path(dev, partition=None, base='/dev')

Return a path to a particular device.

>>> make_dev_path('xvdc')
/dev/xvdc
>>> make_dev_path('xvdc', 1)
/dev/xvdc1
map_dict_keys(dict_, key_map)

Return a dict in which the dictionaries keys are mapped to new keys.

monkey_patch()

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

Parameters of the decorator is as follows. (See cinder.openstack.common.notifier.api.notify_decorator)

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

parse_mailmap(mailmap='.mailmap')
partition_dict(dict_, keys)

Return two dicts, one with keys the other with everything else.

read_cached_file(filename, cache_info, reload_func=None)

Read from a file if it has been modified.

Parameters:
  • cache_info – dictionary to hold opaque cache.
  • reload_func – optional function to be called with data when file is reloaded due to a modification.
Returns:

data from file

read_file_as_root(file_path)

Secure helper to read file as root.

remove_path_on_error(*args, **kwds)

Protect code that wants to operate on PATH atomically. Any exception will cause PATH to be removed.

sanitize_hostname(hostname)

Return a hostname which conforms to RFC-952 and RFC-1123 specs.

service_is_up(service)

Check whether a service is up based on last heartbeat.

ssh_execute(ssh, cmd, process_input=None, addl_env=None, check_exit_code=True)
str_dict_replace(s, mapping)
strcmp_const_time(s1, s2)

Constant-time string comparison.

Params s1:the first string
Params s2:the second string
Returns:True if the strings are equal.

This function takes two strings and compares them. It is intended to be used when doing a comparison for authentication purposes to help guard against timing attacks.

subset_dict(dict_, keys)

Return a dict that only contains a subset of keys.

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

Temporarily chown a path.

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

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

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

with temporary_mutation(context, read_deleted=”yes”):
do_something_that_needed_deleted_objects()
timefunc(func)

Decorator that logs how long a particular function took to execute

total_seconds(td)

Local total_seconds implementation for compatibility with python 2.6

trycmd(*args, **kwargs)

A wrapper around execute() to more easily handle warnings and errors.

Returns an (out, err) tuple of strings containing the output of the command’s stdout and stderr. If ‘err’ is not empty then the command can be considered to have failed.

:discard_warnings True | False. Defaults to False. If set to True,
then for succeeding commands, stderr is cleared
utf8(value)

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

Code is directly from the utf8 function in http://github.com/facebook/tornado/blob/master/tornado/escape.py

walk_class_hierarchy(clazz, encountered=None)

Walk class hierarchy, yielding most derived classes first

xhtml_escape(value)

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

The cinder.validate Module

The cinder.wsgi Module

Utility methods for working with WSGI servers.

class Application

Bases: object

Base WSGI application wrapper. Subclasses need to implement __call__.

classmethod Application.factory(global_config, **local_config)

Used for paste app factories in paste.deploy config files.

Any local configuration (that is, values under the [app:APPNAME] section of the paste config) will be passed into the __init__ method as kwargs.

A hypothetical configuration would look like:

[app:wadl] latest_version = 1.3 paste.app_factory = cinder.api.fancy_api:Wadl.factory

which would result in a call to the Wadl class as

import cinder.api.fancy_api fancy_api.Wadl(latest_version=‘1.3’)

You could of course re-implement the factory method in subclasses, but using the kwarg passing it shouldn’t be necessary.

class Debug(application)

Bases: cinder.wsgi.Middleware

Helper class for debugging a WSGI application.

Can be inserted into any WSGI application chain to get information about the request and response.

static Debug.print_generator(app_iter)

Iterator that prints the contents of a wrapper string.

class Loader(config_path=None)

Bases: object

Used to load WSGI applications from paste configurations.

Loader.load_app(name)

Return the paste URLMap wrapped WSGI application.

Parameters:name – Name of the application to load.
Returns:Paste URLMap object wrapping the requested application.
Raises :cinder.exception.PasteAppNotFound
class Middleware(application)

Bases: cinder.wsgi.Application

Base WSGI middleware.

These classes require an application to be initialized that will be called next. By default the middleware will simply call its wrapped app, or you can override __call__ to customize its behavior.

classmethod Middleware.factory(global_config, **local_config)

Used for paste app factories in paste.deploy config files.

Any local configuration (that is, values under the [filter:APPNAME] section of the paste config) will be passed into the __init__ method as kwargs.

A hypothetical configuration would look like:

[filter:analytics] redis_host = 127.0.0.1 paste.filter_factory = cinder.api.analytics:Analytics.factory

which would result in a call to the Analytics class as

import cinder.api.analytics analytics.Analytics(app_from_paste, redis_host=‘127.0.0.1’)

You could of course re-implement the factory method in subclasses, but using the kwarg passing it shouldn’t be necessary.

Middleware.process_request(req)

Called on each request.

If this returns None, the next application down the stack will be executed. If it returns a response then that response will be returned and execution will stop here.

Middleware.process_response(response)

Do whatever you’d like to the response.

class Request(environ, charset=(No Default), unicode_errors=(No Default), decode_param_names=(No Default), **kw)

Bases: webob.request.Request

class Router(mapper)

Bases: object

WSGI middleware that maps incoming requests to WSGI apps.

class Server(name, app, host=None, port=None, pool_size=None, protocol=<class eventlet.wsgi.HttpProtocol at 0xa0a9bfc>)

Bases: object

Server class to manage a WSGI server, serving a WSGI application.

Server.start(backlog=128)

Start serving a WSGI application.

Parameters:backlog – Maximum number of queued connections.
Returns:None
Raises :cinder.exception.InvalidInput
Server.stop()

Stop this server.

This is not a very nice action, as currently the method by which a server is stopped is by killing its eventlet.

Returns:None
Server.wait()

Block, until the server has stopped.

Waits on the server’s eventlet to finish, then returns.

Returns:None

Tests

The declare_flags Module

The fake_flags Module

The flags_unittest Module

The process_unittest Module

The real_flags Module

The rpc_unittest Module

The runtime_flags Module

The validator_unittest Module