text
stringlengths
81
112k
Updates an existing collection. The collection being updated *is* expected to include the id. def put_collection(self, collection, body): """ Updates an existing collection. The collection being updated *is* expected to include the id. """ uri = self.uri + '/v1' + col...
Deletes an existing collection. The collection being updated *is* expected to include the id. def delete_collection(self, collection): """ Deletes an existing collection. The collection being updated *is* expected to include the id. """ uri = str.join('/', [self.uri, c...
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' }] de...
Save an asset collection to the service. 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, co...
Populate a manifest file generated from details from the cloud foundry space environment. 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() ...
Lock the manifest to the current organization and space regardless of Cloud Foundry target. 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....
Creates an instance of UAA Service. :param admin_secret: The secret password for administering the service such as adding clients and users. def create_uaa(self, admin_secret, **kwargs): """ Creates an instance of UAA Service. :param admin_secret: The secret password for a...
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 def crea...
Creates an instance of the Time Series Service. 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: ...
Creates an instance of the Asset Service. 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(...
Creates an instance of the Asset Service. 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(cl...
Creates an instance of the Asset Service. 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: w...
Creates an instance of the BlobStore Service. 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 Logging Service. 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-...
Creates an instance of the Cache Service. 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
todo make it so the client can be customised to publish/subscribe Creates an instance of eventhub service def create_eventhub(self, **kwargs): """ todo make it so the client can be customised to publish/subscribe Creates an instance of eventhub service """ eventhub = pre...
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...
If we are in an app context we can authenticate immediately. 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(p...
Simple GET request for a given path. 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)) ...
Simple POST request for a given path. 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=he...
Simple PUT operation for a given path. 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=he...
Simple DELETE operation for a given path. 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_co...
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/...
Returns the full path that uniquely identifies the resource endpoint. 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.qu...
Returns a specific resource by resource id. 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)
Create new resources and associated attributes. Example: acs.post_resource([ { "resourceIdentifier": "masaya", "parents": [], "attributes": [ { "issuer": "default", ...
Remove a specific resource by its identifier. 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._del...
Update a resource for the given resource id. The body is not a list but a dictionary of a single resource. 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. """ ass...
Will add the given resource with a given identifier and attribute dictionary. example/ add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'}) def add_resource(self, resource_id, attributes, parents=[], issuer='default'): """ Will add the given reso...
Returns the full path that uniquely identifies the subject endpoint. 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_...
Returns a specific subject by subject id. 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)
Create new subjects and associated attributes. Example: acs.post_subject([ { "subjectIdentifier": "/role/evangelist", "parents": [], "attributes": [ { "issuer": "default"...
Remove a specific subject by its identifier. 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(...
Update a subject for the given subject id. The body is not a list but a dictionary of a single resource. 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 is...
Will add the given subject with a given identifier and attribute dictionary. example/ add_subject('/user/j12y', {'username': 'j12y'}) def add_subject(self, subject_id, attributes, parents=[], issuer='default'): """ Will add the given subject with a give...
Tests whether or not the ACS service being monitored is alive. 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
Will test whether the ACS service is up and alive. 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 Fa...
Returns the full path that uniquely identifies the subject endpoint. 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....
Will create or update a policy set for the given path. 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...
Get a specific policy set by id. 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)
Delete a specific policy set by id. Method is idempotent. 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)
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...
Evaluate a policy-set against a subject and resource. example/ is_allowed('/user/j12y', 'GET', '/asset/12') def is_allowed(self, subject_id, action, resource_id, policy_sets=[]): """ Evaluate a policy-set against a subject and resource. example/ is_allowed('/...
Main download function 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, ...
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...
Sending a single cURL request to download 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.setop...
Start downloading, handling auto retry, download resume and path moving 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:...
Move the downloaded file to the authentic path (identified by effective URL) 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._pycu...
Create a new instance of the UAA service. Requires a secret password for the 'admin' user account. def create(self, secret, **kwargs): """ Create a new instance of the UAA service. Requires a secret password for the 'admin' user account. """ parameters = {"adminClientS...
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. def add_to_manifest(self, manifest): """ ...
Authenticate into the UAA instance as the admin user. 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.securi...
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) def _create_secret(self, length=12): """ Use a cryptograhically-secure P...
Create a new client for use by applications. 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)
Add the client credentials to the specified manifest. 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_cl...
Returns the URI endpoint for an instance of a UAA service instance from environment inspection. 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: s...
Returns response of authenticating with the given client and secret. def _authenticate_client(self, client, secret): """ Returns response of authenticating with the given client and secret. """ client_s = str.join(':', [client, secret]) credentials = base64.b64en...
Returns the response of authenticating with the given user and password. def _authenticate_user(self, user, password): """ Returns the response of authenticating with the given user and password. """ headers = self._get_headers() params = { 'usern...
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. def is_expired_token(self, client): """ For a given clien...
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. def _initialize_uaa_cache(self): """ If we don't yet have a uaa cache we need to initialize it. As there may...
Read cache of UAA client/user details. 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 ope...
For the given client_id return what is cached. 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: ...
Cache the client details into a cached file on disk. 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...
Authenticate the given client against UAA. The resulting token will be cached for reuse. 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...
Log currently authenticated user out, invalidating any existing tokens. 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()...
Simple POST request for a given uri path. 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)) ...
Returns the bare access token for the authorized client. 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 ...
Returns the scopes for the authenticated client. 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.sp...
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') def assert_has_permission(self, scope_required): """ ...
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 def grant_...
Returns the clients stored in the instance of UAA. 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 ...
Returns details about a specific client by the client_id. 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_auth...
Will extend the client with additional scopes or authorities. Any existing scopes and authorities will be left as is unless asked to replace entirely. def update_client_grants(self, client_id, scope=[], authorities=[], grant_types=[], redirect_uri=[], replace=False): """ Wi...
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...
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...
Add the given client / secret to the manifest for use in the application. 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' ...
Creates a new user account with the required details. :: create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com') def create_user(self, username, password, family_name, given_name, primary_email, details={}): """ Creates a new user account with the requ...
Delete user with given id. 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=" +...
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 def get_users(self, filter=None, sortBy=None, sortOrder=None, startIndex=None, count=None): ...
Returns details for user of the given username. If there is more than one match will only return the first. Use get_users() for full result set. def get_user_by_username(self, username): """ Returns details for user of the given username. If there is more than one match will ...
Returns details for user with the given email address. If there is more than one match will only return the first. Use get_users() for full result set. def get_user_by_email(self, email): """ Returns details for user with the given email address. If there is more than one mat...
Returns details about the user for the given id. Use get_user_by_email() or get_user_by_username() for help identifiying the id. def get_user(self, id): """ Returns details about the user for the given id. Use get_user_by_email() or get_user_by_username() for help iden...
Create an instance of the Time Series Service with the typical starting settings. def create(self): """ Create an instance of the Time Series Service with the typical starting settings. """ self.service.create() predix.config.set_env_value(self.use_class, 'inges...
Grant the given client id all the scopes and authorities needed to work with the timeseries service. def grant_client(self, client_id, read=True, write=True): """ Grant the given client id all the scopes and authorities needed to work with the timeseries service. """ sco...
Return the uri used for queries on time series data. def get_query_uri(self): """ Return the uri used for queries on time series data. """ # Query URI has extra path we don't want so strip it off here query_uri = self.service.settings.data['query']['uri'] query_uri = url...
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. def add_to_manifest(self, manifest): """ ...
This method tries to determine the requirements of a particular project by inspecting the possible places that they could be defined. It will attempt, in order: 1) to parse setup.py in the root for an install_requires value 2) to read a requirements.txt file or a requirements.pip in the root 3) to...
Returns the GUID for the app instance with the given name. def get_app_guid(self, app_name): """ Returns the GUID for the app instance with the given name. """ summary = self.space.get_space_summary() for app in summary['apps']: if app['name'] == app_...
Delete the given app. Will fail intentionally if there are any service bindings. You must delete those first. def delete_app(self, app_name): """ Delete the given app. Will fail intentionally if there are any service bindings. You must delete those first. """...
Reads in config file of UAA credential information or generates one as a side-effect if not yet initialized. def _get_service_config(self): """ Reads in config file of UAA credential information or generates one as a side-effect if not yet initialized. """ ...
Will write the config out to disk. def _write_service_config(self): """ Will write the config out to disk. """ with open(self.config_path, 'w') as output: output.write(json.dumps(self.data, sort_keys=True, indent=4))
Create an instance of the Blob Store Service with the typical starting settings. def create(self, **kwargs): """ Create an instance of the Blob Store Service with the typical starting settings. """ self.service.create(**kwargs) predix.config.set_env_value(self.u...
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. def add_to_manifest(self, manifest): """ ...
return a generator for all subscribe messages :return: None def subscribe(self): """ return a generator for all subscribe messages :return: None """ while self.run_subscribe_generator: if len(self._rx_messages) != 0: yield self._rx_messages.po...
send acks to the service :param message: EventHub_pb2.Message :return: None def send_acks(self, message): """ send acks to the service :param message: EventHub_pb2.Message :return: None """ if isinstance(message, EventHub_pb2.Message): ack = E...
generate the subscribe stub headers based on the supplied config :return: i def _generate_subscribe_headers(self): """ generate the subscribe stub headers based on the supplied config :return: i """ headers =[] headers.append(('predix-zone-id', self.eventhub_clie...
Returns the raw results of an asset search for a given bounding box. def _get_assets(self, bbox, size=None, page=None, asset_type=None, device_type=None, event_type=None, media_type=None): """ Returns the raw results of an asset search for a given bounding box. """ ...
Query the assets stored in the intelligent environment for a given bounding box and query. Assets can be filtered by type of asset, event, or media available. - device_type=['DATASIM'] - asset_type=['CAMERA'] - event_type=['PKIN'] - media_type=['IMAGE'] ...
Returns raw response for an given asset by its unique id. def _get_asset(self, asset_uid): """ Returns raw response for an given asset by its unique id. """ uri = self.uri + '/v2/assets/' + asset_uid headers = self._get_headers() return self.service._get(uri, headers=h...
Label input grid with hysteresis method. Args: input_grid: 2D array of values. Returns: Labeled output grid. def label(self, input_grid): """ Label input grid with hysteresis method. Args: input_grid: 2D array of values. Returns: ...
Remove labeled objects that do not meet size threshold criteria. Args: labeled_grid: 2D output from label method. min_size: minimum size of object in pixels. Returns: labeled grid with smaller objects removed. def size_filter(labeled_grid, min_size): """ ...