sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _health_check_thread(self): """ Health checker thread that pings the service every 30 seconds :return: None """ while self._run_health_checker: response = self._health_check(Health_pb2.HealthCheckRequest(service='predix-event-hub.grpc.health')) logging...
Health checker thread that pings the service every 30 seconds :return: None
entailment
def create_temp_space(): """ Create a new temporary cloud foundry space for a project. """ # Truncating uuid to just take final 12 characters since space name # is used to name services and there is a 50 character limit on instance # names. # MAINT: hacky with possible collisions u...
Create a new temporary cloud foundry space for a project.
entailment
def _get_spaces(self): """ Get the marketplace services. """ guid = self.api.config.get_organization_guid() uri = '/v2/organizations/%s/spaces' % (guid) return self.api.get(uri)
Get the marketplace services.
entailment
def target(self): """ Target the current space for any forthcoming Cloud Foundry operations. """ # MAINT: I don't like this, but will deal later os.environ['PREDIX_SPACE_GUID'] = self.guid os.environ['PREDIX_SPACE_NAME'] = self.name os.environ['PREDIX_ORGA...
Target the current space for any forthcoming Cloud Foundry operations.
entailment
def get_spaces(self): """ Return a flat list of the names for spaces in the organization. """ self.spaces = [] for resource in self._get_spaces()['resources']: self.spaces.append(resource['entity']['name']) return self.spaces
Return a flat list of the names for spaces in the organization.
entailment
def create_space(self, space_name, add_users=True): """ Create a new space with the given name in the current target organization. """ body = { 'name': space_name, 'organization_guid': self.api.config.get_organization_guid() } # MAINT: may...
Create a new space with the given name in the current target organization.
entailment
def delete_space(self, name=None, guid=None): """ Delete the current space, or a space with the given name or guid. """ if not guid: if name: spaces = self._get_spaces() for space in spaces['resources']: if space['e...
Delete the current space, or a space with the given name or guid.
entailment
def get_services(self): """ Returns a flat list of the service names available from the marketplace for this space. """ services = [] for resource in self._get_services()['resources']: services.append(resource['entity']['label']) return services
Returns a flat list of the service names available from the marketplace for this space.
entailment
def _get_instances(self, page_number=None): """ Returns the service instances activated in this space. """ instances = [] uri = '/v2/spaces/%s/service_instances' % self.guid json_response = self.api.get(uri) instances += json_response['resources'] while js...
Returns the service instances activated in this space.
entailment
def get_instances(self): """ Returns a flat list of the names of services created in this space. """ services = [] for resource in self._get_instances(): services.append(resource['entity']['name']) return services
Returns a flat list of the names of services created in this space.
entailment
def has_service_of_type(self, service_type): """ Tests whether a service instance exists for the given service. """ summary = self.get_space_summary() for instance in summary['services']: if 'service_plan' in instance: if service_type == instan...
Tests whether a service instance exists for the given service.
entailment
def purge(self): """ Remove all services and apps from the space. Will leave the space itself, call delete_space() if you want to remove that too. Similar to `cf delete-space -f <space-name>`. """ logging.warning("Purging all services from space %s" % ...
Remove all services and apps from the space. Will leave the space itself, call delete_space() if you want to remove that too. Similar to `cf delete-space -f <space-name>`.
entailment
def create(self, max_wait=300, allocated_storage=None, encryption_at_rest=None, restore_to_time=None, **kwargs): """ Create an instance of the PostgreSQL service with the typical starting settings. :param max_wait: service is created asynchronously, so will only wait ...
Create an instance of the PostgreSQL service with the typical starting settings. :param max_wait: service is created asynchronously, so will only wait this number of seconds before giving up. :param allocated_storage: int for GBs to be allocated for storage :param encrypti...
entailment
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: A predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry ...
Add useful details to the manifest about this service so that it can be used in an application. :param manifest: A predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app.
entailment
def create(self, asset, timeseries, client_id, client_secret, ui_client_id=None, ui_client_secret=None): """ Create an instance of the Analytics Framework Service with the typical starting settings. If not provided, will reuse the runtime client for the ui as well. ...
Create an instance of the Analytics Framework Service with the typical starting settings. If not provided, will reuse the runtime client for the ui as well.
entailment
def _find_service_name(self): """ For cloud operations there is support for multiple pools of resources dedicated to logstash. The service name as a result follows the pattern logstash-{n} where n is some number. We can find it from the service marketplace. """ ...
For cloud operations there is support for multiple pools of resources dedicated to logstash. The service name as a result follows the pattern logstash-{n} where n is some number. We can find it from the service marketplace.
entailment
def add_to_manifest(self, manifest): """ Add to the manifest to make sure it is bound to the application. """ manifest.add_service(self.service.name) manifest.write_manifest()
Add to the manifest to make sure it is bound to the application.
entailment
def _get_zone_id(self): """ Returns the Predix Zone Id for the service that is a required header in service calls. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) predix_asset = services['predix-asset'][0]['credentia...
Returns the Predix Zone Id for the service that is a required header in service calls.
entailment
def get_collections(self): """ Returns a flat list of the names of collections in the asset service. .. ['wind-turbines', 'jet-engines'] """ collections = [] for result in self._get_collections(): collections.append(result['collection'])...
Returns a flat list of the names of collections in the asset service. .. ['wind-turbines', 'jet-engines']
entailment
def get_collection(self, collection, filter=None, fields=None, page_size=None): """ Returns a specific collection from the asset service with the given collection endpoint. Supports passing through parameters such as... - filters such as "name=Vesuvius" following GEL...
Returns a specific collection from the asset service with the given collection endpoint. Supports passing through parameters such as... - filters such as "name=Vesuvius" following GEL spec - fields such as "uri,description" comma delimited - page_size such as "100" (the default)
entailment
def create_guid(self, collection=None): """ Returns a new guid for use in posting a new asset to a collection. """ guid = str(uuid.uuid4()) if collection: return str.join('/', [collection, guid]) else: return guid
Returns a new guid for use in posting a new asset to a collection.
entailment
def post_collection(self, collection, body): """ Creates a new collection. This is mostly just transport layer and passes collection and body along. It presumes the body already has generated. The collection is *not* expected to have the id. """ assert isinstan...
Creates a new collection. This is mostly just transport layer and passes collection and body along. It presumes the body already has generated. The collection is *not* expected to have the id.
entailment
def put_collection(self, collection, body): """ Updates an existing collection. The collection being updated *is* expected to include the id. """ uri = self.uri + '/v1' + collection return self.service._put(uri, body)
Updates an existing collection. The collection being updated *is* expected to include the id.
entailment
def delete_collection(self, collection): """ Deletes an existing collection. The collection being updated *is* expected to include the id. """ uri = str.join('/', [self.uri, collection]) return self.service._delete(uri)
Deletes an existing collection. The collection being updated *is* expected to include the id.
entailment
def patch_collection(self, collection, changes): """ Will make specific updates to a record based on JSON Patch documentation. https://tools.ietf.org/html/rfc6902 the format of changes is something like:: [{ 'op': 'add', 'path': ...
Will make specific updates to a record based on JSON Patch documentation. https://tools.ietf.org/html/rfc6902 the format of changes is something like:: [{ 'op': 'add', 'path': '/newfield', 'value': 'just added' }]
entailment
def save(self, collection): """ Save an asset collection to the service. """ assert isinstance(collection, predix.data.asset.AssetCollection), "Expected AssetCollection" collection.validate() self.put_collection(collection.uri, collection.__dict__)
Save an asset collection to the service.
entailment
def create_manifest_from_space(self): """ Populate a manifest file generated from details from the cloud foundry space environment. """ space = predix.admin.cf.spaces.Space() summary = space.get_space_summary() for instance in summary['services']: ser...
Populate a manifest file generated from details from the cloud foundry space environment.
entailment
def lock_to_org_space(self): """ Lock the manifest to the current organization and space regardless of Cloud Foundry target. """ self.add_env_var('PREDIX_ORGANIZATION_GUID', self.space.org.guid) self.add_env_var('PREDIX_ORGANIZATION_NAME', self.space.org.name) sel...
Lock the manifest to the current organization and space regardless of Cloud Foundry target.
entailment
def create_uaa(self, admin_secret, **kwargs): """ Creates an instance of UAA Service. :param admin_secret: The secret password for administering the service such as adding clients and users. """ uaa = predix.admin.uaa.UserAccountAuthentication(**kwargs) if no...
Creates an instance of UAA Service. :param admin_secret: The secret password for administering the service such as adding clients and users.
entailment
def create_client(self, client_id=None, client_secret=None, uaa=None): """ Create a client and add it to the manifest. :param client_id: The client id used to authenticate as a client in UAA. :param client_secret: The secret password used by a client to authenti...
Create a client and add it to the manifest. :param client_id: The client id used to authenticate as a client in UAA. :param client_secret: The secret password used by a client to authenticate and generate a UAA token. :param uaa: The UAA to create client with
entailment
def create_timeseries(self, **kwargs): """ Creates an instance of the Time Series Service. """ ts = predix.admin.timeseries.TimeSeries(**kwargs) ts.create() client_id = self.get_client_id() if client_id: ts.grant_client(client_id) ts.add_to_m...
Creates an instance of the Time Series Service.
entailment
def create_asset(self, **kwargs): """ Creates an instance of the Asset Service. """ asset = predix.admin.asset.Asset(**kwargs) asset.create() client_id = self.get_client_id() if client_id: asset.grant_client(client_id) asset.add_to_manifest(s...
Creates an instance of the Asset Service.
entailment
def create_acs(self, **kwargs): """ Creates an instance of the Asset Service. """ acs = predix.admin.acs.AccessControl(**kwargs) acs.create() client_id = self.get_client_id() if client_id: acs.grant_client(client_id) acs.grant_client(client_i...
Creates an instance of the Asset Service.
entailment
def create_weather(self, **kwargs): """ Creates an instance of the Asset Service. """ weather = predix.admin.weather.WeatherForecast(**kwargs) weather.create() client_id = self.get_client_id() if client_id: weather.grant_client(client_id) wea...
Creates an instance of the Asset Service.
entailment
def create_blobstore(self, **kwargs): """ Creates an instance of the BlobStore Service. """ blobstore = predix.admin.blobstore.BlobStore(**kwargs) blobstore.create() blobstore.add_to_manifest(self) return blobstore
Creates an instance of the BlobStore Service.
entailment
def create_logstash(self, **kwargs): """ Creates an instance of the Logging Service. """ logstash = predix.admin.logstash.Logging(**kwargs) logstash.create() logstash.add_to_manifest(self) logging.info('Install Kibana-Me-Logs application by following GitHub instr...
Creates an instance of the Logging Service.
entailment
def create_cache(self, **kwargs): """ Creates an instance of the Cache Service. """ cache = predix.admin.cache.Cache(**kwargs) cache.create(**kwargs) cache.add_to_manifest(self) return cache
Creates an instance of the Cache Service.
entailment
def create_eventhub(self, **kwargs): """ todo make it so the client can be customised to publish/subscribe Creates an instance of eventhub service """ eventhub = predix.admin.eventhub.EventHub(**kwargs) eventhub.create() eventhub.add_to_manifest(self) even...
todo make it so the client can be customised to publish/subscribe Creates an instance of eventhub service
entailment
def get_service_marketplace(self, available=True, unavailable=False, deprecated=False): """ Returns a list of service names. Can return all services, just those supported by PredixPy, or just those not yet supported by PredixPy. :param available: Return the services...
Returns a list of service names. Can return all services, just those supported by PredixPy, or just those not yet supported by PredixPy. :param available: Return the services that are available in PredixPy. (Defaults to True) :param unavailable: Return the services that a...
entailment
def _auto_authenticate(self): """ If we are in an app context we can authenticate immediately. """ client_id = predix.config.get_env_value(predix.app.Manifest, 'client_id') client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret') if client_id and...
If we are in an app context we can authenticate immediately.
entailment
def _get(self, uri, params=None, headers=None): """ Simple GET request for a given path. """ if not headers: headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("HEADERS=" + str(headers)) response = self.session.get(uri, head...
Simple GET request for a given path.
entailment
def _post(self, uri, data): """ Simple POST request for a given path. """ headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("BODY=" + json.dumps(data)) response = self.session.post(uri, headers=headers, data=json.dumps(...
Simple POST request for a given path.
entailment
def _put(self, uri, data): """ Simple PUT operation for a given path. """ headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("BODY=" + json.dumps(data)) response = self.session.put(uri, headers=headers, data=json.dumps(d...
Simple PUT operation for a given path.
entailment
def _delete(self, uri): """ Simple DELETE operation for a given path. """ headers = self._get_headers() response = self.session.delete(uri, headers=headers) # Will return a 204 on successful delete if response.status_code == 204: return response ...
Simple DELETE operation for a given path.
entailment
def _patch(self, uri, data): """ Simple PATCH operation for a given path. The body is expected to list operations to perform to update the data. Operations include: - add - remove - replace - move - copy - test ...
Simple PATCH operation for a given path. The body is expected to list operations to perform to update the data. Operations include: - add - remove - replace - move - copy - test [ { "op": "test", "path": "/a/...
entailment
def _get_resource_uri(self, guid=None): """ Returns the full path that uniquely identifies the resource endpoint. """ uri = self.uri + '/v1/resource' if guid: uri += '/' + urllib.quote_plus(guid) return uri
Returns the full path that uniquely identifies the resource endpoint.
entailment
def get_resource(self, resource_id): """ Returns a specific resource by resource id. """ # resource_id could be a path such as '/asset/123' so quote uri = self._get_resource_uri(guid=resource_id) return self.service._get(uri)
Returns a specific resource by resource id.
entailment
def _post_resource(self, body): """ Create new resources and associated attributes. Example: acs.post_resource([ { "resourceIdentifier": "masaya", "parents": [], "attributes": [ { ...
Create new resources and associated attributes. Example: acs.post_resource([ { "resourceIdentifier": "masaya", "parents": [], "attributes": [ { "issuer": "default", ...
entailment
def delete_resource(self, resource_id): """ Remove a specific resource by its identifier. """ # resource_id could be a path such as '/asset/123' so quote uri = self._get_resource_uri(guid=resource_id) return self.service._delete(uri)
Remove a specific resource by its identifier.
entailment
def _put_resource(self, resource_id, body): """ Update a resource for the given resource id. The body is not a list but a dictionary of a single resource. """ assert isinstance(body, (dict)), "PUT requires body to be a dict." # resource_id could be a path such as '/asset...
Update a resource for the given resource id. The body is not a list but a dictionary of a single resource.
entailment
def add_resource(self, resource_id, attributes, parents=[], issuer='default'): """ Will add the given resource with a given identifier and attribute dictionary. example/ add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'}) """ # MA...
Will add the given resource with a given identifier and attribute dictionary. example/ add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'})
entailment
def _get_subject_uri(self, guid=None): """ Returns the full path that uniquely identifies the subject endpoint. """ uri = self.uri + '/v1/subject' if guid: uri += '/' + urllib.quote_plus(guid) return uri
Returns the full path that uniquely identifies the subject endpoint.
entailment
def get_subject(self, subject_id): """ Returns a specific subject by subject id. """ # subject_id could be a path such as '/user/j12y' so quote uri = self._get_subject_uri(guid=subject_id) return self.service._get(uri)
Returns a specific subject by subject id.
entailment
def _post_subject(self, body): """ Create new subjects and associated attributes. Example: acs.post_subject([ { "subjectIdentifier": "/role/evangelist", "parents": [], "attributes": [ ...
Create new subjects and associated attributes. Example: acs.post_subject([ { "subjectIdentifier": "/role/evangelist", "parents": [], "attributes": [ { "issuer": "default"...
entailment
def delete_subject(self, subject_id): """ Remove a specific subject by its identifier. """ # subject_id could be a path such as '/role/analyst' so quote uri = self._get_subject_uri(guid=subject_id) return self.service._delete(uri)
Remove a specific subject by its identifier.
entailment
def _put_subject(self, subject_id, body): """ Update a subject for the given subject id. The body is not a list but a dictionary of a single resource. """ assert isinstance(body, (dict)), "PUT requires body to be dict." # subject_id could be a path such as '/asset/123' ...
Update a subject for the given subject id. The body is not a list but a dictionary of a single resource.
entailment
def add_subject(self, subject_id, attributes, parents=[], issuer='default'): """ Will add the given subject with a given identifier and attribute dictionary. example/ add_subject('/user/j12y', {'username': 'j12y'}) """ # MAINT: consider t...
Will add the given subject with a given identifier and attribute dictionary. example/ add_subject('/user/j12y', {'username': 'j12y'})
entailment
def _get_monitoring_heartbeat(self): """ Tests whether or not the ACS service being monitored is alive. """ target = self.uri + '/monitoring/heartbeat' response = self.session.get(target) return response
Tests whether or not the ACS service being monitored is alive.
entailment
def is_alive(self): """ Will test whether the ACS service is up and alive. """ response = self.get_monitoring_heartbeat() if response.status_code == 200 and response.content == 'alive': return True return False
Will test whether the ACS service is up and alive.
entailment
def _get_policy_set_uri(self, guid=None): """ Returns the full path that uniquely identifies the subject endpoint. """ uri = self.uri + '/v1/policy-set' if guid: uri += '/' + urllib.quote_plus(guid) return uri
Returns the full path that uniquely identifies the subject endpoint.
entailment
def _put_policy_set(self, policy_set_id, body): """ Will create or update a policy set for the given path. """ assert isinstance(body, (dict)), "PUT requires body to be a dict." uri = self._get_policy_set_uri(guid=policy_set_id) return self.service._put(uri, body)
Will create or update a policy set for the given path.
entailment
def _get_policy_set(self, policy_set_id): """ Get a specific policy set by id. """ uri = self._get_policy_set_uri(guid=policy_set_id) return self.service._get(uri)
Get a specific policy set by id.
entailment
def delete_policy_set(self, policy_set_id): """ Delete a specific policy set by id. Method is idempotent. """ uri = self._get_policy_set_uri(guid=policy_set_id) return self.service._delete(uri)
Delete a specific policy set by id. Method is idempotent.
entailment
def add_policy(self, name, action, resource, subject, condition, policy_set_id=None, effect='PERMIT'): """ Will create a new policy set to enforce the given policy details. The name is just a helpful descriptor for the policy. The action maps to a HTTP verb. Polici...
Will create a new policy set to enforce the given policy details. The name is just a helpful descriptor for the policy. The action maps to a HTTP verb. Policies are evaluated against resources and subjects. They are identified by matching a uriTemplate or attributes. Example...
entailment
def is_allowed(self, subject_id, action, resource_id, policy_sets=[]): """ Evaluate a policy-set against a subject and resource. example/ is_allowed('/user/j12y', 'GET', '/asset/12') """ body = { "action": action, "subjectIdentifier": subjec...
Evaluate a policy-set against a subject and resource. example/ is_allowed('/user/j12y', 'GET', '/asset/12')
entailment
def download(url, path=None, headers=None, session=None, show_progress=True, resume=True, auto_retry=True, max_rst_retries=5, pass_through_opts=None, cainfo=None, user_agent=None, auth=None): """Main download function""" hm = Homura(url, path, headers, session, show_progress, resume, ...
Main download function
entailment
def _fill_in_cainfo(self): """Fill in the path of the PEM file containing the CA certificate. The priority is: 1. user provided path, 2. path to the cacert.pem bundle provided by certifi (if installed), 3. let pycurl use the system path where libcurl's cacert bundle is assumed to be sto...
Fill in the path of the PEM file containing the CA certificate. The priority is: 1. user provided path, 2. path to the cacert.pem bundle provided by certifi (if installed), 3. let pycurl use the system path where libcurl's cacert bundle is assumed to be stored, as established at libcurl...
entailment
def curl(self): """Sending a single cURL request to download""" c = self._pycurl # Resume download if os.path.exists(self.path) and self.resume: mode = 'ab' self.downloaded = os.path.getsize(self.path) c.setopt(pycurl.RESUME_FROM, self.downloaded) ...
Sending a single cURL request to download
entailment
def start(self): """ Start downloading, handling auto retry, download resume and path moving """ if not self.auto_retry: self.curl() return while not self.is_finished: try: self.curl() except pycurl.error as ...
Start downloading, handling auto retry, download resume and path moving
entailment
def _move_path(self): """ Move the downloaded file to the authentic path (identified by effective URL) """ if is_temp_path(self._path) and self._pycurl is not None: eurl = self._pycurl.getinfo(pycurl.EFFECTIVE_URL) er = get_resource_name(eurl) ...
Move the downloaded file to the authentic path (identified by effective URL)
entailment
def create(self, secret, **kwargs): """ Create a new instance of the UAA service. Requires a secret password for the 'admin' user account. """ parameters = {"adminClientSecret": secret} self.service.create(parameters=parameters) # Store URI into environment vari...
Create a new instance of the UAA service. Requires a secret password for the 'admin' user account.
entailment
def add_to_manifest(self, manifest): """ Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry...
Add useful details to the manifest about this service so that it can be used in an application. :param manifest: An predix.admin.app.Manifest object instance that manages reading/writing manifest config for a cloud foundry app.
entailment
def authenticate(self): """ Authenticate into the UAA instance as the admin user. """ # Make sure we've stored uri for use predix.config.set_env_value(self.use_class, 'uri', self._get_uri()) self.uaac = predix.security.uaa.UserAccountAuthentication() self.uaac.au...
Authenticate into the UAA instance as the admin user.
entailment
def _create_secret(self, length=12): """ Use a cryptograhically-secure Pseudorandom number generator for picking a combination of letters, digits, and punctuation to be our secret. :param length: how long to make the secret (12 seems ok most of the time) """ # Charset w...
Use a cryptograhically-secure Pseudorandom number generator for picking a combination of letters, digits, and punctuation to be our secret. :param length: how long to make the secret (12 seems ok most of the time)
entailment
def create_client(self, client_id, client_secret): """ Create a new client for use by applications. """ assert self.is_admin, "Must authenticate() as admin to create client" return self.uaac.create_client(client_id, client_secret)
Create a new client for use by applications.
entailment
def add_client_to_manifest(self, client_id, client_secret, manifest): """ Add the client credentials to the specified manifest. """ assert self.is_admin, "Must authenticate() as admin to create client" return self.uaac.add_client_to_manifest(client_id, client_secret, ...
Add the client credentials to the specified manifest.
entailment
def _get_uaa_uri(self): """ Returns the URI endpoint for an instance of a UAA service instance from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) predix_uaa = services['predix-uaa'][0]['cred...
Returns the URI endpoint for an instance of a UAA service instance from environment inspection.
entailment
def _authenticate_client(self, client, secret): """ Returns response of authenticating with the given client and secret. """ client_s = str.join(':', [client, secret]) credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8') headers = { ...
Returns response of authenticating with the given client and secret.
entailment
def _authenticate_user(self, user, password): """ Returns the response of authenticating with the given user and password. """ headers = self._get_headers() params = { 'username': user, 'password': password, 'grant_type': 'p...
Returns the response of authenticating with the given user and password.
entailment
def is_expired_token(self, client): """ For a given client will test whether or not the token has expired. This is for testing a client object and does not look up from client_id. You can use _get_client_from_cache() to lookup a client from client_id. """ ...
For a given client will test whether or not the token has expired. This is for testing a client object and does not look up from client_id. You can use _get_client_from_cache() to lookup a client from client_id.
entailment
def _initialize_uaa_cache(self): """ If we don't yet have a uaa cache we need to initialize it. As there may be more than one UAA instance we index by issuer and then store any clients, users, etc. """ try: os.makedirs(os.path.dirname(self._cache_path...
If we don't yet have a uaa cache we need to initialize it. As there may be more than one UAA instance we index by issuer and then store any clients, users, etc.
entailment
def _read_uaa_cache(self): """ Read cache of UAA client/user details. """ self._cache_path = os.path.expanduser('~/.predix/uaa.json') if not os.path.exists(self._cache_path): return self._initialize_uaa_cache() with open(self._cache_path, 'r') as data: ...
Read cache of UAA client/user details.
entailment
def _get_client_from_cache(self, client_id): """ For the given client_id return what is cached. """ data = self._read_uaa_cache() # Only if we've cached any for this issuer if self.uri not in data: return for client in data[self.uri]: ...
For the given client_id return what is cached.
entailment
def _write_to_uaa_cache(self, new_item): """ Cache the client details into a cached file on disk. """ data = self._read_uaa_cache() # Initialize client list if first time if self.uri not in data: data[self.uri] = [] # Remove existing client record an...
Cache the client details into a cached file on disk.
entailment
def authenticate(self, client_id, client_secret, use_cache=True): """ Authenticate the given client against UAA. The resulting token will be cached for reuse. """ # We will reuse a token for as long as we have one cached # and it hasn't expired. if use_cache: ...
Authenticate the given client against UAA. The resulting token will be cached for reuse.
entailment
def logout(self): """ Log currently authenticated user out, invalidating any existing tokens. """ # Remove token from local cache # MAINT: need to expire token on server data = self._read_uaa_cache() if self.uri in data: for client in data[self.uri]: ...
Log currently authenticated user out, invalidating any existing tokens.
entailment
def _post(self, uri, data, headers=None): """ Simple POST request for a given uri path. """ if not headers: headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("HEADERS=" + str(headers)) logging.debug("BODY=" + str(data)) ...
Simple POST request for a given uri path.
entailment
def get_token(self): """ Returns the bare access token for the authorized client. """ if not self.authenticated: raise ValueError("Must authenticate() as a client first.") # If token has expired we'll need to refresh and get a new # client credential ...
Returns the bare access token for the authorized client.
entailment
def get_scopes(self): """ Returns the scopes for the authenticated client. """ if not self.authenticated: raise ValueError("Must authenticate() as a client first.") scope = self.client['scope'] return scope.split()
Returns the scopes for the authenticated client.
entailment
def assert_has_permission(self, scope_required): """ Warn that the required scope is not found in the scopes granted to the currently authenticated user. :: # The admin user should have client admin permissions uaa.assert_has_permission('admin', 'clients.admin')...
Warn that the required scope is not found in the scopes granted to the currently authenticated user. :: # The admin user should have client admin permissions uaa.assert_has_permission('admin', 'clients.admin')
entailment
def grant_client_permissions(self, client_id, admin=False, write=False, read=False, secret=False): """ Grant the given client_id permissions for managing clients. - clients.admin: super user scope to create, modify, delete - clients.write: scope ot create and modify clients ...
Grant the given client_id permissions for managing clients. - clients.admin: super user scope to create, modify, delete - clients.write: scope ot create and modify clients - clients.read: scope to read info about clients - clients.secret: scope to change password of a client
entailment
def get_clients(self): """ Returns the clients stored in the instance of UAA. """ self.assert_has_permission('clients.read') uri = self.uri + '/oauth/clients' headers = self.get_authorization_headers() response = requests.get(uri, headers=headers) return ...
Returns the clients stored in the instance of UAA.
entailment
def get_client(self, client_id): """ Returns details about a specific client by the client_id. """ self.assert_has_permission('clients.read') uri = self.uri + '/oauth/clients/' + client_id headers = self.get_authorization_headers() response = requests.get(uri, he...
Returns details about a specific client by the client_id.
entailment
def update_client_grants(self, client_id, scope=[], authorities=[], grant_types=[], redirect_uri=[], replace=False): """ Will extend the client with additional scopes or authorities. Any existing scopes and authorities will be left as is unless asked to replace entirely. ...
Will extend the client with additional scopes or authorities. Any existing scopes and authorities will be left as is unless asked to replace entirely.
entailment
def grant_scim_permissions(self, client_id, read=False, write=False, create=False, userids=False, zones=False, invite=False, openid=False): """ Grant the given client_id permissions for managing users. System for Cross-domain Identity Management (SCIM) are required for a...
Grant the given client_id permissions for managing users. System for Cross-domain Identity Management (SCIM) are required for accessing /Users and /Groups endpoints of UAA. - scim.read: scope for read access to all SCIM endpoints - scim.write: scope for write access to all SCIM endpoin...
entailment
def create_client(self, client_id, client_secret, manifest=None, client_credentials=True, refresh_token=True, authorization_code=False, redirect_uri=[]): """ Will create a new client for your application use. - client_credentials: allows client to get access token ...
Will create a new client for your application use. - client_credentials: allows client to get access token - refresh_token: can be used to get new access token when expired without re-authenticating - authorization_code: redirection-based flow for user authentication More det...
entailment
def add_client_to_manifest(self, client_id, client_secret, manifest): """ Add the given client / secret to the manifest for use in the application. """ client_id_key = 'PREDIX_APP_CLIENT_ID' manifest.add_env_var(client_id_key, client_id) client_secret_key = 'PRED...
Add the given client / secret to the manifest for use in the application.
entailment
def create_user(self, username, password, family_name, given_name, primary_email, details={}): """ Creates a new user account with the required details. :: create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com') """ self.assert_has_perm...
Creates a new user account with the required details. :: create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com')
entailment
def delete_user(self, id): """ Delete user with given id. """ self.assert_has_permission('scim.write') uri = self.uri + '/Users/%s' % id headers = self._get_headers() logging.debug("URI=" + str(uri)) logging.debug("HEADERS=" + str(headers)) resp...
Delete user with given id.
entailment
def get_users(self, filter=None, sortBy=None, sortOrder=None, startIndex=None, count=None): """ Returns users accounts stored in UAA. See https://docs.cloudfoundry.org/api/uaa/#list63 For filtering help, see: http://www.simplecloud.info/specs/draft-scim-api-01.html#q...
Returns users accounts stored in UAA. See https://docs.cloudfoundry.org/api/uaa/#list63 For filtering help, see: http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources
entailment