desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Checks if a role has been granted on either a domain or project.'
@controller.protected def check_grant(self, context, role_id, user_id=None, group_id=None, domain_id=None, project_id=None):
self._require_domain_xor_project(domain_id, project_id) self._require_user_xor_group(user_id, group_id) self.identity_api.get_grant(context, role_id, user_id, group_id, domain_id, project_id)
'Revokes a role from user/group on either a domain or project.'
@controller.protected def revoke_grant(self, context, role_id, user_id=None, group_id=None, domain_id=None, project_id=None):
self._require_domain_xor_project(domain_id, project_id) self._require_user_xor_group(user_id, group_id) self.identity_api.delete_grant(context, role_id, user_id, group_id, domain_id, project_id) if user_id: self._delete_tokens_for_user(context, user_id) else: self._delete_tokens_for_...
'Creates a new service. :raises: keystone.exception.Conflict'
def create_service(self, service_id, service_ref):
raise exception.NotImplemented()
'List all services. :returns: list of service_refs or an empty list.'
def list_services(self):
raise exception.NotImplemented()
'Get service by id. :returns: service_ref dict :raises: keystone.exception.ServiceNotFound'
def get_service(self, service_id):
raise exception.NotImplemented()
'Update service by id. :returns: service_ref dict :raises: keystone.exception.ServiceNotFound'
def update_service(self, service_id):
raise exception.NotImplemented()
'Deletes an existing service. :raises: keystone.exception.ServiceNotFound'
def delete_service(self, service_id):
raise exception.NotImplemented()
'Creates a new endpoint for a service. :raises: keystone.exception.Conflict, keystone.exception.ServiceNotFound'
def create_endpoint(self, endpoint_id, endpoint_ref):
raise exception.NotImplemented()
'Get endpoint by id. :returns: endpoint_ref dict :raises: keystone.exception.EndpointNotFound'
def get_endpoint(self, endpoint_id):
raise exception.NotImplemented()
'List all endpoints. :returns: list of endpoint_refs or an empty list.'
def list_endpoints(self):
raise exception.NotImplemented()
'Get endpoint by id. :returns: endpoint_ref dict :raises: keystone.exception.EndpointNotFound keystone.exception.ServiceNotFound'
def update_endpoint(self, endpoint_id, endpoint_ref):
raise exception.NotImplemented()
'Deletes an endpoint for a service. :raises: keystone.exception.EndpointNotFound'
def delete_endpoint(self, endpoint_id):
raise exception.NotImplemented()
'Retrieve and format the current service catalog. Example:: { \'RegionOne\': {\'compute\': { \'adminURL\': u\'http://host:8774/v1.1/tenantid\', \'internalURL\': u\'http://host:8774/v1.1/tenant_id\', \'name\': \'Compute Service\', \'publicURL\': u\'http://host:8774/v1.1/tenantid\'}, \'ec2\': { \'adminURL\': \'http://hos...
def get_catalog(self, user_id, tenant_id, metadata=None):
raise exception.NotImplemented()
'Retrieve and format the current V3 service catalog. Example:: "endpoints": [ "interface": "public", "id": "--endpoint-id--", "region": "RegionOne", "url": "http://external:8776/v1/--project-id--" "interface": "internal", "id": "--endpoint-id--", "region": "RegionOne", "url": "http://internal:8776/v1/--project-id--" "i...
def get_v3_catalog(self, user_id, tenant_id, metadata=None):
raise exception.NotImplemented()
'Merge matching v3 endpoint refs into legacy refs.'
def get_endpoints(self, context):
self.assert_admin(context) legacy_endpoints = {} for endpoint in self.catalog_api.list_endpoints(context): if (not endpoint.get('legacy_endpoint_id')): continue if (endpoint['legacy_endpoint_id'] not in legacy_endpoints): legacy_ep = endpoint.copy() legacy...
'Create three v3 endpoint refs based on a legacy ref.'
def create_endpoint(self, context, endpoint):
self.assert_admin(context) self._require_attribute(endpoint, 'publicurl') legacy_endpoint_ref = endpoint.copy() urls = {} for i in INTERFACES: if (endpoint.get(('%surl' % i)) is not None): urls[i] = endpoint.pop(('%surl' % i)) elif (('%surl' % i) in endpoint): ...
'Delete up to three v3 endpoint refs based on a legacy ref ID.'
def delete_endpoint(self, context, endpoint_id):
self.assert_admin(context) deleted_at_least_one = False for endpoint in self.catalog_api.list_endpoints(context): if (endpoint['legacy_endpoint_id'] == endpoint_id): self.catalog_api.delete_endpoint(context, endpoint['id']) deleted_at_least_one = True if (not deleted_at_l...
'Authenticate user and return an authentication context. :param context: keystone\'s request context :auth_payload: the content of the authentication for a given method :auth_context: user authentication context, a dictionary shared by all plugins. It contains "method_names" and "extras" by default. "method_names" is a...
def authenticate(self, context, auth_payload, auth_context):
raise exception.Unauthorized()
'Validate and normalize scope data'
def _validate_and_normalize_scope_data(self):
if ('scope' not in self.auth): return if (sum([('project' in self.auth['scope']), ('domain' in self.auth['scope']), ('OS-TRUST:trust' in self.auth['scope'])]) != 1): raise exception.ValidationError(attribute='project, domain, or OS-TRUST:trust', target='scope') if ('project' in self...
'Make sure "auth" is valid.'
def _validate_and_normalize_auth_data(self):
if (not self.auth): raise exception.ValidationError(attribute='auth', target='request body') self._validate_auth_methods() self._validate_and_normalize_scope_data()
'Returns the identity method names. :returns: list of auth method names'
def get_method_names(self):
return self.auth['identity']['methods']
'Get the auth method payload. :returns: auth method payload'
def get_method_data(self, method):
if (method not in self.auth['identity']['methods']): raise exception.ValidationError(attribute=method_name, target='identity') return self.auth['identity'][method]
'Get scope information. Verify and return the scoping information. :returns: (domain_id, project_id, trust_ref). If scope to a project, (None, project_id, None) will be returned. If scoped to a domain, (domain_id, None,None) will be returned. If scoped to a trust, (None, project_id, trust_ref), Will be returned, where ...
def get_scope(self):
return self._scope_data
'Set scope information.'
def set_scope(self, domain_id=None, project_id=None, trust=None):
if (domain_id and project_id): msg = _('Scoping to both domain and project is not allowed') raise ValueError(msg) if (domain_id and trust): msg = _('Scoping to both domain and trust is not allowed') raise ValueError(msg) if (pro...
'Authenticate user and issue a token.'
def authenticate_for_token(self, context, auth=None):
try: auth_info = AuthInfo(context, auth=auth) auth_context = {'extras': {}, 'method_names': []} self.authenticate(context, auth_info, auth_context) self._check_and_set_default_scoping(context, auth_info, auth_context) (token_id, token_data) = token_factory.create_token(contex...
'Authenticate user.'
def authenticate(self, context, auth_info, auth_context):
if ('REMOTE_USER' in context): self._build_remote_user_auth_context(context, auth_info, auth_context) return auth_response = {'methods': []} for method_name in auth_info.get_method_names(): method = get_auth_method(method_name) resp = method.authenticate(context, auth_info.ge...
'Try to authenticate against the identity backend.'
def authenticate(self, context, auth_payload, user_context):
user_info = UserAuthInfo(context, auth_payload) user_auth_data = self.identity_api.authenticate(context=context, user_id=user_info.user_id, password=user_info.password) if ('user_id' not in user_context): user_context['user_id'] = user_info.user_id
'Validate a signed EC2 request and provide a token. Other services (such as Nova) use this **admin** call to determine if a request they signed received is from a valid user. If it is a valid signature, an openstack token that maps to the user/tenant is returned to the caller, along with all the other details returned ...
def authenticate(self, context, credentials=None, ec2Credentials=None):
if ((not credentials) and ec2Credentials): credentials = ec2Credentials if ('access' not in credentials): raise exception.Unauthorized(message='EC2 signature not supplied.') creds_ref = self._get_credentials(context, credentials['access']) self.check_signature(creds_ref, credent...
'Create a secret/access pair for use with ec2 style auth. Generates a new set of credentials that map the the user/tenant pair. :param context: standard context :param user_id: id of user :param tenant_id: id of tenant :returns: credential: dict of ec2 credential'
def create_credential(self, context, user_id, tenant_id):
if (not self._is_admin(context)): self._assert_identity(context, user_id) self._assert_valid_user_id(context, user_id) self._assert_valid_project_id(context, tenant_id) cred_ref = {'user_id': user_id, 'tenant_id': tenant_id, 'access': uuid.uuid4().hex, 'secret': uuid.uuid4().hex} self.ec2_ap...
'List all credentials for a user. :param context: standard context :param user_id: id of user :returns: credentials: list of ec2 credential dicts'
def get_credentials(self, context, user_id):
if (not self._is_admin(context)): self._assert_identity(context, user_id) self._assert_valid_user_id(context, user_id) return {'credentials': self.ec2_api.list_credentials(context, user_id)}
'Retrieve a user\'s access/secret pair by the access key. Grab the full access/secret pair for a given access key. :param context: standard context :param user_id: id of user :param credential_id: access key for credentials :returns: credential: dict of ec2 credential'
def get_credential(self, context, user_id, credential_id):
if (not self._is_admin(context)): self._assert_identity(context, user_id) self._assert_valid_user_id(context, user_id) creds = self._get_credentials(context, credential_id) return {'credential': creds}
'Delete a user\'s access/secret pair. Used to revoke a user\'s access/secret pair :param context: standard context :param user_id: id of user :param credential_id: access key for credentials :returns: bool: success'
def delete_credential(self, context, user_id, credential_id):
if (not self._is_admin(context)): self._assert_identity(context, user_id) self._assert_owner(context, user_id, credential_id) self._assert_valid_user_id(context, user_id) self._get_credentials(context, credential_id) return self.ec2_api.delete_credential(context, credential_id)
'Return credentials from an ID. :param context: standard context :param credential_id: id of credential :raises exception.Unauthorized: when credential id is invalid :returns: credential: dict of ec2 credential.'
def _get_credentials(self, context, credential_id):
creds = self.ec2_api.get_credential(context, credential_id) if (not creds): raise exception.Unauthorized(message='EC2 access key not found.') return creds
'Check that the provided token belongs to the user. :param context: standard context :param user_id: id of user :raises exception.Forbidden: when token is invalid'
def _assert_identity(self, context, user_id):
try: token_ref = self.token_api.get_token(context=context, token_id=context['token_id']) except exception.TokenNotFound as e: raise exception.Unauthorized(e) if (token_ref['user'].get('id') != user_id): raise exception.Forbidden('Token belongs to another user')
'Wrap admin assertion error return statement. :param context: standard context :returns: bool: success'
def _is_admin(self, context):
try: self.assert_admin(context) return True except exception.Forbidden: return False
'Ensure the provided user owns the credential. :param context: standard context :param user_id: expected credential owner :param credential_id: id of credential object :raises exception.Forbidden: on failure'
def _assert_owner(self, context, user_id, credential_id):
cred_ref = self.ec2_api.get_credential(context, credential_id) if (not (user_id == cred_ref['user_id'])): raise exception.Forbidden('Credential belongs to another user')
'Ensure a valid user id. :param context: standard context :param user_id: expected credential owner :raises exception.UserNotFound: on failure'
def _assert_valid_user_id(self, context, user_id):
user_ref = self.identity_api.get_user(context=context, user_id=user_id) if (not user_ref): raise exception.UserNotFound(user_id=user_id)
'Ensure a valid tenant id. :param context: standard context :param tenant_id: expected tenant :raises exception.ProjectNotFound: on failure'
def _assert_valid_project_id(self, context, tenant_id):
tenant_ref = self.identity_api.get_project(context=context, tenant_id=tenant_id) if (not tenant_ref): raise exception.ProjectNotFound(project_id=tenant_id)
'Retrieve all previously-captured statistics for an interface.'
def get_stats(self, api):
raise exception.NotImplemented()
'Update statistics for an interface.'
def set_stats(self, api, stats_ref):
raise exception.NotImplemented()
'Increment the counter for an individual statistic.'
def increment_stat(self, api, category, value):
raise exception.NotImplemented()
'Collect each attribute from the given object.'
def capture_stats(self, host, obj, attributes):
for attribute in attributes: self.stats_api.increment_stat(None, self._resolve_api(host), attribute, getattr(obj, attribute))
'Monitor incoming request attributes.'
def process_request(self, request):
self.capture_stats(request.host, request, self.request_attributes)
'Monitor outgoing response attributes.'
def process_response(self, request, response):
self.capture_stats(request.host, response, self.response_attributes) return response
'Increment a statistic counter, or create it if it doesn\'t exist.'
def increment_stat(self, api, category, value):
stats = self.get_stats(api) stats.setdefault(category, dict()) counter = stats[category].setdefault(value, 0) stats[category][value] = (counter + 1) self.set_stats(api, stats)
'Any distribution-specific post-processing gets done here. In particular, this is useful for applying patches to code inside the venv.'
def post_process(self):
pass
'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)
'Print arguments for bash_completion. Prints all of the commands and options to stdout so that the monitor.bash_completion script doesn\'t have to hard code them.'
def do_bash_completion(self, args):
commands = set() options = set() for (sc_str, sc) in self.subcommands.items(): commands.add(sc_str) for option in sc._optionals._option_string_actions.keys(): options.add(option) commands.remove('bash-completion') commands.remove('bash_completion') print ' '.join((...
'Display help about this program or one of its subcommands.'
@utils.arg('command', metavar='<subcommand>', nargs='?', help='Display help for <subcommand>') def do_help(self, args):
if args.command: if (args.command in self.subcommands): self.subcommands[args.command].print_help() else: raise exc.CommandError(("'%s' is not a valid subcommand" % args.command)) else: self.parser.print_help()
'Ignores the passed in args.'
def __init__(self, *args, **kwargs):
self.cache = {}
'Retrieves the value for a key or None. this expunges expired keys during each get'
def get(self, key):
now = timeutils.utcnow_ts() for k in self.cache.keys(): (timeout, _value) = self.cache[k] if (timeout and (now >= timeout)): del self.cache[k] return self.cache.get(key, (0, None))[1]
'Sets the value for a key.'
def set(self, key, value, time=0, min_compress_len=0):
timeout = 0 if (time != 0): timeout = (timeutils.utcnow_ts() + time) self.cache[key] = (timeout, value) return True
'Sets the value for a key if it doesn\'t exist.'
def add(self, key, value, time=0, min_compress_len=0):
if (self.get(key) is not None): return False return self.set(key, value, time, min_compress_len)
'Increments the value for a key.'
def incr(self, key, delta=1):
value = self.get(key) if (value is None): return None new_value = (int(value) + delta) self.cache[key] = (self.cache[key][0], str(new_value)) return new_value
'Deletes the value associated with a key.'
def delete(self, key, time=0):
if (key in self.cache): del self.cache[key]
'Object that understands versioning for a package :param package: name of the python package, such as glance, or python-glanceclient'
def __init__(self, package):
self.package = package self.release = None self.version = None self._cached_version = None
'Make the VersionInfo object behave like a string.'
def __str__(self):
return self.version_string()
'Include the name.'
def __repr__(self):
return ('VersionInfo(%s:%s)' % (self.package, self.version_string()))
'Get the version of the package from the pkg_resources record associated with the package.'
def _get_version_from_pkg_resources(self):
try: requirement = pkg_resources.Requirement.parse(self.package) provider = pkg_resources.get_provider(requirement) return provider.version except pkg_resources.DistributionNotFound: from monitorclient.openstack.common import setup return setup.get_version(self.package)
'Return the full version of the package including suffixes indicating VCS status.'
def release_string(self):
if (self.release is None): self.release = self._get_version_from_pkg_resources() return self.release
'Return the short version minus any alpha/beta tags.'
def version_string(self):
if (self.version is None): parts = [] for part in self.release_string().split('.'): if part[0].isdigit(): parts.append(part) else: break self.version = '.'.join(parts) return self.version
'Generate an object which will expand in a string context to the results of version_string(). We do this so that don\'t call into pkg_resources every time we start up a program when passing version information into the CONF constructor, but rather only do the calculation when and if a version is requested'
def cached_version_string(self, prefix=''):
if (not self._cached_version): self._cached_version = ('%s%s' % (prefix, self.version_string())) return self._cached_version
'Restore a backup to a monitor. :param backup_id: The ID of the backup to restore. :param monitor_id: The ID of the monitor to restore the backup to. :rtype: :class:`Restore`'
def restore(self, backup_id, monitor_id=None):
body = {'restore': {'monitor_id': monitor_id}} return self._create(('/backups/%s/restore' % backup_id), body, 'restore')
'QuotaClassSet does not have a \'id\' attribute but base.Resource needs it to self-refresh and QuotaSet is indexed by class_name'
@property def id(self):
return self.class_name