text stringlengths 81 112k |
|---|
auto send blocking function, when the interval or the message size has been reached, publish
:return:
def _auto_send(self):
"""
auto send blocking function, when the interval or the message size has been reached, publish
:return:
"""
while True:
if time.time(... |
generate the headers for the connection to event hub service based on the provided config
:return: {} headers
def _generate_publish_headers(self):
"""
generate the headers for the connection to event hub service based on the provided config
:return: {} headers
"""
header... |
publisher callback that grpc and web socket can pass messages to
address the received message onto the queue
:param publish_ack: EventHub_pb2.Ack the ack received from either wss or grpc
:return: None
def _publisher_callback(self, publish_ack):
"""
publisher callback that grpc a... |
initialize the grpc publisher, builds the stub and then starts the grpc manager
:return: None
def _init_grpc_publisher(self):
"""
initialize the grpc publisher, builds the stub and then starts the grpc manager
:return: None
"""
self._stub = EventHub_pb2_grpc.PublisherStu... |
send the messages in the tx queue to the GRPC manager
:return: None
def _publish_queue_grpc(self):
"""
send the messages in the tx queue to the GRPC manager
:return: None
"""
messages = EventHub_pb2.Messages(msg=self._tx_queue)
publish_request = EventHub_pb2.Publ... |
send the messages down the web socket connection as a json object
:return: None
def _publish_queue_wss(self):
"""
send the messages down the web socket connection as a json object
:return: None
"""
msg = []
for m in self._tx_queue:
msg.append({'id': ... |
Create a new web socket connection with proper headers.
def _init_publisher_ws(self):
"""
Create a new web socket connection with proper headers.
"""
logging.debug("Initializing new web socket connection.")
url = ('wss://%s/v1/stream/messages/' % self.eventhub_client.host)
... |
on_message callback of websocket class, load the message into a dict and then
update an Ack Object with the results
:param ws: web socket connection that the message was received on
:param message: web socket message in text form
:return: None
def _on_ws_message(self, ws, message):
... |
Create an instance of the Parking Planning Service with the
typical starting settings.
def create(self):
"""
Create an instance of the Parking Planning Service with the
typical starting settings.
"""
self.service.create()
os.environ[self.__module__ + '.uri'] = se... |
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):
"""
... |
Read an existing manifest.
def read_manifest(self, encrypted=None):
"""
Read an existing manifest.
"""
with open(self.manifest_path, 'r') as input_file:
self.manifest = yaml.safe_load(input_file)
if 'env' not in self.manifest:
self.manifest['env']... |
Create a new manifest and write it to
disk.
def create_manifest(self):
"""
Create a new manifest and write it to
disk.
"""
self.manifest = {}
self.manifest['applications'] = [{'name': self.app_name}]
self.manifest['services'] = []
self.manifest['e... |
Returns contents of the manifest where environment variables
that are secret will be encrypted without modifying the existing
state in memory which will remain unencrypted.
def _get_encrypted_manifest(self):
"""
Returns contents of the manifest where environment variables
that a... |
Write manifest to disk.
:param manifest_path: write to a different location
:param encrypted: write with env data encrypted
def write_manifest(self, manifest_path=None, encrypted=None):
"""
Write manifest to disk.
:param manifest_path: write to a different location
:pa... |
Add the given key / value as another environment
variable.
def add_env_var(self, key, value):
"""
Add the given key / value as another environment
variable.
"""
self.manifest['env'][key] = value
os.environ[key] = str(value) |
Add the given service to the manifest.
def add_service(self, service_name):
"""
Add the given service to the manifest.
"""
if service_name not in self.manifest['services']:
self.manifest['services'].append(service_name) |
Will load any environment variables found in the
manifest file into the current process for use
by applications.
When apps run in cloud foundry this would happen
automatically.
def set_os_environ(self):
"""
Will load any environment variables found in the
manife... |
Return the client id that should have all the
needed scopes and authorities for the services
in this manifest.
def get_client_id(self):
"""
Return the client id that should have all the
needed scopes and authorities for the services
in this manifest.
"""
... |
Return the client secret that should correspond with
the 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')
re... |
Returns an instance of the Time Series Service.
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 |
Returns an instance of the Asset Service.
def get_asset(self):
"""
Returns an instance of the Asset Service.
"""
import predix.data.asset
asset = predix.data.asset.Asset()
return asset |
Returns an insstance of the UAA Service.
def get_uaa(self):
"""
Returns an insstance of the UAA Service.
"""
import predix.security.uaa
uaa = predix.security.uaa.UserAccountAuthentication()
return uaa |
Returns an instance of the Asset Control Service.
def get_acs(self):
"""
Returns an instance of the Asset Control Service.
"""
import predix.security.acs
acs = predix.security.acs.AccessControl()
return acs |
Returns an instance of the Weather Service.
def get_weather(self):
"""
Returns an instance of the Weather Service.
"""
import predix.data.weather
weather = predix.data.weather.WeatherForecast()
return weather |
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 description of reading types:
... |
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 w['reading_type'], '=', w[... |
Can generate a name based on the space, service name and plan.
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() |
Return a sensible configuration path for caching config
settings.
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
... |
Create a Cloud Foundry service that has custom parameters.
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,
... |
Delete a Cloud Foundry service and any associations.
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) |
Get a service key or create one if needed.
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:
... |
Will get configuration for the service from a service key.
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.... |
Create the service.
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... |
Returns a valid UAA instance for performing administrative functions
on services.
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):
... |
Create an instance of the US Weather Forecast Service with
typical starting settings.
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
... |
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()
os.environ[predix.config.get_env_key(self.use_clas... |
Grant the given client id all the scopes and authorities
needed to work with the eventhub service.
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):
"""
... |
returns the publish grpc endpoint for ingestion.
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 protoco... |
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):
"""
... |
Returns the host address for an instance of Blob Store service from
environment inspection.
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 = j... |
Returns the access key for an instance of Blob Store service from
environment inspection.
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:
service... |
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.
def list_objects(self, bucket_name=None, **kwargs):
"""
This method is primarily for illustration and just calls the
... |
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.
def upload_file(self, src_filepath, dest_filename=None, bucket_name=None,
**kwargs):
"""
This method is primar... |
Reads the local cf CLI cache stored in the users
home directory.
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):
... |
Returns the GUID for the organization currently targeted.
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:
i... |
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.
def get_space_guid(self):
"""
Returns the GUID for the space currently targeted.
Can be set by environment variable with PREDIX... |
Get the user's PredixPy manifest key. Generate and store one if not
yet generated.
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... |
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
def get_env_key(obj, key=None):
"""
Return environment variable key to use for lookups within a
namesp... |
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.
def get_env_value(obj, attribute):
"""
Returns the environment variable value for the attribute o... |
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.
def set_env_value(obj, attribute, value):
"""
Set the environment variabl... |
Returns the GUID for the service instance with
the given name.
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']:
... |
Return the service bindings for the service instance.
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']) |
Remove service bindings to applications.
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']) |
Return the service keys for the given service.
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) |
Returns a flat list of the names of the service keys
for the given service.
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)['re... |
Returns the service key details.
Similar to `cf service-key`.
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 ... |
Create a service key for the given service.
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 s... |
Delete a service key for the given service.
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))
... |
Retrieves a service instance with the given name.
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['enti... |
Return the service plans available for a given service.
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']['la... |
Return the service plan GUID for the given service / plan.
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'] == p... |
Create a service instance.
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... |
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.
def delete_service(self, service_name, params=None):
"""
Delete the service of the given name. It may fail if there are
any service keys ... |
Returns the URI endpoint for performing queries of a
Predix Time Series instance from environment inspection.
def _get_query_uri(self):
"""
Returns the URI endpoint for performing queries of a
Predix Time Series instance from environment inspection.
"""
if 'VCAP_SERVICES... |
Returns the ZoneId for performing queries of a Predix
Time Series instance from environment inspection.
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.... |
Will make a direct REST call with the given json body payload to
get datapoints.
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.servic... |
Convenience method that for simple single tag queries will
return just the values to be iterated on.
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],... |
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 relative (ie. '1w-ago' or
1494015972386)
- end: data before this value
- order: ascending (asc) or d... |
Create a new websocket connection with proper headers.
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(),
... |
Reuse existing connection or create a new connection.
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
... |
Establish or reuse socket connection and send
the given message to the timeseries service.
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))
... |
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 constants BAD, GOOD, etc.
(option... |
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:
que... |
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
resultset of interes... |
Shutdown the client, shutdown the sub clients and stop the health checker
:return: None
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 N... |
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
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... |
build the grpc channel used for both publisher and subscriber
:return: None
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... |
start the health checker stub and start a thread to ping it every 30 seconds
:return: None
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._c... |
Health checker thread that pings the service every 30 seconds
:return: None
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(Healt... |
Create a new temporary cloud foundry space for
a project.
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
... |
Get the marketplace services.
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) |
Target the current space for any forthcoming Cloud Foundry
operations.
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
... |
Return a flat list of the names for spaces in the 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... |
Create a new space with the given name in the current target
organization.
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,
'organiz... |
Delete the current space, or a space with the given name
or guid.
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()
... |
Returns a flat list of the service names available
from the marketplace for this space.
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()['res... |
Returns the service instances activated in this space.
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)
... |
Returns a flat list of the names of services created
in this space.
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['ent... |
Tests whether a service instance exists for the given
service.
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']:
... |
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>`.
def purge(self):
"""
Remove all services and apps from the space.
Will leave the space itself, c... |
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... |
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.
def add_to_manifest(self, manifest):
"""
... |
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.
def create(self, asset, timeseries, client_id, client_secret,
ui_client_id=None, ui_client_secret=None):
"""
... |
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.
def _find_service_name(self):
"""
For cloud operation... |
Add to the manifest to make sure it is bound to the
application.
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() |
Returns the Predix Zone Id for the service that is a required
header in service calls.
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.loa... |
Returns a flat list of the names of collections in the asset
service.
..
['wind-turbines', 'jet-engines']
def get_collections(self):
"""
Returns a flat list of the names of collections in the asset
service.
..
['wind-turbines', 'jet-engines']
... |
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)... |
Returns a new guid for use in posting a new asset to a collection.
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])
... |
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.
def post_collection(self, collection, body):
"""
Creates a new collection. This is... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.