glance.common package

Submodules

glance.common.auth module

This auth module is intended to allow OpenStack client-tools to select from a variety of authentication strategies, including NoAuth (the default), and Keystone (an identity management system).

> auth_plugin = AuthPlugin(creds)

> auth_plugin.authenticate()

> auth_plugin.auth_token abcdefg

> auth_plugin.management_url http://service_endpoint/

class glance.common.auth.BaseStrategy[source]

Bases: object

authenticate()[source]
is_authenticated[source]
strategy[source]
class glance.common.auth.KeystoneStrategy(creds, insecure=False, configure_via_auth=True)[source]

Bases: glance.common.auth.BaseStrategy

MAX_REDIRECTS = 10
authenticate()[source]

Authenticate with the Keystone service.

There are a few scenarios to consider here:

  1. Which version of Keystone are we using? v1 which uses headers to pass the credentials, or v2 which uses a JSON encoded request body?
  2. Keystone may respond back with a redirection using a 305 status code.
  3. We may attempt a v1 auth when v2 is what’s called for. In this case, we rewrite the url to contain /v2.0/ and retry using the v2 protocol.
check_auth_params()[source]
is_authenticated[source]
strategy[source]
class glance.common.auth.NoAuthStrategy[source]

Bases: glance.common.auth.BaseStrategy

authenticate()[source]
is_authenticated[source]
strategy[source]
glance.common.auth.get_endpoint(service_catalog, service_type='image', endpoint_region=None, endpoint_type='publicURL')[source]

Select an endpoint from the service catalog

We search the full service catalog for services matching both type and region. If the client supplied no region then any ‘image’ endpoint is considered a match. There must be one – and only one – successful match in the catalog, otherwise we will raise an exception.

glance.common.auth.get_plugin_from_strategy(strategy, creds=None, insecure=False, configure_via_auth=True)[source]

glance.common.client module

class glance.common.client.BaseClient(host, port=None, timeout=None, use_ssl=False, auth_token=None, creds=None, doc_root=None, key_file=None, cert_file=None, ca_file=None, insecure=False, configure_via_auth=True)[source]

Bases: object

A base client class

DEFAULT_CA_FILE_PATH = '/etc/ssl/certs/ca-certificates.crt:/etc/pki/tls/certs/ca-bundle.crt:/etc/ssl/ca-bundle.pem:/etc/ssl/cert.pem'
DEFAULT_DOC_ROOT = None
DEFAULT_PORT = 80
OK_RESPONSE_CODES = (200, 201, 202, 204)
REDIRECT_RESPONSE_CODES = (301, 302, 303, 305, 307)
configure_from_url(url)[source]

Setups the connection based on the given url.

The form is:

<http|https>://<host>:port/doc_root
do_request(*args, **kwargs)[source]

Make a request, returning an HTTP response object.

Parameters:
  • method – HTTP verb (GET, POST, PUT, etc.)
  • action – Requested path to append to self.doc_root
  • body – Data to send in the body of the request
  • headers – Headers to send with the request
  • params – Key/value pairs to use in query string
Returns:

HTTP response object

get_connect_kwargs()[source]
get_connection_type()[source]

Returns the proper connection type

get_status_code(response)[source]

Returns the integer status code from the response, which can be either a Webob.Response (used in testing) or httplib.Response

make_auth_plugin(creds, insecure)[source]

Returns an instantiated authentication plugin.

class glance.common.client.HTTPSClientAuthConnection(host, port, key_file, cert_file, ca_file, timeout=None, insecure=False)[source]

Bases: httplib.HTTPSConnection

Class to make a HTTPS connection, with support for full client-based SSL Authentication

:see http://code.activestate.com/recipes/
577548-https-httplib-client-connection-with-certificate-v/
connect()[source]

Connect to a host on a given (SSL) port. If ca_file is pointing somewhere, use it to check Server Certificate.

Redefined/copied and extended from httplib.py:1105 (Python 2.6.x). This is needed to pass cert_reqs=ssl.CERT_REQUIRED as parameter to ssl.wrap_socket(), which forces SSL to check server certificate against our client certificate.

glance.common.client.handle_redirects(func)[source]

Wrap the _do_request function to handle HTTP redirects.

glance.common.client.handle_unauthenticated(func)[source]

Wrap a function to re-authenticate and retry.

glance.common.config module

Routines for configuring Glance

glance.common.config.load_paste_app(app_name, flavor=None, conf_file=None)[source]

Builds and returns a WSGI app from a paste config file.

We assume the last config file specified in the supplied ConfigOpts object is the paste config file, if conf_file is None.

Parameters:
  • app_name – name of the application to load
  • flavor – name of the variant of the application to load
  • conf_file – path to the paste config file
Raises:

RuntimeError when config file cannot be located or application cannot be loaded from config file

glance.common.config.parse_args(args=None, usage=None, default_config_files=None)[source]
glance.common.config.parse_cache_args(args=None)[source]
glance.common.config.set_config_defaults()[source]

This method updates all configuration default values.

glance.common.config.set_cors_middleware_defaults()[source]

Update default configuration options for oslo.middleware.

