code stringlengths 1 18.2k |
|---|
def get_client_id(self): """ Return the client id that should have all the needed scopes and authorities for the services in this manifest. """ self._client_id = predix.config.get_env_value(predix.app.Manifest, 'client_id') return self._client_id |
def get_client_secret(self): """ Return the client secret that should correspond with the client id. """ self._client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret') return self._client_secret |
def get_timeseries(self, *args, **kwargs): """ Returns an instance of the Time Series Service. """ import predix.data.timeseries ts = predix.data.timeseries.TimeSeries(*args, **kwargs) return ts |
def get_asset(self): """ Returns an instance of the Asset Service. """ import predix.data.asset asset = predix.data.asset.Asset() return asset |
def get_uaa(self): """ Returns an insstance of the UAA Service. """ import predix.security.uaa uaa = predix.security.uaa.UserAccountAuthentication() return uaa |
def get_acs(self): """ Returns an instance of the Asset Control Service. """ import predix.security.acs acs = predix.security.acs.AccessControl() return acs |
def get_weather(self): """ Returns an instance of the Weather Service. """ import predix.data.weather weather = predix.data.weather.WeatherForecast() return weather |
def get_weather_forecast_days(self, latitude, longitude, days=1, frequency=1, reading_type=None): """ Return the weather forecast for a given location. :: results = ws.get_weather_forecast_days(lat, long) for w in results['hits']: print w['start_datetime_local'] print w['reading_type'], w['reading_value'] For descripti... |
be 1 or 3") params['days'] = days params['source'] = 'NWS' + str(frequency) params['latitude'] = latitude params['longitude'] = longitude if reading_type: # url encoding will make spaces a + instead of %20, which service # interprets as an "and" search which is undesirable reading_type = reading_type.replace(' ', '%20'... |
def get_weather_forecast(self, latitude, longitude, start, end, frequency=1, reading_type=None): """ Return the weather forecast for a given location for specific datetime specified in UTC format. :: results = ws.get_weather_forecast(lat, long, start, end) for w in results['hits']: print w['start_datetime_local'] print... |
intervals. if frequency not in [1, 3]: raise ValueError("Reading frequency must be 1 or 3") params['source'] = 'NWS' + str(frequency) params['latitude'] = latitude params['longitude'] = longitude params['start_datetime_utc'] = start params['end_datetime_utc'] = end if reading_type: # Not using urllib.quote_plus() becau... |
reading_type url = self.uri + '/v1/weather-forecast-datetime/' return self.service._get(url, params=params) |
def _generate_name(self, space, service_name, plan_name): """ Can generate a name based on the space, service name and plan. """ return str.join('-', [space, service_name, plan_name]).lower() |
def _get_config_path(self): """ Return a sensible configuration path for caching config settings. """ org = self.service.space.org.name space = self.service.space.name name = self.name return "~/.predix/%s/%s/%s.json" % (org, space, name) |
def _create_service(self, parameters={}, **kwargs): """ Create a Cloud Foundry service that has custom parameters. """ logging.debug("_create_service()") logging.debug(str.join(',', [self.service_name, self.plan_name, self.name, str(parameters)])) return self.service.create_service(self.service_name, self.plan_name, se... |
def _delete_service(self, service_only=False): """ Delete a Cloud Foundry service and any associations. """ logging.debug('_delete_service()') return self.service.delete_service(self.service_name) |
def _get_or_create_service_key(self): """ Get a service key or create one if needed. """ keys = self.service._get_service_keys(self.name) for key in keys['resources']: if key['entity']['name'] == self.service_name: return self.service.get_service_key(self.name, self.service_name) self.service.create_service_key(self.na... |
def _get_service_config(self): """ Will get configuration for the service from a service key. """ key = self._get_or_create_service_key() config = {} config['service_key'] = [{'name': self.name}] config.update(key['entity']['credentials']) return config |
def create(self, parameters={}, create_keys=True, **kwargs): """ Create the service. """ # Create the service cs = self._create_service(parameters=parameters, **kwargs) # Create the service key to get config details and # store in local cache file. if create_keys: cfg = parameters cfg.update(self._get_service_config())... |
def _get_or_create_uaa(self, uaa): """ Returns a valid UAA instance for performing administrative functions on services. """ if isinstance(uaa, predix.admin.uaa.UserAccountAuthentication): return uaa logging.debug("Initializing a new UAA") return predix.admin.uaa.UserAccountAuthentication() |
def create(self, parameters={}, **kwargs): """ Create an instance of the US Weather Forecast Service with typical starting settings. """ # Add parameter during create for UAA issuer uri = self.uaa.service.settings.data['uri'] + '/oauth/token' parameters["trustedIssuerIds"] = [uri] super(PredixService, self).create(para... |
def create(self): """ Create an instance of the Time Series Service with the typical starting settings. """ self.service.create() os.environ[predix.config.get_env_key(self.use_class, 'host')] = self.get_eventhub_host() os.environ[predix.config.get_env_key(self.use_class, 'port')] = self.get_eventhub_grpc_port() os.envi... |
def grant_client(self, client_id, publish=False, subscribe=False, publish_protocol=None, publish_topics=None, subscribe_topics=None, scope_prefix='predix-event-hub', **kwargs): """ Grant the given client id all the scopes and authorities needed to work with the eventhub service. """ scopes = ['openid'] authorities = ['... |
None: raise Exception("multiple topics are not currently available in preidx-py") if publish_topics is None: publish_topics = ['topic'] if subscribe_topics is None: subscribe_topics = ['topic'] if publish: # we are granting just the default topic if publish_protocol is None: scopes.append('%s.zones.%s.grpc.publish' % (... |
publish_protocol)) # we are requesting multiple topics for topic in publish_topics: if publish_protocol is None: scopes.append('%s.zones.%s.%s.grpc.publish' % (scope_prefix, zone_id, topic)) scopes.append('%s.zones.%s.%s.wss.publish' % (scope_prefix, zone_id, topic)) scopes.append('%s.zones.%s.%s.user' % (scope_prefix,... |
just the default topic scopes.append('%s.zones.%s.grpc.subscribe' % (scope_prefix, zone_id)) authorities.append('%s.zones.%s.grpc.subscribe' % (scope_prefix, zone_id)) # we are requesting multiple topics for topic in subscribe_topics: scopes.append('%s.zones.%s.%s.grpc.subscribe' % (scope_prefix, zone_id, topic)) autho... |
def get_eventhub_host(self): """ returns the publish grpc endpoint for ingestion. """ for protocol in self.service.settings.data['publish']['protocol_details']: if protocol['protocol'] == 'grpc': return protocol['uri'][0:protocol['uri'].index(':')] |
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 app. """ # Add this service to list of services manifest... |
manifest.write_manifest() |
def _get_host(self): """ Returns the host address for an instance of Blob Store service from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) host = services['predix-blobstore'][0]['credentials']['host'] else: host = predix.config.get_env_value(self, 'host'... |
def _get_access_key_id(self): """ Returns the access key for an instance of Blob Store service from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) return services['predix-blobstore'][0]['credentials']['access_key_id'] else: return predix.config.get_env_va... |
def list_objects(self, bucket_name=None, **kwargs): """ This method is primarily for illustration and just calls the boto3 client implementation of list_objects but is a common task for first time Predix BlobStore users. """ if not bucket_name: bucket_name = self.bucket_name return self.client.list_objects(Bucket=bucke... |
def upload_file(self, src_filepath, dest_filename=None, bucket_name=None, **kwargs): """ This method is primarily for illustration and just calls the boto3 client implementation of upload_file but is a common task for first time Predix BlobStore users. """ if not bucket_name: bucket_name = self.bucket_name if not dest_... |
def _get_cloud_foundry_config(self): """ Reads the local cf CLI cache stored in the users home directory. """ config = os.path.expanduser(self.config_file) if not os.path.exists(config): raise CloudFoundryLoginError('You must run `cf login` to authenticate') with open(config, "r") as data: return json.load(data) |
def get_organization_guid(self): """ Returns the GUID for the organization currently targeted. """ if 'PREDIX_ORGANIZATION_GUID' in os.environ: return os.environ['PREDIX_ORGANIZATION_GUID'] else: info = self._get_organization_info() for key in ('Guid', 'GUID'): if key in info.keys(): return info[key] raise ValueError('... |
def get_space_guid(self): """ Returns the GUID for the space currently targeted. Can be set by environment variable with PREDIX_SPACE_GUID. Can be determined by ~/.cf/config.json. """ if 'PREDIX_SPACE_GUID' in os.environ: return os.environ['PREDIX_SPACE_GUID'] else: info = self._get_space_info() for key in ('Guid', 'GU... |
def get_crypt_key(key_path): """ Get the user's PredixPy manifest key. Generate and store one if not yet generated. """ key_path = os.path.expanduser(key_path) if os.path.exists(key_path): with open(key_path, 'r') as data: key = data.read() else: key = Fernet.generate_key() with open(key_path, 'w') as output: output.wr... |
def get_env_key(obj, key=None): """ Return environment variable key to use for lookups within a namespace represented by the package name. For example, any varialbes for predix.security.uaa are stored as PREDIX_SECURITY_UAA_KEY """ return str.join('_', [obj.__module__.replace('.','_').upper(), key.upper()]) |
def get_env_value(obj, attribute): """ Returns the environment variable value for the attribute of the given object. For example `get_env_value(predix.security.uaa, 'uri')` will return value of environment variable PREDIX_SECURITY_UAA_URI. """ varname = get_env_key(obj, attribute) var = os.environ.get(varname) if not v... |
def set_env_value(obj, attribute, value): """ Set the environment variable value for the attribute of the given object. For example, `set_env_value(predix.security.uaa, 'uri', 'http://...')` will set the environment variable PREDIX_SECURITY_UAA_URI to the given uri. """ varname = get_env_key(obj, attribute) os.environ[... |
def get_instance_guid(self, service_name): """ Returns the GUID for the service instance with the given name. """ summary = self.space.get_space_summary() for service in summary['services']: if service['name'] == service_name: return service['guid'] raise ValueError("No service with name '%s' found." % (service_name)) |
def _get_service_bindings(self, service_name): """ Return the service bindings for the service instance. """ instance = self.get_instance(service_name) return self.api.get(instance['service_bindings_url']) |
def delete_service_bindings(self, service_name): """ Remove service bindings to applications. """ instance = self.get_instance(service_name) return self.api.delete(instance['service_bindings_url']) |
def _get_service_keys(self, service_name): """ Return the service keys for the given service. """ guid = self.get_instance_guid(service_name) uri = "/v2/service_instances/%s/service_keys" % (guid) return self.api.get(uri) |
def get_service_keys(self, service_name): """ Returns a flat list of the names of the service keys for the given service. """ keys = [] for key in self._get_service_keys(service_name)['resources']: keys.append(key['entity']['name']) return keys |
def get_service_key(self, service_name, key_name): """ Returns the service key details. Similar to `cf service-key`. """ for key in self._get_service_keys(service_name)['resources']: if key_name == key['entity']['name']: guid = key['metadata']['guid'] uri = "/v2/service_keys/%s" % (guid) return self.api.get(uri) return... |
def create_service_key(self, service_name, key_name): """ Create a service key for the given service. """ if self.has_key(service_name, key_name): logging.warning("Reusing existing service key %s" % (key_name)) return self.get_service_key(service_name, key_name) body = { 'service_instance_guid': self.get_instance_guid(... |
def delete_service_key(self, service_name, key_name): """ Delete a service key for the given service. """ key = self.get_service_key(service_name, key_name) logging.info("Deleting service key %s for service %s" % (key, service_name)) return self.api.delete(key['metadata']['url']) |
def get_instance(self, service_name): """ Retrieves a service instance with the given name. """ for resource in self.space._get_instances(): if resource['entity']['name'] == service_name: return resource['entity'] |
def get_service_plan_for_service(self, service_name): """ Return the service plans available for a given service. """ services = self.get_services() for service in services['resources']: if service['entity']['label'] == service_name: response = self.api.get(service['entity']['service_plans_url']) return response['resou... |
def get_service_plan_guid(self, service_name, plan_name): """ Return the service plan GUID for the given service / plan. """ for plan in self.get_service_plan_for_service(service_name): if plan['entity']['name'] == plan_name: return plan['metadata']['guid'] return None |
def create_service(self, service_type, plan_name, service_name, params, async=False, **kwargs): """ Create a service instance. """ if self.space.has_service_with_name(service_name): logging.warning("Service already exists with that name.") return self.get_instance(service_name) if self.space.has_service_of_type(service... |
'&async=true' return self.api.post(uri, body) |
def delete_service(self, service_name, params=None): """ Delete the service of the given name. It may fail if there are any service keys or app bindings. Use purge() if you want to delete it all. """ if not self.space.has_service_with_name(service_name): logging.warning("Service not found so... succeeded?") return True... |
of api return self.api.delete("/v2/service_instances/%s?accepts_incomplete=true" % (guid), params=params) |
def _get_query_uri(self): """ Returns the URI endpoint for performing queries of a Predix Time Series instance from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) predix_timeseries = services['predix-timeseries'][0]['credentials'] return predix_timeseries... |
def _get_query_zone_id(self): """ Returns the ZoneId for performing queries of a Predix Time Series instance from environment inspection. """ if 'VCAP_SERVICES' in os.environ: services = json.loads(os.getenv('VCAP_SERVICES')) predix_timeseries = services['predix-timeseries'][0]['credentials'] return predix_timeseries['... |
def _get_datapoints(self, params): """ Will make a direct REST call with the given json body payload to get datapoints. """ url = self.query_uri + '/v1/datapoints' return self.service._get(url, params=params) |
def get_values(self, *args, **kwargs): """ Convenience method that for simple single tag queries will return just the values to be iterated on. """ if isinstance(args[0], list): raise ValueError("Can only get_values() for a single tag.") response = self.get_datapoints(*args, **kwargs) for value in response['tags'][0]['... |
def get_datapoints(self, tags, start=None, end=None, order=None, limit=None, qualities=None, attributes=None, measurement=None, aggregations=None, post=False): """ Returns all of the datapoints that match the given query. - tags: list or string identifying the name/tag (ie. "temp") - start: data after this, absolute or... |
values (ie. 25) - qualities: data quality value (ie. [ts.GOOD, ts.UNCERTAIN]) - attributes: dictionary of key-values (ie. {'unit': 'mph'}) - measurement: tuple of operation and value (ie. ('gt', 30)) - aggregations: summary statistics on data results (ie. 'avg') - post: POST query instead of GET (caching implication) A... |
limit so resultset will differ The returned results match what the service response is so you'll need to unpack it as appropriate. Oftentimes what you want for a simple single tag query will be: response['tags'][0]['results'][0]['values'] """ params = {} # Documentation says start is required for GET but not POST, but ... |
not start: start = '1w-ago' logging.warning("Defaulting query for data with start date %s" % (start)) # Start date can be absolute or relative, only certain legal values # but service will throw error if used improperly. (ms, s, mi, h, d, # w, mm, y). Relative dates must end in -ago. params['start'] = start # Docs say ... |
end must also be # specified, but this does not seem to be the case. if end: # MAINT: error when end < start which is handled by service params['end'] = end params['tags'] = [] if not isinstance(tags, list): tags = [tags] for tag in tags: query = {} query['name'] = tag # Limit resultset with an integer value if limit: ... |
# Order must be 'asc' or 'desc' but will get sensible error # from service. if order: query['order'] = order # Filters are complex and support filtering by # quality, measurement, and attributes. filters = {} # Check for the quality of the datapoints if qualities is not None: if isinstance(qualities, int) or isinstance... |
a string, not integer, # so coerce each into a string for i, quality in enumerate(qualities): qualities[i] = str(quality) filters['qualities'] = {"values": qualities} # Check for attributes on the datapoints, expected to be # a dictionary of key / value pairs that datapoints must match. if attributes is not None: if no... |
Check for measurements that meets a given comparison operation # such as ge, gt, eq, ne, le, lt if measurement is not None: filters['measurements'] = { 'condition': measurement[0], 'values': measurement[1] } # If we found any filters add them to the query if filters: query['filters'] = filters # Handle any additional a... |
= [aggregations] query['aggregations'] = [] for aggregation in aggregations: query['aggregations'].append({ 'sampling': {'datapoints': 1}, 'type': aggregation }) params['tags'].append(query) if post: return self._post_datapoints(params) else: return self._get_datapoints({"query": json.dumps(params)}) |
def _create_connection(self): """ Create a new websocket connection with proper headers. """ logging.debug("Initializing new websocket connection.") headers = { 'Authorization': self.service._get_bearer_token(), 'Predix-Zone-Id': self.ingest_zone_id, 'Content-Type': 'application/json', } url = self.ingest_uri logging.d... |
def _get_websocket(self, reuse=True): """ Reuse existing connection or create a new connection. """ # Check if still connected if self.ws and reuse: if self.ws.connected: return self.ws logging.debug("Stale connection, reconnecting.") self.ws = self._create_connection() return self.ws |
def _send_to_timeseries(self, message): """ Establish or reuse socket connection and send the given message to the timeseries service. """ logging.debug("MESSAGE=" + str(message)) result = None try: ws = self._get_websocket() ws.send(json.dumps(message)) result = ws.recv() except (websocket.WebSocketConnectionClosedExc... |
def queue(self, name, value, quality=None, timestamp=None, attributes=None): """ To reduce network traffic, you can buffer datapoints and then flush() anything in the queue. :param name: the name / label / tag for sensor data :param value: the sensor reading or value to record :param quality: the quality value, use the... |
reading was recorded in epoch milliseconds (optional and defaults to now) :param attributes: dictionary for any key-value pairs to store with the reading (optional) """ # Get timestamp first in case delay opening websocket connection # and it must have millisecond accuracy if not timestamp: timestamp = int(round(time.t... |
1000)) # Only specific quality values supported if quality not in [self.BAD, self.GOOD, self.NA, self.UNCERTAIN]: quality = self.UNCERTAIN # Check if adding to queue of an existing tag and add second datapoint for point in self._queue: if point['name'] == name: point['datapoints'].append([timestamp, value, quality]) re... |
# Attributes are extra details for a datapoint if attributes is not None: if not isinstance(attributes, dict): raise ValueError("Attributes are expected to be a dictionary.") # Validate rules for attribute keys to provide guidance. invalid_value = ':;= ' has_invalid_value = re.compile(r'[%s]' % (invalid_value)).search ... |
raise ValueError("Attribute (%s) must have a non-empty value." % (key)) # Values should be treated as a string for regex validation val = str(val) # Values cannot contain certain arbitrary characters if bool(has_invalid_value(val)): raise ValueError("Attribute (%s) cannot contain (%s)." % (key, invalid_value)) # Attrib... |
+ str(len(self._queue))) |
def send(self, name=None, value=None, **kwargs): """ Can accept a name/tag and value to be queued and then send anything in the queue to the time series service. Optional parameters include setting quality, timestamp, or attributes. See spec for queue() for complete list of options. Example of sending a batch of values... |
send('temp', 70.3) send('temp', 70.4, quality=ts.GOOD, attributes={'unit': 'F'}) """ if name and value: self.queue(name, value, **kwargs) timestamp = int(round(time.time() * 1000)) # The label "name" or "tag" is sometimes used ambiguously msg = { "messageId": timestamp, "body": self._queue } self._queue = [] return sel... |
def execute(self, statement, *args, **kwargs): """ This convenience method will execute the query passed in as is. For more complex functionality you may want to use the sqlalchemy engine directly, but this serves as an example implementation. :param select_query: SQL statement to execute that will identify the results... |
def shutdown(self): """ Shutdown the client, shutdown the sub clients and stop the health checker :return: None """ self._run_health_checker = False if self.publisher is not None: self.publisher.shutdown() if self.subscriber is not None: self.subscriber.shutdown() |
def get_service_env_value(self, key): """ Get a env variable as defined by the service admin :param key: the base of the key to use :return: the env if it exists """ service_key = predix.config.get_env_key(self, key) value = os.environ[service_key] if not value: raise ValueError("%s env unset" % key) return value |
def _init_channel(self): """ build the grpc channel used for both publisher and subscriber :return: None """ host = self._get_host() port = self._get_grpc_port() if 'TLS_PEM_FILE' in os.environ: with open(os.environ['TLS_PEM_FILE'], mode='rb') as f: # b is important -> binary file_content = f.read() credentials = grpc.... |
def _init_health_checker(self): """ start the health checker stub and start a thread to ping it every 30 seconds :return: None """ stub = Health_pb2_grpc.HealthStub(channel=self._channel) self._health_check = stub.Check health_check_thread = threading.Thread(target=self._health_check_thread) health_check_thread.daemon ... |
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.debug('received health check: ' + str(response)) time.sleep(30)... |
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 unique_name = str(uuid.uuid4()).split('... |
return space |
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) |
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_ORGANIZATION_GUID'] = self.org.guid os.environ['PREDIX_ORGANIZATION_... |
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 |
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 need to do this more generally later if add_users: space_users = [] org_users = ... |
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['entity']['name'] == name: guid = space['metadata']['guid'] break if not guid: raise ValueError("Space with... |
self.api.delete("/v2/spaces/%s" % (guid), params={'recursive': 'true'}) |
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 |
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 json_response['next_url'] is not None: json_response = self.api.ge... |
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 |
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 == instance['service_plan']['service']['label']: return True return False |
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" % (self.name)) service = predix.admin.cf.services.Service() for servic... |
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 this number of seconds before giving up. :param allo... |
db backup to be used when initiating """ # MAINT: Add these if there is demand for it and validated if allocated_storage or encryption_at_rest or restore_to_time: raise NotImplementedError() # Will need to wait for the service to be provisioned before can add # service keys and get env details. self.service.create(asyn... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.