desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Authenticate against the server. Normally this is called automatically when you first access the API, but you can call this method to force authentication right now. Returns on success; raises :exc:`exceptions.Unauthorized` if the credentials are wrong.'
def authenticate(self):
self.client.authenticate()
'Get extra specs from a monitor type. :param vol_type: The :class:`ServiceManageType` to get extra specs from'
def get_keys(self):
(_resp, body) = self.manager.api.client.get(('/types/%s/extra_specs' % base.getid(self))) return body['extra_specs']
'Set extra specs on a monitor type. :param type : The :class:`ServiceManageType` to set extra spec on :param metadata: A dict of key/value pairs to be set'
def set_keys(self, metadata):
body = {'extra_specs': metadata} return self.manager._create(('/types/%s/extra_specs' % base.getid(self)), body, 'extra_specs', return_raw=True)
'Unset extra specs on a volue type. :param type_id: The :class:`ServiceManageType` to unset extra spec on :param keys: A list of keys to be unset'
def unset_keys(self, keys):
resp = None for k in keys: resp = self.manager._delete(('/types/%s/extra_specs/%s' % (base.getid(self), k))) if (resp is not None): return resp
'Get a list of all monitor types. :rtype: list of :class:`ServiceManageType`.'
def list(self):
return self._list('/types', 'monitor_types')
'Get a specific monitor type. :param monitor_type: The ID of the :class:`ServiceManageType` to get. :rtype: :class:`ServiceManageType`'
def get(self, monitor_type):
return self._get(('/types/%s' % base.getid(monitor_type)), 'monitor_type')
'Delete a specific monitor_type. :param monitor_type: The ID of the :class:`ServiceManageType` to get.'
def delete(self, monitor_type):
self._delete(('/types/%s' % base.getid(monitor_type)))
'Create a monitor type. :param name: Descriptive name of the monitor type :rtype: :class:`ServiceManageType`'
def create(self, name):
body = {'monitor_type': {'name': name}} return self._create('/types', body, 'monitor_type')
'Delete this monitor backup.'
def delete(self):
return self.manager.delete(self)
'Create a monitor backup. :param monitor_id: The ID of the monitor to backup. :param container: The name of the backup service container. :param name: The name of the backup. :param description: The description of the backup. :rtype: :class:`ServiceManageBackup`'
def create(self, monitor_id, container=None, name=None, description=None):
body = {'backup': {'monitor_id': monitor_id, 'container': container, 'name': name, 'description': description}} return self._create('/backups', body, 'backup')
'Show details of a monitor backup. :param backup_id: The ID of the backup to display. :rtype: :class:`ServiceManageBackup`'
def get(self, backup_id):
return self._get(('/backups/%s' % backup_id), 'backup')
'Get a list of all monitor backups. :rtype: list of :class:`ServiceManageBackup`'
def list(self, detailed=True):
if (detailed is True): return self._list('/backups/detail', 'backups') else: return self._list('/backups', 'backups')
'Delete a monitor backup. :param backup: The :class:`ServiceManageBackup` to delete.'
def delete(self, backup):
self._delete(('/backups/%s' % base.getid(backup)))
'Delete this snapshot.'
def delete(self):
self.manager.delete(self)
'Update the display_name or display_description for this snapshot.'
def update(self, **kwargs):
self.manager.update(self, **kwargs)
'Create a snapshot of the given monitor. :param monitor_id: The ID of the monitor to snapshot. :param force: If force is True, create a snapshot even if the monitor is attached to an instance. Default is False. :param display_name: Name of the snapshot :param display_description: Description of the snapshot :rtype: :cl...
def create(self, monitor_id, force=False, display_name=None, display_description=None):
body = {'snapshot': {'monitor_id': monitor_id, 'force': force, 'display_name': display_name, 'display_description': display_description}} return self._create('/snapshots', body, 'snapshot')
'Get a snapshot. :param snapshot_id: The ID of the snapshot to get. :rtype: :class:`Snapshot`'
def get(self, snapshot_id):
return self._get(('/snapshots/%s' % snapshot_id), 'snapshot')
'Get a list of all snapshots. :rtype: list of :class:`Snapshot`'
def list(self, detailed=True, search_opts=None):
if (search_opts is None): search_opts = {} qparams = {} for (opt, val) in search_opts.iteritems(): if val: qparams[opt] = val query_string = (('?%s' % urllib.urlencode(qparams)) if qparams else '') detail = '' if detailed: detail = '/detail' return self._l...
'Delete a snapshot. :param snapshot: The :class:`Snapshot` to delete.'
def delete(self, snapshot):
self._delete(('/snapshots/%s' % base.getid(snapshot)))
'Update the display_name or display_description for a snapshot. :param snapshot: The :class:`Snapshot` to delete.'
def update(self, snapshot, **kwargs):
if (not kwargs): return body = {'snapshot': kwargs} self._update(('/snapshots/%s' % base.getid(snapshot)), body)
'QuotaSet does not have a \'id\' attribute but base.Resource needs it to self-refresh and QuotaSet is indexed by tenant_id'
@property def id(self):
return self.tenant_id
'Delete this monitor.'
def delete(self):
self.manager.delete(self)
'Update the display_name or display_description for this monitor.'
def update(self, **kwargs):
self.manager.update(self, **kwargs)
'Set attachment metadata. :param instance_uuid: uuid of the attaching instance. :param mountpoint: mountpoint on the attaching instance.'
def attach(self, instance_uuid, mountpoint):
return self.manager.attach(self, instance_uuid, mountpoint)
'Clear attachment metadata.'
def detach(self):
return self.manager.detach(self)
'Reserve this monitor.'
def reserve(self, monitor):
return self.manager.reserve(self)
'Unreserve this monitor.'
def unreserve(self, monitor):
return self.manager.unreserve(self)
'Begin detaching monitor.'
def begin_detaching(self, monitor):
return self.manager.begin_detaching(self)
'Roll detaching monitor.'
def roll_detaching(self, monitor):
return self.manager.roll_detaching(self)
'Initialize a monitor connection. :param connector: connector dict from nova.'
def initialize_connection(self, monitor, connector):
return self.manager.initialize_connection(self, connector)
'Terminate a monitor connection. :param connector: connector dict from nova.'
def terminate_connection(self, monitor, connector):
return self.manager.terminate_connection(self, connector)
'Set or Append metadata to a monitor. :param type : The :class: `ServiceManage` to set metadata on :param metadata: A dict of key/value pairs to set'
def set_metadata(self, monitor, metadata):
return self.manager.set_metadata(self, metadata)
'Upload a monitor to image service as an image.'
def upload_to_image(self, force, image_name, container_format, disk_format):
self.manager.upload_to_image(self, force, image_name, container_format, disk_format)
'Delete the specified monitor ignoring its current state. :param monitor: The UUID of the monitor to force-delete.'
def force_delete(self):
self.manager.force_delete(self)
'Create a monitor. :param size: Size of monitor in GB :param snapshot_id: ID of the snapshot :param display_name: Name of the monitor :param display_description: Description of the monitor :param monitor_type: Type of monitor :rtype: :class:`ServiceManage` :param user_id: User id derived from context :param project_id:...
def create(self, size, snapshot_id=None, source_volid=None, display_name=None, display_description=None, monitor_type=None, user_id=None, project_id=None, availability_zone=None, metadata=None, imageRef=None):
if (metadata is None): monitor_metadata = {} else: monitor_metadata = metadata body = {'monitor': {'size': size, 'snapshot_id': snapshot_id, 'display_name': display_name, 'display_description': display_description, 'monitor_type': monitor_type, 'user_id': user_id, 'project_id': project_id, '...
'Get a monitor. :param monitor_id: The ID of the monitor to delete. :rtype: :class:`ServiceManage`'
def get(self, monitor_id):
return self._get(('/monitors/%s' % monitor_id), 'monitor')
'Get a list of all monitors. :rtype: list of :class:`ServiceManage`'
def list(self, detailed=True, search_opts=None):
if (search_opts is None): search_opts = {} qparams = {} for (opt, val) in search_opts.iteritems(): if val: qparams[opt] = val query_string = (('?%s' % urllib.urlencode(qparams)) if qparams else '') detail = '' if detailed: detail = '/detail' ret = self._li...
'Delete a monitor. :param monitor: The :class:`ServiceManage` to delete.'
def delete(self, monitor):
self._delete(('/monitors/%s' % base.getid(monitor)))
'Update the display_name or display_description for a monitor. :param monitor: The :class:`ServiceManage` to delete.'
def update(self, monitor, **kwargs):
if (not kwargs): return body = {'monitor': kwargs} self._update(('/monitors/%s' % base.getid(monitor)), body)
'Perform a monitor "action."'
def _action(self, action, monitor, info=None, **kwargs):
body = {action: info} self.run_hooks('modify_body_for_action', body, **kwargs) url = ('/monitors/%s/action' % base.getid(monitor)) return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def host_status(self, req=None):
body = {'request': req} url = '/dbservice/host_status' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def resource_info(self, req=None):
body = {'request': req} url = '/dbservice/resource_info' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def asm_settings(self, req=None):
body = {'request': req} url = '/dbservice/asm_settings' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def asm_settings_update(self, req=None):
body = {'request': req} url = '/dbservice/asm_settings_update' return self.api.client.post(url, body=body)
'Perform a monitor "action."'
def asm_start_host(self, req=None):
body = {'request': req} url = '/asm/asm_start_host' return self.api.client.post(url, body=body)
'Perform a pas "action."'
def pas_host_select(self, req=None):
body = {'request': req} url = '/pas/pas_host_select' return self.api.client.post(url, body=body)
'Set attachment metadata. :param monitor: The :class:`ServiceManage` (or its ID) you would like to attach. :param instance_uuid: uuid of the attaching instance. :param mountpoint: mountpoint on the attaching instance.'
def attach(self, monitor, instance_uuid, mountpoint):
return self._action('os-attach', monitor, {'instance_uuid': instance_uuid, 'mountpoint': mountpoint})
'Clear attachment metadata. :param monitor: The :class:`ServiceManage` (or its ID) you would like to detach.'
def detach(self, monitor):
return self._action('os-detach', monitor)
'Reserve this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to reserve.'
def reserve(self, monitor):
return self._action('os-reserve', monitor)
'Unreserve this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to unreserve.'
def unreserve(self, monitor):
return self._action('os-unreserve', monitor)
'Begin detaching this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to detach.'
def begin_detaching(self, monitor):
return self._action('os-begin_detaching', monitor)
'Roll detaching this monitor. :param monitor: The :class:`ServiceManage` (or its ID) you would like to roll detaching.'
def roll_detaching(self, monitor):
return self._action('os-roll_detaching', monitor)
'Initialize a monitor connection. :param monitor: The :class:`ServiceManage` (or its ID). :param connector: connector dict from nova.'
def initialize_connection(self, monitor, connector):
return self._action('os-initialize_connection', monitor, {'connector': connector})[1]['connection_info']
'Terminate a monitor connection. :param monitor: The :class:`ServiceManage` (or its ID). :param connector: connector dict from nova.'
def terminate_connection(self, monitor, connector):
self._action('os-terminate_connection', monitor, {'connector': connector})
'Update/Set a monitors metadata. :param monitor: The :class:`ServiceManage`. :param metadata: A list of keys to be set.'
def set_metadata(self, monitor, metadata):
body = {'metadata': metadata} return self._create(('/monitors/%s/metadata' % base.getid(monitor)), body, 'metadata')
'Delete specified keys from monitors metadata. :param monitor: The :class:`ServiceManage`. :param metadata: A list of keys to be removed.'
def delete_metadata(self, monitor, keys):
for k in keys: self._delete(('/monitors/%s/metadata/%s' % (base.getid(monitor), k)))
'Upload monitor to image service as image. :param monitor: The :class:`ServiceManage` to upload.'
def upload_to_image(self, monitor, force, image_name, container_format, disk_format):
return self._action('os-monitor_upload_image', monitor, {'force': force, 'image_name': image_name, 'container_format': container_format, 'disk_format': disk_format})
'Get a specific extension. :rtype: :class:`Limits`'
def get(self):
return self._get('/limits', 'limits')
'Fetch the public URL from the Compute service for a particular endpoint attribute. If none given, return the first. See tests for sample service catalog.'
def url_for(self, attr=None, filter_value=None, service_type=None, endpoint_type='publicURL', service_name=None, monitor_service_name=None):
matching_endpoints = [] if ('endpoints' in self.catalog): for endpoint in self.catalog['endpoints']: if ((not filter_value) or (endpoint[attr] == filter_value)): matching_endpoints.append(endpoint) if (not matching_endpoints): raise monitorclient.exception...
'Run before each test.'
def setUp(self):
super(ShellTest, self).setUp() for var in self.FAKE_ENV: self.useFixture(fixtures.EnvironmentVariable(var, self.FAKE_ENV[var])) self.shell = shell.OpenStackMonitorShell() self.old_get_client_class = client.get_client_class client.get_client_class = (lambda *_: fakes.FakeClient)
'Run before each test.'
def setUp(self):
super(ShellTest, self).setUp() for var in self.FAKE_ENV: self.useFixture(fixtures.EnvironmentVariable(var, self.FAKE_ENV[var])) self.shell = shell.OpenStackMonitorShell() self.old_get_client_class = client.get_client_class client.get_client_class = (lambda *_: fakes.FakeClient)
'Assert than an API method was just called.'
def assert_called(self, method, url, body=None, pos=(-1), **kwargs):
expected = (method, url) called = self.client.callstack[pos][0:2] assert self.client.callstack, ('Expected %s %s but no calls were made.' % expected) assert (expected == called), ('Expected %s %s; got %s %s' % (expected + called)) if (body is not None): as...
'Assert than an API method was called anytime in the test.'
def assert_called_anytime(self, method, url, body=None):
expected = (method, url) assert self.client.callstack, ('Expected %s %s but no calls were made.' % expected) found = False for entry in self.client.callstack: if (expected == entry[0:2]): found = True break assert found, ('Expected %s %s; ...
'The completion cache store items that can be used for bash autocompletion, like UUIDs or human-friendly IDs. A resource listing will clear and repopulate the cache. A resource create will append to the cache. Delete is not handled because listings are assumed to be performed often enough to keep the cache reasonably u...
@contextlib.contextmanager def completion_cache(self, cache_type, obj_class, mode):
base_dir = utils.env('ENERGYCLIENT_UUID_CACHE_DIR', default='~/.monitorclient') username = utils.env('OS_USERNAME', 'ENERGY_USERNAME') url = utils.env('OS_URL', 'ENERGY_URL') uniqifier = hashlib.md5((username + url)).hexdigest() cache_dir = os.path.expanduser(os.path.join(base_dir, uniqifier)) t...
'Find a single item with attributes matching ``**kwargs``. This isn\'t very efficient: it loads the entire list then filters on the Python side.'
def find(self, **kwargs):
matches = self.findall(**kwargs) num_matches = len(matches) if (num_matches == 0): msg = ('No %s matching %s.' % (self.resource_class.__name__, kwargs)) raise exceptions.NotFound(404, msg) elif (num_matches > 1): raise exceptions.NoUniqueMatch else: return ma...
'Find all items with attributes matching ``**kwargs``. This isn\'t very efficient: it loads the entire list then filters on the Python side.'
def findall(self, **kwargs):
found = [] searches = kwargs.items() for obj in self.list(): try: if all(((getattr(obj, attr) == value) for (attr, value) in searches)): found.append(obj) except AttributeError: continue return found
'Subclasses may override this provide a pretty ID which can be used for bash completion.'
@property def human_id(self):
if (('name' in self.__dict__) and self.HUMAN_ID): return utils.slugify(self.name) return None
'Determine the api version that we should use.'
def _choose_api_version(self):
if self._conf_get('auth_version'): version_to_use = self._conf_get('auth_version') self.LOG.info('Auth Token proceeding with requested %s apis', version_to_use) else: version_to_use = None versions_supported_by_server = self._get_supported_versions() if ...
'Remove headers so a user can\'t fake authentication. :param env: wsgi request environment'
def _remove_auth_headers(self, env):
auth_headers = ('X-Identity-Status', 'X-Domain-Id', 'X-Domain-Name', 'X-Project-Id', 'X-Project-Name', 'X-Project-Domain-Id', 'X-Project-Domain-Name', 'X-User-Id', 'X-User-Name', 'X-User-Domain-Id', 'X-User-Domain-Name', 'X-Roles', 'X-Service-Catalog', 'X-User', 'X-Tenant-Id', 'X-Tenant-Name', 'X-Tenant', 'X-Role')...
'Get token id from request. :param env: wsgi request environment :return token id :raises InvalidUserToken if no token is provided in request'
def _get_user_token_from_header(self, env):
token = self._get_header(env, 'X-Auth-Token', self._get_header(env, 'X-Storage-Token')) if token: return token else: if (not self.delay_auth_decision): self.LOG.warn('Unable to find authentication token in headers') self.LOG.debug('Headers: %s', e...
'Redirect client to auth server. :param env: wsgi request environment :param start_response: wsgi response callback :returns HTTPUnauthorized http response'
def _reject_request(self, env, start_response):
headers = [('WWW-Authenticate', ("Keystone uri='%s'" % self.auth_uri))] resp = webob.exc.HTTPUnauthorized('Authentication required', headers) return resp(env, start_response)
'Return admin token, possibly fetching a new one. if self.admin_token_expiry is set from fetching an admin token, check it for expiration, and request a new token is the existing token is about to expire. :return admin token id :raise ServiceError when unable to retrieve token from monitor'
def get_admin_token(self):
if self.admin_token_expiry: if will_expire_soon(self.admin_token_expiry): self.admin_token = None if (not self.admin_token): (self.admin_token, self.admin_token_expiry) = self._request_admin_token() return self.admin_token
'HTTP request helper used to make unspecified content type requests. :param method: http method :param path: relative request url :return (http response object, response body) :raise ServerError when unable to communicate with monitor'
def _http_request(self, method, path, **kwargs):
conn = self._get_http_connection() RETRIES = 3 retry = 0 while True: try: conn.request(method, path, **kwargs) response = conn.getresponse() body = response.read() break except Exception as e: if (retry == RETRIES): ...
'HTTP request helper used to make json requests. :param method: http method :param path: relative request url :param body: dict to encode to json as request body. Optional. :param additional_headers: dict of additional headers to send with http request. Optional. :return (http response object, response body parsed as j...
def _json_request(self, method, path, body=None, additional_headers=None):
kwargs = {'headers': {'Content-type': 'application/json', 'Accept': 'application/json'}} if additional_headers: kwargs['headers'].update(additional_headers) if body: kwargs['body'] = jsonutils.dumps(body) path = (self.auth_admin_prefix + path) (response, body) = self._http_request(me...
'Retrieve new token as admin user from monitor. :return token id upon success :raises ServerError when unable to communicate with monitor Irrespective of the auth version we are going to use for the user token, for simplicity we always use a v2 admin token to validate the user token.'
def _request_admin_token(self):
params = {'auth': {'passwordCredentials': {'username': self.admin_user, 'password': self.admin_password}, 'tenantName': self.admin_tenant_name}} (response, data) = self._json_request('POST', '/v2.0/tokens', body=params) try: token = data['access']['token']['id'] expiry = data['access']['toke...
'Authenticate user using PKI :param user_token: user\'s token id :param retry: Ignored, as it is not longer relevant :return uncrypted body of the token if the token is valid :raise InvalidUserToken if token is rejected :no longer raises ServiceError since it no longer makes RPC'
def _validate_user_token(self, user_token, retry=True):
try: token_id = cms.cms_hash_token(user_token) cached = self._cache_get(token_id) if cached: return cached if cms.is_ans1_token(user_token): verified = self.verify_signed_token(user_token) data = json.loads(verified) else: data ...
'Convert token object into headers. Build headers that represent authenticated user - see main doc info at start of file for details of headers to be defined. :param token_info: token object returned by monitor on authentication :raise InvalidUserToken when unable to parse token object'
def _build_user_headers(self, token_info):
def get_tenant_info(): 'Returns a (tenant_id, tenant_name) tuple from context.' def essex(): 'Essex puts the tenant ID and name on the token.' return (token['tenant']['id'], token['tenant']['name']) def pre_diablo(): ...
'Convert header to wsgi env variable. :param key: http header name (ex. \'X-Auth-Token\') :return wsgi env variable name (ex. \'HTTP_X_AUTH_TOKEN\')'
def _header_to_env_var(self, key):
return ('HTTP_%s' % key.replace('-', '_').upper())
'Add http headers to environment.'
def _add_headers(self, env, headers):
for (k, v) in headers.iteritems(): env_key = self._header_to_env_var(k) env[env_key] = v
'Remove http headers from environment.'
def _remove_headers(self, env, keys):
for k in keys: env_key = self._header_to_env_var(k) try: del env[env_key] except KeyError: pass
'Get http header from environment.'
def _get_header(self, env, key, default=None):
env_key = self._header_to_env_var(key) return env.get(env_key, default)
'Encrypt or sign data if necessary.'
def _protect_cache_value(self, token, data):
try: if (self._memcache_security_strategy == 'ENCRYPT'): return memcache_crypt.encrypt_data(token, self._memcache_secret_key, data) elif (self._memcache_security_strategy == 'MAC'): return memcache_crypt.sign_data(token, data) else: return data except:...
'Decrypt or verify signed data if necessary.'
def _unprotect_cache_value(self, token, data):
if (data is None): return data try: if (self._memcache_security_strategy == 'ENCRYPT'): return memcache_crypt.decrypt_data(token, self._memcache_secret_key, data) elif (self._memcache_security_strategy == 'MAC'): return memcache_crypt.verify_signed_data(token, dat...
'Return the cache key. Do not use clear token as key if memcache protection is on.'
def _get_cache_key(self, token):
htoken = token if (self._memcache_security_strategy in ('ENCRYPT', 'MAC')): derv_token = (token + self._memcache_secret_key) htoken = memcache_crypt.hash_data(derv_token) return ('tokens/%s' % htoken)
'Return token information from cache. If token is invalid raise InvalidUserToken return token only if fresh (not expired).'
def _cache_get(self, token):
if (self._cache and token): key = self._get_cache_key(token) cached = self._cache.get(key) cached = self._unprotect_cache_value(token, cached) if (cached == 'invalid'): self.LOG.debug('Cached Token %s is marked unauthorized', token) raise Invali...
'Store value into memcache.'
def _cache_store(self, token, data, expires=None):
key = self._get_cache_key(token) data = self._protect_cache_value(token, data) data_to_store = data if expires: data_to_store = (data, expires) if self._use_monitor_cache: self._cache.set(key, data_to_store, time=self.token_cache_time) else: self._cache.set(key, data_to_s...
'Put token data into the cache. Stores the parsed expire date in cache allowing quick check of token freshness on retrieval.'
def _cache_put(self, token, data, expires):
if self._cache: self.LOG.debug('Storing %s token in memcache', token) self._cache_store(token, data, expires)
'Store invalid token in cache.'
def _cache_store_invalid(self, token):
if self._cache: self.LOG.debug('Marking token %s as unauthorized in memcache', token) self._cache_store(token, 'invalid')
'Authenticate user token with monitor. :param user_token: user\'s token id :param retry: flag that forces the middleware to retry user authentication when an indeterminate response is received. Optional. :return token object received from monitor on success :raise InvalidUserToken if token is rejected :raise ServiceErr...
def verify_uuid_token(self, user_token, retry=True):
if (not self.auth_version): self.auth_version = self._choose_api_version() if (self.auth_version == 'v3.0'): headers = {'X-Auth-Token': self.get_admin_token(), 'X-Subject-Token': safe_quote(user_token)} (response, data) = self._json_request('GET', '/v3/auth/tokens', additional_headers=he...
'Indicate whether the token appears in the revocation list.'
def is_signed_token_revoked(self, signed_text):
revocation_list = self.token_revocation_list revoked_tokens = revocation_list.get('revoked', []) if (not revoked_tokens): return revoked_ids = (x['id'] for x in revoked_tokens) token_id = utils.hash_signed_token(signed_text) for revoked_id in revoked_ids: if (token_id == revoked_...
'Verifies the signature of the provided data\'s IAW CMS syntax. If either of the certificate files are missing, fetch them and retry.'
def cms_verify(self, data):
while True: try: output = cms.cms_verify(data, self.signing_cert_file_name, self.ca_file_name) except cms.subprocess.CalledProcessError as err: if self.cert_file_missing(err.output, self.signing_cert_file_name): self.fetch_signing_cert() contin...
'Check that the token is unrevoked and has a valid signature.'
def verify_signed_token(self, signed_text):
if self.is_signed_token_revoked(signed_text): raise InvalidUserToken('Token has been revoked') formatted = cms.token_to_cms(signed_text) return self.cms_verify(formatted)
'Save a revocation list to memory and to disk. :param value: A json-encoded revocation list'
@token_revocation_list.setter def token_revocation_list(self, value):
self._token_revocation_list = jsonutils.loads(value) self.token_revocation_list_fetched_time = timeutils.utcnow() with open(self.revoked_file_name, 'w') as f: f.write(value)
'See what the auth service told us and process the response. We may get redirected to another site, fail or actually get back a service catalog with a token and our endpoints.'
def _extract_service_catalog(self, url, resp, body, extract_token=True):
if (resp.status_code == 200): try: self.auth_url = url self.service_catalog = service_catalog.ServiceCatalog(body) print 'JIYOU in _extract_service_catalog' print self.service_catalog print self.service_type print self.service_nam...
'We have a token, but don\'t know the final endpoint for the region. We have to go back to the auth service and ask again. This request requires an admin-level token to work. The proxy token supplied could be from a low-level enduser. We can\'t get this from the keystone service endpoint, we have to use the admin endpo...
def _fetch_endpoints_from_auth(self, url):
url = '/'.join([url, 'tokens', ('%s?belongsTo=%s' % (self.proxy_token, self.proxy_tenant_id))]) self._logger.debug(('Using Endpoint URL: %s' % url)) (resp, body) = self.request(url, 'GET', headers={'X-Auth-Token': self.auth_token}) return self._extract_service_catalog(url, resp, body, extract_t...
'Authenticate against a v2.0 auth service.'
def _v2_auth(self, url):
body = {'auth': {'passwordCredentials': {'username': self.user, 'password': self.password}}} if self.projectid: body['auth']['tenantName'] = self.projectid elif self.tenant_id: body['auth']['tenantId'] = self.tenant_id self._authenticate(url, body)
'Authenticate against the Rackspace auth service.'
def _rax_auth(self, url):
body = {'auth': {'RAX-KSKEY:apiKeyCredentials': {'username': self.user, 'apiKey': self.password, 'tenantName': self.projectid}}} self._authenticate(url, body)
'Authenticate and extract the service catalog.'
def _authenticate(self, url, body):
token_url = (url + '/tokens') (resp, body) = self.request(token_url, 'POST', body=body, allow_redirects=True) return self._extract_service_catalog(url, resp, body)
'error(message: string) Prints a usage message incorporating the message to stderr and exits.'
def error(self, message):
self.print_usage(sys.stderr) choose_from = ' (choose from' progparts = self.prog.partition(' ') self.exit(2, ("error: %(errmsg)s\nTry '%(mainp)s help %(subp)s' for more information.\n" % {'errmsg': message.split(choose_from)[0], 'mainp': progparts[0], 'subp': progparts[2]})...
'Run hooks for all registered extensions.'
def _run_extension_hooks(self, hook_type, *args, **kwargs):
for extension in self.extensions: extension.run_hooks(hook_type, *args, **kwargs)