glance.common.crypt module

Routines for URL-safe encrypting/decrypting

glance.common.crypt.urlsafe_decrypt(key, ciphertext)[source]

Decrypts URL-safe base64 encoded ciphertext. On Python 3, the result is decoded from UTF-8.

Parameters:
  • key – AES secret key
  • ciphertext – The encrypted text to decrypt
Returns:

Resulting plaintext

glance.common.crypt.urlsafe_encrypt(key, plaintext, blocksize=16)[source]

Encrypts plaintext. Resulting ciphertext will contain URL-safe characters. If plaintext is Unicode, encode it to UTF-8 before encryption.

Parameters:
  • key – AES secret key
  • plaintext – Input text to be encrypted
  • blocksize – Non-zero integer multiple of AES blocksize in bytes (16)
Returns:

Resulting ciphertext

glance.common.exception module

Glance exception subclasses

exception glance.common.exception.ArtifactCircularDependency(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Artifact with a circular dependency can not be created'
exception glance.common.exception.ArtifactDuplicateDirectDependency(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'Artifact with the specified type, name and version already has the direct dependency=%(dep)s'
exception glance.common.exception.ArtifactDuplicateNameTypeVersion(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'Artifact with the specified type, name and version already exists'
exception glance.common.exception.ArtifactDuplicateTransitiveDependency(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'Artifact with the specified type, name and version already has the transitive dependency=%(dep)s'
exception glance.common.exception.ArtifactForbidden(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Artifact with id=%(id)s is not accessible'
exception glance.common.exception.ArtifactInvalidProperty(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Artifact has no property %(prop)s'
exception glance.common.exception.ArtifactInvalidPropertyParameter(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Cannot use this parameter with the operator %(op)s'
exception glance.common.exception.ArtifactInvalidStateTransition(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Artifact state cannot be changed from %(curr)s to %(to)s'
exception glance.common.exception.ArtifactLoadError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u"Cannot load artifact '%(name)s'"
exception glance.common.exception.ArtifactNonMatchingTypeName(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.ArtifactLoadError

message = u"Plugin name '%(plugin)s' should match artifact typename '%(name)s'"
exception glance.common.exception.ArtifactNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'Artifact with id=%(id)s was not found'
exception glance.common.exception.ArtifactPluginNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u"No plugin for '%(name)s' has been loaded"
exception glance.common.exception.ArtifactPropertyValueNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u"Property's %(prop)s value has not been found"
exception glance.common.exception.ArtifactUnsupportedPropertyOperator(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Operator %(op)s is not supported'
exception glance.common.exception.ArtifactUnsupportedShowLevel(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Show level %(shl)s is not supported in this operation'
exception glance.common.exception.AuthBadRequest(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Connect error/bad request to Auth service at URL %(url)s.'
exception glance.common.exception.AuthUrlNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Auth service at URL %(url)s not found.'
exception glance.common.exception.AuthorizationFailure(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Authorization failed.'
exception glance.common.exception.AuthorizationRedirect(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Redirecting to %(uri)s for authorization.'
exception glance.common.exception.BadAuthStrategy(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Incorrect auth strategy, expected "%(expected)s" but received "%(received)s"'
exception glance.common.exception.BadDriverConfiguration(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Driver %(driver_name)s could not be configured correctly. Reason: %(reason)s'
exception glance.common.exception.BadRegistryConnectionConfiguration(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Registry was not configured correctly on API server. Reason: %(reason)s'
exception glance.common.exception.BadStoreUri(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The Store URI was malformed.'
exception glance.common.exception.BadTaskConfiguration(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Task was not configured properly'
exception glance.common.exception.ClientConfigurationError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'There was an error configuring the client.'
exception glance.common.exception.ClientConnectionError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'There was an error connecting to a server'
exception glance.common.exception.Conflict(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'An object with the same identifier is currently being operated on.'
exception glance.common.exception.Duplicate(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'An object with the same identifier already exists.'
exception glance.common.exception.DuplicateLocation(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'The location %(location)s already exists'
exception glance.common.exception.Forbidden(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'You are not authorized to complete this action.'
exception glance.common.exception.ForbiddenPublicImage(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'You are not authorized to complete this action.'
exception glance.common.exception.GlanceException(message=None, *args, **kwargs)[source]

Bases: exceptions.Exception

Base Glance 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.

message = u'An unknown exception occurred'
exception glance.common.exception.ImageLocationLimitExceeded(*args, **kwargs)[source]

Bases: glance.common.exception.LimitExceeded

message = u'The limit has been exceeded on the number of allowed image locations. Attempted: %(attempted)s, Maximum: %(maximum)s'
exception glance.common.exception.ImageMemberLimitExceeded(*args, **kwargs)[source]

Bases: glance.common.exception.LimitExceeded

message = u'The limit has been exceeded on the number of allowed image members for this image. Attempted: %(attempted)s, Maximum: %(maximum)s'
exception glance.common.exception.ImageNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'Image with the given id %(image_id)s was not found'
exception glance.common.exception.ImagePropertyLimitExceeded(*args, **kwargs)[source]

Bases: glance.common.exception.LimitExceeded

message = u'The limit has been exceeded on the number of allowed image properties. Attempted: %(attempted)s, Maximum: %(maximum)s'
exception glance.common.exception.ImageSizeLimitExceeded(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The provided image is too large.'
exception glance.common.exception.ImageTagLimitExceeded(*args, **kwargs)[source]

Bases: glance.common.exception.LimitExceeded

message = u'The limit has been exceeded on the number of allowed image tags. Attempted: %(attempted)s, Maximum: %(maximum)s'
exception glance.common.exception.ImportTaskError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.TaskException, glance.common.exception.Invalid

message = u'An import task exception occurred'
exception glance.common.exception.Invalid(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Data supplied was not valid.'
exception glance.common.exception.InvalidArtifactPropertyValue(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u"Property '%(name)s' may not have value '%(val)s': %(msg)s"
exception glance.common.exception.InvalidArtifactStateTransition(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Artifact cannot change state from %(source)s to %(target)s'
exception glance.common.exception.InvalidArtifactTypeDefinition(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Invalid type definition'
exception glance.common.exception.InvalidArtifactTypePropertyDefinition(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Invalid property definition'
exception glance.common.exception.InvalidContentType(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Invalid content type %(content_type)s'
exception glance.common.exception.InvalidFilterOperatorValue(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Unable to filter using the specified operator.'
exception glance.common.exception.InvalidFilterRangeValue(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Unable to filter using the specified range.'
exception glance.common.exception.InvalidImageStatusTransition(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Image status transition from %(cur_status)s to %(new_status)s is not allowed'
exception glance.common.exception.InvalidJsonPatchBody(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.JsonPatchException

message = u'The provided body %(body)s is invalid under given schema: %(schema)s'
exception glance.common.exception.InvalidJsonPatchPath(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.JsonPatchException

message = u"The provided path '%(path)s' is invalid: %(explanation)s"
exception glance.common.exception.InvalidObject(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u"Provided object does not match schema '%(schema)s': %(reason)s"
exception glance.common.exception.InvalidOptionValue(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Invalid value for option %(option)s: %(value)s'
exception glance.common.exception.InvalidParameterValue(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u"Invalid value '%(value)s' for parameter '%(param)s': %(extra_msg)s"
exception glance.common.exception.InvalidPropertyProtectionConfiguration(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Invalid configuration in property protection file.'
exception glance.common.exception.InvalidRedirect(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Received invalid HTTP redirect.'
exception glance.common.exception.InvalidSortDir(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Sort direction supplied was not valid.'
exception glance.common.exception.InvalidSortKey(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Sort key supplied was not valid.'
exception glance.common.exception.InvalidSwiftStoreConfiguration(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Invalid configuration in glance-swift conf file.'
exception glance.common.exception.InvalidTaskStatus(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.TaskException, glance.common.exception.Invalid

message = u'Provided status of task is unsupported: %(status)s'
exception glance.common.exception.InvalidTaskStatusTransition(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.TaskException, glance.common.exception.Invalid

message = u'Status transition from %(cur_status)s to %(new_status)s is not allowed'
exception glance.common.exception.InvalidTaskType(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.TaskException, glance.common.exception.Invalid

message = u'Provided type of task is unsupported: %(type)s'
exception glance.common.exception.InvalidVersion(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Invalid

message = u'Version is invalid: %(reason)s'
exception glance.common.exception.JsonPatchException(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Invalid jsonpatch request'
exception glance.common.exception.LimitExceeded(*args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The request returned a 413 Request Entity Too Large. This generally means that rate limiting or a quota threshold was breached.\n\nThe response body:\n%(body)s'
exception glance.common.exception.MaxRedirectsExceeded(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Maximum redirects (%(redirects)s) was exceeded.'
exception glance.common.exception.MetadefDuplicateNamespace(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'The metadata definition namespace=%(namespace_name)s already exists.'
exception glance.common.exception.MetadefDuplicateObject(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'A metadata definition object with name=%(object_name)s already exists in namespace=%(namespace_name)s.'
exception glance.common.exception.MetadefDuplicateProperty(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'A metadata definition property with name=%(property_name)s already exists in namespace=%(namespace_name)s.'
exception glance.common.exception.MetadefDuplicateResourceType(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'A metadata definition resource-type with name=%(resource_type_name)s already exists.'
exception glance.common.exception.MetadefDuplicateResourceTypeAssociation(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'The metadata definition resource-type association of resource-type=%(resource_type_name)s to namespace=%(namespace_name)s already exists.'
exception glance.common.exception.MetadefDuplicateTag(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Duplicate

message = u'A metadata tag with name=%(name)s already exists in namespace=%(namespace_name)s.'
exception glance.common.exception.MetadefForbidden(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'You are not authorized to complete this action.'
exception glance.common.exception.MetadefIntegrityError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'The metadata definition %(record_type)s with name=%(record_name)s not deleted. Other records still refer to it.'
exception glance.common.exception.MetadefNamespaceNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'Metadata definition namespace=%(namespace_name)swas not found.'
exception glance.common.exception.MetadefObjectNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'The metadata definition object with name=%(object_name)s was not found in namespace=%(namespace_name)s.'
exception glance.common.exception.MetadefPropertyNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'The metadata definition property with name=%(property_name)s was not found in namespace=%(namespace_name)s.'
exception glance.common.exception.MetadefResourceTypeAssociationNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'The metadata definition resource-type association of resource-type=%(resource_type_name)s to namespace=%(namespace_name)s, was not found.'
exception glance.common.exception.MetadefResourceTypeNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'The metadata definition resource-type with name=%(resource_type_name)s, was not found.'
exception glance.common.exception.MetadefTagNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u'The metadata definition tag with name=%(name)s was not found in namespace=%(namespace_name)s.'
exception glance.common.exception.MissingCredentialError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Missing required credential: %(required)s'
exception glance.common.exception.MultipleChoices(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The request returned a 302 Multiple Choices. This generally means that you have not included a version indicator in a request URI.\n\nThe body of response returned:\n%(body)s'
exception glance.common.exception.NoServiceEndpoint(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Response from Keystone does not contain a Glance endpoint.'
exception glance.common.exception.NotAuthenticated(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'You are not authenticated.'
exception glance.common.exception.NotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'An object with the specified identifier was not found.'
exception glance.common.exception.ProtectedImageDelete(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Image %(image_id)s is protected and cannot be deleted.'
exception glance.common.exception.ProtectedMetadefNamespaceDelete(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Metadata definition namespace %(namespace)s is protected and cannot be deleted.'
exception glance.common.exception.ProtectedMetadefNamespacePropDelete(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Metadata definition property %(property_name)s is protected and cannot be deleted.'
exception glance.common.exception.ProtectedMetadefObjectDelete(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Metadata definition object %(object_name)s is protected and cannot be deleted.'
exception glance.common.exception.ProtectedMetadefResourceTypeAssociationDelete(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Metadata definition resource-type-association %(resource_type)s is protected and cannot be deleted.'
exception glance.common.exception.ProtectedMetadefResourceTypeSystemDelete(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Metadata definition resource-type %(resource_type_name)s is a seeded-system type and cannot be deleted.'
exception glance.common.exception.ProtectedMetadefTagDelete(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u'Metadata definition tag %(tag_name)s is protected and cannot be deleted.'
exception glance.common.exception.RPCError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'%(cls)s exception was raised in the last rpc call: %(val)s'
exception glance.common.exception.ReadonlyProperty(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u"Attribute '%(property)s' is read-only."
exception glance.common.exception.RedirectException(url)[source]

Bases: exceptions.Exception

exception glance.common.exception.RegionAmbiguity(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u"Multiple 'image' service matches for region %(region)s. This generally means that a region is required and you have not supplied one."
exception glance.common.exception.ReservedProperty(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.Forbidden

message = u"Attribute '%(property)s' is reserved."
exception glance.common.exception.SIGHUPInterrupt(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'System SIGHUP signal received.'
exception glance.common.exception.SchemaLoadError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Unable to load schema: %(reason)s'
exception glance.common.exception.ServerError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The request returned 500 Internal Server Error.'
exception glance.common.exception.ServiceUnavailable(*args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The request returned 503 Service Unavailable. This generally occurs on service overload or other transient outage.'
exception glance.common.exception.SignatureVerificationError(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Unable to verify signature: %(reason)s'
exception glance.common.exception.StorageQuotaFull(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The size of the data %(image_size)s will exceed the limit. %(remaining)s bytes remaining.'
exception glance.common.exception.TaskException(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'An unknown task exception occurred'
exception glance.common.exception.TaskNotFound(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.TaskException, glance.common.exception.NotFound

message = u'Task with the given id %(task_id)s was not found'
exception glance.common.exception.UnexpectedStatus(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'The request returned an unexpected status: %(status)s.\n\nThe response body:\n%(body)s'
exception glance.common.exception.UnknownArtifactType(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.NotFound

message = u"Artifact type with name '%(name)s' and version '%(version)s' is not known"
exception glance.common.exception.UploadException(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Image upload problem: %s'
exception glance.common.exception.WorkerCreationFailure(message=None, *args, **kwargs)[source]

Bases: glance.common.exception.GlanceException

message = u'Server worker creation failed: %(reason)s.'

glance.common.jsonpatchvalidator module

A mixin that validates the given body for jsonpatch-compatibility. The methods supported are limited to listed in METHODS_ALLOWED

class glance.common.jsonpatchvalidator.JsonPatchValidatorMixin(methods_allowed=None)[source]

Bases: object

ALLOWED = ['replace', 'test', 'remove', 'add', 'copy']
PATH_REGEX_COMPILED = <_sre.SRE_Pattern object at 0x7f9ec76a63f0>
validate_body(body)[source]

glance.common.property_utils module

class glance.common.property_utils.PropertyRules(policy_enforcer=None)[source]

Bases: object

check_property_rules(property_name, action, context)[source]
glance.common.property_utils.is_property_protection_enabled()[source]

glance.common.rpc module

RPC Controller

class glance.common.rpc.Controller(raise_exc=False)[source]

Bases: object

Base RPCController.

This is the base controller for RPC based APIs. Commands handled by this controller respect the following form:

[{
‘command’: ‘method_name’, ‘kwargs’: {...}

}]

The controller is capable of processing more than one command per request and will always return a list of results.

Params raise_exc:
 Boolean that specifies whether to raise

exceptions instead of “serializing” them.

register(resource, filtered=None, excluded=None, refiner=None)[source]

Exports methods through the RPC Api.

Params resource:
 Resource’s instance to register.
Params filtered:
 List of methods that can be registered. Read

as “Method must be in this list”. :params excluded: List of methods to exclude. :params refiner: Callable to use as filter for methods.

Raises TypeError:
 If refiner is not callable.
class glance.common.rpc.RPCClient(*args, **kwargs)[source]

Bases: glance.common.client.BaseClient

bulk_request(*args, **kwargs)[source]

Execute multiple commands in a single request.

Params commands:
 List of commands to send. Commands

must respect the following form:

{
‘command’: ‘method_name’, ‘kwargs’: method_kwargs

}

do_request(method, **kwargs)[source]

Simple do_request override. This method serializes the outgoing body and builds the command that will be sent.

Params method:The remote python method to call
Params kwargs:Dynamic parameters that will be passed to the remote method.
class glance.common.rpc.RPCJSONDeserializer[source]

Bases: glance.common.wsgi.JSONRequestDeserializer

class glance.common.rpc.RPCJSONSerializer[source]

Bases: glance.common.wsgi.JSONResponseSerializer

glance.common.semver_db module

class glance.common.semver_db.DBVersion(components_long, prerelease, build)[source]

Bases: object

class glance.common.semver_db.VersionComparator(prop, parentmapper, adapt_to_entity=None)[source]

Bases: sqlalchemy.orm.descriptor_props.Comparator

glance.common.semver_db.parse(version_string)[source]

glance.common.signature_utils module

Support signature verification.

class glance.common.signature_utils.SignatureKeyType(name, public_key_type, create_verifier)[source]

Bases: object

classmethod lookup(name)[source]

Look up the signature key type.

Parameters:name – the name of the signature key type
Returns:the SignatureKeyType object
Raises:glance.common.exception.SignatureVerificationError if signature key type is invalid
classmethod register(name, public_key_type, create_verifier)[source]

Register a signature key type.

Parameters:
  • name – the name of the signature key type
  • public_key_type – e.g. RSAPublicKey, DSAPublicKey, etc.
  • create_verifier – a function to create a verifier for this type
glance.common.signature_utils.create_verifier_for_dsa(signature, hash_method, public_key, image_properties)[source]

Create verifier to use when the key type is DSA

Parameters:
  • signature – the decoded signature to use
  • hash_method – the hash method to use, as a cryptography object
  • public_key – the public key to use, as a cryptography object
  • image_properties – the key-value properties about the image
Returns:

the verifier to use to verify the signature for DSA

glance.common.signature_utils.create_verifier_for_ecc(signature, hash_method, public_key, image_properties)[source]

Create the verifier to use when the key type is ECC_*.

Parameters:
  • signature – the decoded signature to use
  • hash_method – the hash method to use, as a cryptography object
  • public_key – the public key to use, as a cryptography object
  • image_properties – the key-value properties about the image
Returns:

the verifier to use to verify the signature for ECC_*

glance.common.signature_utils.create_verifier_for_pss(signature, hash_method, public_key, image_properties)[source]

Create the verifier to use when the key type is RSA-PSS.

Parameters:
  • signature – the decoded signature to use
  • hash_method – the hash method to use, as a cryptography object
  • public_key – the public key to use, as a cryptography object
  • image_properties – the key-value properties about the image
Returns:

the verifier to use to verify the signature for RSA-PSS

Raises glance.common.exception.SignatureVerificationError:
 

if the RSA-PSS specific properties are invalid

glance.common.signature_utils.get_certificate(context, signature_certificate_uuid)[source]

Create the certificate object from the retrieved certificate data.

Parameters:
  • context – the user context for authentication
  • signature_certificate_uuid – the uuid to use to retrieve the certificate
Returns:

the certificate cryptography object

Raises glance.common.exception.SignatureVerificationError:
 

if the retrieval fails or the format is invalid

glance.common.signature_utils.get_hash_method(hash_method_name)[source]

Verify the hash method name and create the hash method.

Parameters:hash_method_name – the name of the hash method to retrieve
Returns:the hash method, a cryptography object
Raises glance.common.exception.SignatureVerificationError:
 if the hash method name is invalid
glance.common.signature_utils.get_public_key(context, signature_certificate_uuid, signature_key_type)[source]

Create the public key object from a retrieved certificate.

Parameters:
  • context – the user context for authentication
  • signature_certificate_uuid – the uuid to use to retrieve the certificate
  • signature_key_type – a SignatureKeyType object
Returns:

the public key cryptography object

Raises glance.common.exception.SignatureVerificationError:
 

if public key format is invalid

glance.common.signature_utils.get_signature(signature_data)[source]

Decode the signature data and returns the signature.

Parameters:siganture_data – the base64-encoded signature data
Returns:the decoded signature
Raises glance.common.exception.SignatureVerificationError:
 if the signature data is malformatted
glance.common.signature_utils.get_verifier(context, image_properties)[source]

Retrieve the image properties and use them to create a verifier.

Parameters:
  • context – the user context for authentication
  • image_properties – the key-value properties about the image
Returns:

instance of cryptography AsymmetricVerificationContext

Raises glance.common.exception.SignatureVerificationError:
 

if building the verifier fails

glance.common.signature_utils.should_create_verifier(image_properties)[source]

Determine whether a verifier should be created.

Using the image properties, determine whether existing properties indicate that signature verification should be done.

Parameters:image_properties – the key-value properties about the image
Returns:True, if signature metadata properties exist, False otherwise
glance.common.signature_utils.should_verify_signature(image_properties)[source]

Determine whether a signature should be verified.

Using the image properties, determine whether existing properties indicate that signature verification should be done.

Parameters:image_properties – the key-value properties about the image
Returns:True, if signature metadata properties exist, False otherwise
glance.common.signature_utils.verify_certificate(certificate)[source]

Verify that the certificate has not expired.

Parameters:certificate – the cryptography certificate object
Raises glance.common.exception.SignatureVerificationError:
 if the certificate valid time range does not include now
glance.common.signature_utils.verify_signature(context, checksum_hash, image_properties)[source]

Retrieve the image properties and use them to verify the signature.

Parameters:
  • context – the user context for authentication
  • checksum_hash – the ‘checksum’ hash of the image data
  • image_properties – the key-value properties about the image
Returns:

True if verification succeeds

Raises glance.common.exception.SignatureVerificationError:
 

if verification fails

glance.common.store_utils module

glance.common.store_utils.delete_image_location_from_backend(context, image_id, location)[source]

Given a location, immediately or schedule the deletion of an image location and update location status to db.

Parameters:
  • context – The request context
  • image_id – The image identifier
  • location – The image location entry
glance.common.store_utils.safe_delete_from_backend(context, image_id, location)[source]

Given a location, delete an image from the store and update location status to db.

This function try to handle all known exceptions which might be raised by those calls on store and DB modules in its implementation.

Parameters:
  • context – The request context
  • image_id – The image identifier
  • location – The image location entry
glance.common.store_utils.schedule_delayed_delete_from_backend(context, image_id, location)[source]

Given a location, schedule the deletion of an image location and update location status to db.

Parameters:
  • context – The request context
  • image_id – The image identifier
  • location – The image location entry
glance.common.store_utils.validate_external_location(uri)[source]

Validate if URI of external location are supported.

Only over non-local store types are OK, i.e. S3, Swift, HTTP. Note the absence of ‘file://‘ for security reasons, see LP bug #942118, 1400966, ‘swift+config://’ is also absent for security reasons, see LP bug #1334196.

Parameters:uri – The URI of external image location.
Returns:Whether given URI of external image location are OK.

glance.common.swift_store_utils module

class glance.common.swift_store_utils.SwiftParams[source]

Bases: object

glance.common.swift_store_utils.is_multiple_swift_store_accounts_enabled()[source]

glance.common.timeutils module

Time related utilities and helper functions.

glance.common.timeutils.delta_seconds(before, after)[source]

Return the difference between two timing objects.

Compute the difference in seconds between two date, time, or datetime objects (as a float, to microsecond resolution).

glance.common.timeutils.iso8601_from_timestamp(timestamp, microsecond=False)[source]

Returns an iso8601 formatted date from timestamp.

glance.common.timeutils.isotime(at=None, subsecond=False)[source]

Stringify time in ISO 8601 format.

glance.common.timeutils.normalize_time(timestamp)[source]

Normalize time in arbitrary timezone to UTC naive object.

glance.common.timeutils.parse_isotime(timestr)[source]

Parse time from ISO 8601 format.

glance.common.timeutils.utcnow(with_timezone=False)[source]

Overridable version of utils.utcnow that can return a TZ-aware datetime.

glance.common.trust_auth module

class glance.common.trust_auth.TokenRefresher(user_plugin, user_project, user_roles)[source]

Bases: object

Class that responsible for token refreshing with trusts

refresh_token()[source]

Receive new token if user need to update old token

Returns:new token that can be used for authentication
release_resources()[source]

Release keystone resources required for refreshing

glance.common.utils module

System-level utilities and helper functions.

class glance.common.utils.CooperativeReader(fd)[source]

Bases: object

An eventlet thread friendly class for reading in image data.

When accessing data either through the iterator or the read method we perform a sleep to allow a co-operative yield. When there is more than one image being uploaded/downloaded this prevents eventlet thread starvation, ie allows all threads to be scheduled periodically rather than having the same thread be continuously active.

read(length=None)[source]

Return the requested amount of bytes, fetching the next chunk of the underlying iterator when needed.

This is replaced with cooperative_read in __init__ if the underlying fd already supports read().

class glance.common.utils.LimitingReader(data, limit)[source]

Bases: object

Reader designed to fail when reading image data past the configured allowable amount.

read(i)[source]
glance.common.utils.chunkiter(fp, chunk_size=65536)[source]

Return an iterator to a file-like obj which yields fixed size chunks

Parameters:
  • fp – a file-like object
  • chunk_size – maximum size of chunk
glance.common.utils.chunkreadable(iter, chunk_size=65536)[source]

Wrap a readable iterator with a reader yielding chunks of a preferred size, otherwise leave iterator unchanged.

Parameters:
  • iter – an iter which may also be readable
  • chunk_size – maximum size of chunk
glance.common.utils.cooperative_iter(iter)[source]

Return an iterator which schedules after each iteration. This can prevent eventlet thread starvation.

Parameters:iter – an iterator to wrap
glance.common.utils.cooperative_read(fd)[source]

Wrap a file descriptor’s read with a partial function which schedules after each read. This can prevent eventlet thread starvation.

Parameters:fd – a file descriptor to wrap
glance.common.utils.create_mashup_dict(image_meta)[source]

Returns a dictionary-like mashup of the image core properties and the image custom properties from given image metadata.

Parameters:image_meta – metadata of image with core and custom properties
glance.common.utils.evaluate_filter_op(value, operator, threshold)[source]

Evaluate a comparison operator. Designed for use on a comparative-filtering query field.

Parameters:
  • value – evaluated against the operator, as left side of expression
  • operator – any supported filter operation
  • threshold – to compare value against, as right side of expression
Raises:

InvalidFilterOperatorValue if an unknown operator is provided

Returns:

boolean result of applied comparison

glance.common.utils.get_image_meta_from_headers(response)[source]

Processes HTTP headers from a supplied response that match the x-image-meta and x-image-meta-property and returns a mapping of image metadata and properties

Parameters:response – Response to process
glance.common.utils.get_test_suite_socket()[source]
glance.common.utils.image_meta_to_http_headers(image_meta)[source]

Returns a set of image metadata into a dict of HTTP headers that can be fed to either a Webob Request object or an httplib.HTTP(S)Connection object

Parameters:image_meta – Mapping of image metadata
glance.common.utils.is_valid_fqdn(fqdn)[source]

Verify whether a host is a valid FQDN.

glance.common.utils.is_valid_hostname(hostname)[source]

Verify whether a hostname (not an FQDN) is valid.

glance.common.utils.mutating(func)[source]

Decorator to enforce read-only logic

glance.common.utils.no_4byte_params(f)[source]

Checks that no 4 byte unicode characters are allowed in dicts’ keys/values and string’s parameters

glance.common.utils.parse_valid_host_port(host_port)[source]

Given a “host:port” string, attempts to parse it as intelligently as possible to determine if it is valid. This includes IPv6 [host]:port form, IPv4 ip:port form, and hostname:port or fqdn:port form.

Invalid inputs will raise a ValueError, while valid inputs will return a (host, port) tuple where the port will always be of type int.

glance.common.utils.safe_mkdirs(path)[source]
glance.common.utils.setup_remote_pydev_debug(host, port)[source]
glance.common.utils.split_filter_op(expression)[source]

Split operator from threshold in an expression. Designed for use on a comparative-filtering query field. When no operator is found, default to an equality comparison.

Parameters:expression – the expression to parse
Returns:a tuple (operator, threshold) parsed from expression
glance.common.utils.split_filter_value_for_quotes(value)[source]

Split filter values

Split values by commas and quotes for ‘in’ operator, according api-wg.

glance.common.utils.stash_conf_values()[source]

Make a copy of some of the current global CONF’s settings. Allows determining if any of these values have changed when the config is reloaded.

glance.common.utils.validate_key_cert(key_file, cert_file)[source]
glance.common.utils.validate_mysql_int(*args, **kwargs)[source]

Make sure that all arguments are less than 2 ** 31 - 1.

This limitation is introduced because mysql stores INT in 4 bytes. If the validation fails for some argument, exception.Invalid is raised with appropriate information.

glance.common.utils.validate_quotes(value)[source]

Validate filter values

Validation opening/closing quotes in the expression.

glance.common.wsgi module

Utility methods for working with WSGI servers

class glance.common.wsgi.APIMapper(controller_scan=<function controller_scan at 0x7f9ec99efde8>, directory=None, always_scan=False, register=True, explicit=True)[source]

Bases: routes.mapper.Mapper

Handle route matching when url is ‘’ because routes.Mapper returns an error in this case.

routematch(url=None, environ=None)[source]
class glance.common.wsgi.Debug(application)[source]

Bases: glance.common.wsgi.Middleware

Helper class that can be inserted into any WSGI application chain to get information about the request and response.

static print_generator(app_iter)[source]

Iterator that prints the contents of a wrapper string iterator when iterated.

class glance.common.wsgi.JSONRequestDeserializer[source]

Bases: object

default(request)[source]
from_json(datastring)[source]
has_body(request)[source]

Returns whether a Webob.Request object will possess an entity body.

Parameters:request – Webob.Request object
valid_transfer_encoding = frozenset(['gzip', 'chunked', 'compress', 'identity', 'deflate'])
class glance.common.wsgi.JSONResponseSerializer[source]

Bases: object

default(response, result)[source]
to_json(data)[source]
class glance.common.wsgi.Middleware(application)[source]

Bases: object

Base WSGI middleware wrapper. 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 factory(global_conf, **local_conf)[source]
process_request(req)[source]

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.

process_response(response)[source]

Do whatever you’d like to the response.

class glance.common.wsgi.RejectMethodController[source]

Bases: object

reject(req, allowed_methods, *args, **kwargs)[source]
class glance.common.wsgi.Request(environ, charset=None, unicode_errors=None, decode_param_names=None, **kw)[source]

Bases: webob.request.Request

Add some OpenStack API-specific logic to the base webob.Request.

best_match_content_type()[source]

Determine the requested response content-type.

best_match_language()[source]

Determines best available locale from the Accept-Language header.

Returns:the best language match or None if the ‘Accept-Language’ header was not available in the request.
get_content_range()[source]

Return the Range in a request.

get_content_type(allowed_content_types)[source]

Determine content type of the request body.

class glance.common.wsgi.Resource(controller, deserializer=None, serializer=None)[source]

Bases: object

WSGI app that handles (de)serialization and controller dispatch.

Reads routing information supplied by RoutesMiddleware and calls the requested action method upon its deserializer, controller, and serializer. Those three objects may implement any of the basic controller action methods (create, update, show, index, delete) along with any that may be specified in the api router. A ‘default’ method may also be implemented to be used in place of any non-implemented actions. Deserializer methods must accept a request argument and return a dictionary. Controller methods must accept a request argument. Additionally, they must also accept keyword arguments that represent the keys returned by the Deserializer. They may raise a webob.exc exception or return a dict, which will be serialized by requested content type.

dispatch(obj, action, *args, **kwargs)[source]

Find action-specific method on self and call it.

get_action_args(request_environment)[source]

Parse dictionary created by routes library.

class glance.common.wsgi.Router(mapper)[source]

Bases: object

WSGI middleware that maps incoming requests to WSGI apps.

classmethod factory(global_conf, **local_conf)[source]
class glance.common.wsgi.Server(threads=1000, initialize_glance_store=False)[source]

Bases: object

Server class to manage multiple WSGI sockets and applications.

This class requires initialize_glance_store set to True if glance store needs to be initialized.

configure(old_conf=None, has_changed=None)[source]

Apply configuration settings

Parameters:
  • old_conf – Cached old configuration settings (if any)
  • changed (has) – callable to determine if a parameter has changed
configure_socket(old_conf=None, has_changed=None)[source]

Ensure a socket exists and is appropriately configured.

This function is called on start up, and can also be called in the event of a configuration reload.

When called for the first time a new socket is created. If reloading and either bind_host or bind port have been changed the existing socket must be closed and a new socket opened (laws of physics).

In all other cases (bind_host/bind_port have not changed) the existing socket is reused.

Parameters:
  • old_conf – Cached old configuration settings (if any)
  • changed (has) – callable to determine if a parameter has changed
create_pool()[source]
hup(*args)[source]

Reloads configuration files with zero down time

kill_children(*args)[source]

Kills the entire process group.

reload()[source]

Reload and re-apply configuration settings

Existing child processes are sent a SIGHUP signal and will exit after completing existing requests. New child processes, which will have the updated configuration, are spawned. This allows preventing interruption to the service.

run_child()[source]
run_server()[source]

Run a WSGI server.

start(application, default_port)[source]

Run a WSGI server with the given application.

Parameters:
  • application – The application to be run in the WSGI server
  • default_port – Port to bind to if none is specified in conf
start_wsgi()[source]
wait()[source]

Wait until all servers have completed running.

wait_on_children()[source]
glance.common.wsgi.get_asynchronous_eventlet_pool(size=1000)[source]

Return eventlet pool to caller.

Also store pools created in global list, to wait on it after getting signal for graceful shutdown.

Parameters:size – eventlet pool size
Returns:eventlet pool
glance.common.wsgi.get_bind_addr(default_port=None)[source]

Return the host and port to bind to.

glance.common.wsgi.get_num_workers()[source]

Return the configured number of workers.

glance.common.wsgi.get_socket(default_port)[source]

Bind socket to bind ip:port in conf

note: Mostly comes from Swift with a few small changes...

Parameters:default_port – port to bind to if none is specified in conf
Returns:a socket object as returned from socket.listen or ssl.wrap_socket if conf specifies cert_file
glance.common.wsgi.initialize_glance_store()[source]

Initialize glance store.

glance.common.wsgi.set_eventlet_hub()[source]
glance.common.wsgi.ssl_wrap_socket(sock)[source]

Wrap an existing socket in SSL

Parameters:sock – non-SSL socket to wrap
Returns:An SSL wrapped socket
glance.common.wsgi.translate_exception(req, e)[source]

Translates all translatable elements of the given exception.

glance.common.wsme_utils module

class glance.common.wsme_utils.WSMEModelTransformer[source]

Bases: object

classmethod get_mandatory_attrs()[source]
to_dict()[source]
classmethod to_wsme_model(model, db_entity, self_link=None, schema=None)[source]

Module contents