idx
int64 0
63k
| question
stringlengths 61
4.03k
| target
stringlengths 6
1.23k
|
|---|---|---|
4,200
|
def create_space ( self , space_name , add_users = True ) : body = { 'name' : space_name , 'organization_guid' : self . api . config . get_organization_guid ( ) } if add_users : space_users = [ ] org_users = self . org . get_users ( ) for org_user in org_users [ 'resources' ] : guid = org_user [ 'metadata' ] [ 'guid' ] space_users . append ( guid ) body [ 'manager_guids' ] = space_users body [ 'developer_guids' ] = space_users return self . api . post ( '/v2/spaces' , body )
|
Create a new space with the given name in the current target organization .
|
4,201
|
def delete_space ( self , name = None , guid = None ) : 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 name %s not found." % ( name ) ) else : guid = self . guid logging . warning ( "Deleting space (%s) and all services." % ( guid ) ) return self . api . delete ( "/v2/spaces/%s" % ( guid ) , params = { 'recursive' : 'true' } )
|
Delete the current space or a space with the given name or guid .
|
4,202
|
def get_services ( self ) : 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 .
|
4,203
|
def _get_instances ( self , page_number = None ) : 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 . get ( json_response [ 'next_url' ] ) instances += json_response [ 'resources' ] return instances
|
Returns the service instances activated in this space .
|
4,204
|
def get_instances ( self ) : 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 .
|
4,205
|
def has_service_of_type ( self , service_type ) : 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
|
Tests whether a service instance exists for the given service .
|
4,206
|
def purge ( self ) : logging . warning ( "Purging all services from space %s" % ( self . name ) ) service = predix . admin . cf . services . Service ( ) for service_name in self . get_instances ( ) : service . purge ( service_name ) apps = predix . admin . cf . apps . App ( ) for app_name in self . get_apps ( ) : apps . delete_app ( app_name )
|
Remove all services and apps from the space .
|
4,207
|
def create ( self , max_wait = 300 , allocated_storage = None , encryption_at_rest = None , restore_to_time = None , ** kwargs ) : if allocated_storage or encryption_at_rest or restore_to_time : raise NotImplementedError ( ) self . service . create ( async = True , create_keys = False ) while self . _create_in_progress ( ) and max_wait > 0 : if max_wait % 5 == 0 : logging . warning ( 'Can take {}s for create to finish.' . format ( max_wait ) ) time . sleep ( 1 ) max_wait -= 1 cfg = self . service . _get_service_config ( ) self . service . settings . save ( cfg ) hostname = predix . config . get_env_key ( self . use_class , 'hostname' ) os . environ [ hostname ] = self . service . settings . data [ 'hostname' ] password = predix . config . get_env_key ( self . use_class , 'password' ) os . environ [ password ] = self . service . settings . data [ 'password' ] port = predix . config . get_env_key ( self . use_class , 'port' ) os . environ [ port ] = str ( self . service . settings . data [ 'port' ] ) username = predix . config . get_env_key ( self . use_class , 'username' ) os . environ [ username ] = self . service . settings . data [ 'username' ] uri = predix . config . get_env_key ( self . use_class , 'uri' ) os . environ [ uri ] = self . service . settings . data [ 'uri' ]
|
Create an instance of the PostgreSQL service with the typical starting settings .
|
4,208
|
def create ( self , asset , timeseries , client_id , client_secret , ui_client_id = None , ui_client_secret = None ) : assert isinstance ( asset , predix . admin . asset . Asset ) , "Require an existing predix.admin.asset.Asset instance" assert isinstance ( timeseries , predix . admin . timeseries . TimeSeries ) , "Require an existing predix.admin.timeseries.TimeSeries instance" parameters = { 'predixAssetZoneId' : asset . get_zone_id ( ) , 'predixTimeseriesZoneId' : timeseries . get_query_zone_id ( ) , 'runtimeClientId' : client_id , 'runtimeClientSecret' : client_secret , 'uiClientId' : ui_client_id or client_id , 'uiClientSecret' : ui_client_secret or client_secret , 'uiDomainPrefix' : self . service . name , } self . service . create ( parameters = parameters )
|
Create an instance of the Analytics Framework Service with the typical starting settings .
|
4,209
|
def add_to_manifest ( self , manifest ) : manifest . add_service ( self . service . name ) manifest . write_manifest ( )
|
Add to the manifest to make sure it is bound to the application .
|
4,210
|
def _get_zone_id ( self ) : if 'VCAP_SERVICES' in os . environ : services = json . loads ( os . getenv ( 'VCAP_SERVICES' ) ) predix_asset = services [ 'predix-asset' ] [ 0 ] [ 'credentials' ] return predix_asset [ 'zone' ] [ 'http-header-value' ] else : return predix . config . get_env_value ( self , 'zone_id' )
|
Returns the Predix Zone Id for the service that is a required header in service calls .
|
4,211
|
def get_collections ( self ) : collections = [ ] for result in self . _get_collections ( ) : collections . append ( result [ 'collection' ] ) return collections
|
Returns a flat list of the names of collections in the asset service .
|
4,212
|
def get_collection ( self , collection , filter = None , fields = None , page_size = None ) : params = { } if filter : params [ 'filter' ] = filter if fields : params [ 'fields' ] = fields if page_size : params [ 'pageSize' ] = page_size uri = self . uri + '/v1' + collection return self . service . _get ( uri , params = params )
|
Returns a specific collection from the asset service with the given collection endpoint .
|
4,213
|
def create_guid ( self , collection = None ) : 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 .
|
4,214
|
def post_collection ( self , collection , body ) : assert isinstance ( body , ( list ) ) , "POST requires body to be a list" assert collection . startswith ( '/' ) , "Collections must start with /" uri = self . uri + '/v1' + collection return self . service . _post ( uri , body )
|
Creates a new collection . This is mostly just transport layer and passes collection and body along . It presumes the body already has generated .
|
4,215
|
def put_collection ( self , collection , body ) : uri = self . uri + '/v1' + collection return self . service . _put ( uri , body )
|
Updates an existing collection .
|
4,216
|
def delete_collection ( self , collection ) : uri = str . join ( '/' , [ self . uri , collection ] ) return self . service . _delete ( uri )
|
Deletes an existing collection .
|
4,217
|
def patch_collection ( self , collection , changes ) : uri = str . join ( '/' , [ self . uri , collection ] ) return self . service . _patch ( uri , changes )
|
Will make specific updates to a record based on JSON Patch documentation .
|
4,218
|
def save ( self , collection ) : 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 .
|
4,219
|
def create_manifest_from_space ( self ) : space = predix . admin . cf . spaces . Space ( ) summary = space . get_space_summary ( ) for instance in summary [ 'services' ] : service_type = instance [ 'service_plan' ] [ 'service' ] [ 'label' ] name = instance [ 'name' ] if service_type in self . supported : service = self . supported [ service_type ] ( name = name ) service . add_to_manifest ( self ) elif service_type == 'us-weather-forecast' : weather = predix . admin . weather . WeatherForecast ( name = name ) weather . add_to_manifest ( self ) else : logging . warning ( "Unsupported service type: %s" % service_type )
|
Populate a manifest file generated from details from the cloud foundry space environment .
|
4,220
|
def lock_to_org_space ( self ) : self . add_env_var ( 'PREDIX_ORGANIZATION_GUID' , self . space . org . guid ) self . add_env_var ( 'PREDIX_ORGANIZATION_NAME' , self . space . org . name ) self . add_env_var ( 'PREDIX_SPACE_GUID' , self . space . guid ) self . add_env_var ( 'PREDIX_SPACE_NAME' , self . space . name ) self . write_manifest ( )
|
Lock the manifest to the current organization and space regardless of Cloud Foundry target .
|
4,221
|
def create_uaa ( self , admin_secret , ** kwargs ) : uaa = predix . admin . uaa . UserAccountAuthentication ( ** kwargs ) if not uaa . exists ( ) : uaa . create ( admin_secret , ** kwargs ) uaa . add_to_manifest ( self ) return uaa
|
Creates an instance of UAA Service .
|
4,222
|
def create_client ( self , client_id = None , client_secret = None , uaa = None ) : if not uaa : uaa = predix . admin . uaa . UserAccountAuthentication ( ) if not client_id : client_id = uaa . _create_id ( ) if not client_secret : client_secret = uaa . _create_secret ( ) uaa . create_client ( client_id , client_secret ) uaa . add_client_to_manifest ( client_id , client_secret , self )
|
Create a client and add it to the manifest .
|
4,223
|
def create_timeseries ( self , ** kwargs ) : 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_manifest ( self ) return ts
|
Creates an instance of the Time Series Service .
|
4,224
|
def create_blobstore ( self , ** kwargs ) : blobstore = predix . admin . blobstore . BlobStore ( ** kwargs ) blobstore . create ( ) blobstore . add_to_manifest ( self ) return blobstore
|
Creates an instance of the BlobStore Service .
|
4,225
|
def create_logstash ( self , ** kwargs ) : logstash = predix . admin . logstash . Logging ( ** kwargs ) logstash . create ( ) logstash . add_to_manifest ( self ) logging . info ( 'Install Kibana-Me-Logs application by following GitHub instructions' ) logging . info ( 'git clone https://github.com/cloudfoundry-community/kibana-me-logs.git' ) return logstash
|
Creates an instance of the Logging Service .
|
4,226
|
def create_cache ( self , ** kwargs ) : cache = predix . admin . cache . Cache ( ** kwargs ) cache . create ( ** kwargs ) cache . add_to_manifest ( self ) return cache
|
Creates an instance of the Cache Service .
|
4,227
|
def get_service_marketplace ( self , available = True , unavailable = False , deprecated = False ) : supported = set ( self . supported . keys ( ) ) all_services = set ( self . space . get_services ( ) ) results = set ( ) if available : results . update ( supported ) if unavailable : results . update ( all_services . difference ( supported ) ) if deprecated : results . update ( supported . difference ( all_services ) ) return list ( results )
|
Returns a list of service names . Can return all services just those supported by PredixPy or just those not yet supported by PredixPy .
|
4,228
|
def _auto_authenticate ( self ) : 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 client_secret : logging . info ( "Automatically authenticated as %s" % ( client_id ) ) self . uaa . authenticate ( client_id , client_secret )
|
If we are in an app context we can authenticate immediately .
|
4,229
|
def _get ( self , uri , params = None , headers = None ) : if not headers : headers = self . _get_headers ( ) logging . debug ( "URI=" + str ( uri ) ) logging . debug ( "HEADERS=" + str ( headers ) ) response = self . session . get ( uri , headers = headers , params = params ) logging . debug ( "STATUS=" + str ( response . status_code ) ) if response . status_code == 200 : return response . json ( ) else : logging . error ( b"ERROR=" + response . content ) response . raise_for_status ( )
|
Simple GET request for a given path .
|
4,230
|
def _post ( self , uri , data ) : 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 ( data ) ) if response . status_code in [ 200 , 204 ] : try : return response . json ( ) except ValueError : return "{}" else : logging . error ( response . content ) response . raise_for_status ( )
|
Simple POST request for a given path .
|
4,231
|
def _put ( self , uri , data ) : 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 ( data ) ) if response . status_code in [ 201 , 204 ] : return data else : logging . error ( response . content ) response . raise_for_status ( )
|
Simple PUT operation for a given path .
|
4,232
|
def _delete ( self , uri ) : headers = self . _get_headers ( ) response = self . session . delete ( uri , headers = headers ) if response . status_code == 204 : return response else : logging . error ( response . content ) response . raise_for_status ( )
|
Simple DELETE operation for a given path .
|
4,233
|
def _patch ( self , uri , data ) : headers = self . _get_headers ( ) response = self . session . patch ( uri , headers = headers , data = json . dumps ( data ) ) if response . status_code == 204 : return response else : logging . error ( response . content ) response . raise_for_status ( )
|
Simple PATCH operation for a given path .
|
4,234
|
def _get_resource_uri ( self , guid = None ) : uri = self . uri + '/v1/resource' if guid : uri += '/' + urllib . quote_plus ( guid ) return uri
|
Returns the full path that uniquely identifies the resource endpoint .
|
4,235
|
def get_resource ( self , resource_id ) : uri = self . _get_resource_uri ( guid = resource_id ) return self . service . _get ( uri )
|
Returns a specific resource by resource id .
|
4,236
|
def _post_resource ( self , body ) : assert isinstance ( body , ( list ) ) , "POST for requires body to be a list" uri = self . _get_resource_uri ( ) return self . service . _post ( uri , body )
|
Create new resources and associated attributes .
|
4,237
|
def delete_resource ( self , resource_id ) : uri = self . _get_resource_uri ( guid = resource_id ) return self . service . _delete ( uri )
|
Remove a specific resource by its identifier .
|
4,238
|
def _put_resource ( self , resource_id , body ) : assert isinstance ( body , ( dict ) ) , "PUT requires body to be a dict." uri = self . _get_resource_uri ( guid = resource_id ) return self . service . _put ( uri , body )
|
Update a resource for the given resource id . The body is not a list but a dictionary of a single resource .
|
4,239
|
def add_resource ( self , resource_id , attributes , parents = [ ] , issuer = 'default' ) : assert isinstance ( attributes , ( dict ) ) , "attributes expected to be dict" attrs = [ ] for key in attributes . keys ( ) : attrs . append ( { 'issuer' : issuer , 'name' : key , 'value' : attributes [ key ] } ) body = { "resourceIdentifier" : resource_id , "parents" : parents , "attributes" : attrs , } return self . _put_resource ( resource_id , body )
|
Will add the given resource with a given identifier and attribute dictionary .
|
4,240
|
def get_subject ( self , subject_id ) : uri = self . _get_subject_uri ( guid = subject_id ) return self . service . _get ( uri )
|
Returns a specific subject by subject id .
|
4,241
|
def _post_subject ( self , body ) : assert isinstance ( body , ( list ) ) , "POST requires body to be a list" uri = self . _get_subject_uri ( ) return self . service . _post ( uri , body )
|
Create new subjects and associated attributes .
|
4,242
|
def delete_subject ( self , subject_id ) : uri = self . _get_subject_uri ( guid = subject_id ) return self . service . _delete ( uri )
|
Remove a specific subject by its identifier .
|
4,243
|
def _put_subject ( self , subject_id , body ) : assert isinstance ( body , ( dict ) ) , "PUT requires body to be dict." uri = self . _get_subject_uri ( guid = subject_id ) return self . service . _put ( uri , body )
|
Update a subject for the given subject id . The body is not a list but a dictionary of a single resource .
|
4,244
|
def add_subject ( self , subject_id , attributes , parents = [ ] , issuer = 'default' ) : assert isinstance ( attributes , ( dict ) ) , "attributes expected to be dict" attrs = [ ] for key in attributes . keys ( ) : attrs . append ( { 'issuer' : issuer , 'name' : key , 'value' : attributes [ key ] } ) body = { "subjectIdentifier" : subject_id , "parents" : parents , "attributes" : attrs , } return self . _put_subject ( subject_id , body )
|
Will add the given subject with a given identifier and attribute dictionary .
|
4,245
|
def _get_monitoring_heartbeat ( self ) : target = self . uri + '/monitoring/heartbeat' response = self . session . get ( target ) return response
|
Tests whether or not the ACS service being monitored is alive .
|
4,246
|
def is_alive ( self ) : 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 .
|
4,247
|
def _put_policy_set ( self , policy_set_id , body ) : 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 .
|
4,248
|
def _get_policy_set ( self , policy_set_id ) : uri = self . _get_policy_set_uri ( guid = policy_set_id ) return self . service . _get ( uri )
|
Get a specific policy set by id .
|
4,249
|
def delete_policy_set ( self , policy_set_id ) : 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 .
|
4,250
|
def add_policy ( self , name , action , resource , subject , condition , policy_set_id = None , effect = 'PERMIT' ) : if not policy_set_id : policy_set_id = str ( uuid . uuid4 ( ) ) if action not in [ 'GET' , 'PUT' , 'POST' , 'DELETE' ] : raise ValueError ( "Invalid action" ) policy = { "name" : name , "target" : { "resource" : resource , "subject" : subject , "action" : action , } , "conditions" : [ { "name" : "" , "condition" : condition , } ] , "effect" : effect , } body = { "name" : policy_set_id , "policies" : [ policy ] , } result = self . _put_policy_set ( policy_set_id , body ) return result
|
Will create a new policy set to enforce the given policy details .
|
4,251
|
def is_allowed ( self , subject_id , action , resource_id , policy_sets = [ ] ) : body = { "action" : action , "subjectIdentifier" : subject_id , "resourceIdentifier" : resource_id , } if policy_sets : body [ 'policySetsEvaluationOrder' ] = policy_sets uri = self . uri + '/v1/policy-evaluation' logging . debug ( "URI=" + str ( uri ) ) logging . debug ( "BODY=" + str ( body ) ) response = self . service . _post ( uri , body ) if 'effect' in response : if response [ 'effect' ] in [ 'NOT_APPLICABLE' , 'PERMIT' ] : return True return False
|
Evaluate a policy - set against a subject and resource .
|
4,252
|
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 ) : hm = Homura ( url , path , headers , session , show_progress , resume , auto_retry , max_rst_retries , pass_through_opts , cainfo , user_agent , auth ) hm . start ( )
|
Main download function
|
4,253
|
def _fill_in_cainfo ( self ) : if self . cainfo : cainfo = self . cainfo else : try : cainfo = certifi . where ( ) except AttributeError : cainfo = None if cainfo : self . _pycurl . setopt ( pycurl . CAINFO , cainfo )
|
Fill in the path of the PEM file containing the CA certificate .
|
4,254
|
def curl ( self ) : c = self . _pycurl 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 ) else : mode = 'wb' with open ( self . path , mode ) as f : c . setopt ( c . URL , utf8_encode ( self . url ) ) if self . auth : c . setopt ( c . USERPWD , '%s:%s' % self . auth ) c . setopt ( c . USERAGENT , self . _user_agent ) c . setopt ( c . WRITEDATA , f ) h = self . _get_pycurl_headers ( ) if h is not None : c . setopt ( pycurl . HTTPHEADER , h ) c . setopt ( c . NOPROGRESS , 0 ) c . setopt ( pycurl . FOLLOWLOCATION , 1 ) c . setopt ( c . PROGRESSFUNCTION , self . progress ) self . _fill_in_cainfo ( ) if self . _pass_through_opts : for key , value in self . _pass_through_opts . items ( ) : c . setopt ( key , value ) c . perform ( )
|
Sending a single cURL request to download
|
4,255
|
def start ( self ) : if not self . auto_retry : self . curl ( ) return while not self . is_finished : try : self . curl ( ) except pycurl . error as e : if e . args [ 0 ] == pycurl . E_PARTIAL_FILE : pass elif e . args [ 0 ] == pycurl . E_HTTP_RANGE_ERROR : break elif e . args [ 0 ] == pycurl . E_RECV_ERROR : if self . _rst_retries < self . max_rst_retries : pass else : raise e self . _rst_retries += 1 else : raise e self . _move_path ( ) self . _done ( )
|
Start downloading handling auto retry download resume and path moving
|
4,256
|
def create ( self , secret , ** kwargs ) : parameters = { "adminClientSecret" : secret } self . service . create ( parameters = parameters ) predix . config . set_env_value ( self . use_class , 'uri' , self . _get_uri ( ) ) self . authenticate ( )
|
Create a new instance of the UAA service . Requires a secret password for the admin user account .
|
4,257
|
def authenticate ( self ) : predix . config . set_env_value ( self . use_class , 'uri' , self . _get_uri ( ) ) self . uaac = predix . security . uaa . UserAccountAuthentication ( ) self . uaac . authenticate ( 'admin' , self . _get_admin_secret ( ) , use_cache = False ) self . is_admin = True
|
Authenticate into the UAA instance as the admin user .
|
4,258
|
def _create_secret ( self , length = 12 ) : charset = string . digits + string . ascii_letters + '+-' return "" . join ( random . SystemRandom ( ) . choice ( charset ) for _ in range ( length ) )
|
Use a cryptograhically - secure Pseudorandom number generator for picking a combination of letters digits and punctuation to be our secret .
|
4,259
|
def create_client ( self , client_id , client_secret ) : 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 .
|
4,260
|
def add_client_to_manifest ( self , client_id , client_secret , manifest ) : assert self . is_admin , "Must authenticate() as admin to create client" return self . uaac . add_client_to_manifest ( client_id , client_secret , manifest )
|
Add the client credentials to the specified manifest .
|
4,261
|
def _get_uaa_uri ( self ) : if 'VCAP_SERVICES' in os . environ : services = json . loads ( os . getenv ( 'VCAP_SERVICES' ) ) predix_uaa = services [ 'predix-uaa' ] [ 0 ] [ 'credentials' ] return predix_uaa [ 'uri' ] else : return predix . config . get_env_value ( self , 'uri' )
|
Returns the URI endpoint for an instance of a UAA service instance from environment inspection .
|
4,262
|
def _authenticate_client ( self , client , secret ) : client_s = str . join ( ':' , [ client , secret ] ) credentials = base64 . b64encode ( client_s . encode ( 'utf-8' ) ) . decode ( 'utf-8' ) headers = { 'Content-Type' : 'application/x-www-form-urlencoded' , 'Cache-Control' : 'no-cache' , 'Authorization' : 'Basic ' + credentials } params = { 'client_id' : client , 'grant_type' : 'client_credentials' } uri = self . uri + '/oauth/token' logging . debug ( "URI=" + str ( uri ) ) logging . debug ( "HEADERS=" + str ( headers ) ) logging . debug ( "BODY=" + str ( params ) ) response = requests . post ( uri , headers = headers , params = params ) if response . status_code == 200 : logging . debug ( "RESPONSE=" + str ( response . json ( ) ) ) return response . json ( ) else : logging . warning ( "Failed to authenticate as %s" % ( client ) ) response . raise_for_status ( )
|
Returns response of authenticating with the given client and secret .
|
4,263
|
def _authenticate_user ( self , user , password ) : headers = self . _get_headers ( ) params = { 'username' : user , 'password' : password , 'grant_type' : 'password' , } uri = self . uri + '/oauth/token' logging . debug ( "URI=" + str ( uri ) ) logging . debug ( "HEADERS=" + str ( headers ) ) logging . debug ( "BODY=" + str ( params ) ) response = requests . post ( uri , headers = headers , params = params ) if response . status_code == 200 : logging . debug ( "RESPONSE=" + str ( response . json ( ) ) ) return response . json ( ) else : logging . warning ( "Failed to authenticate %s" % ( user ) ) response . raise_for_status ( )
|
Returns the response of authenticating with the given user and password .
|
4,264
|
def is_expired_token ( self , client ) : if 'expires' not in client : return True expires = dateutil . parser . parse ( client [ 'expires' ] ) if expires < datetime . datetime . now ( ) : return True return False
|
For a given client will test whether or not the token has expired .
|
4,265
|
def _initialize_uaa_cache ( self ) : try : os . makedirs ( os . path . dirname ( self . _cache_path ) ) except OSError as exc : if exc . errno != errno . EEXIST : raise data = { } data [ self . uri ] = [ ] return data
|
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 .
|
4,266
|
def _get_client_from_cache ( self , client_id ) : data = self . _read_uaa_cache ( ) if self . uri not in data : return for client in data [ self . uri ] : if client [ 'id' ] == client_id : return client
|
For the given client_id return what is cached .
|
4,267
|
def _write_to_uaa_cache ( self , new_item ) : data = self . _read_uaa_cache ( ) if self . uri not in data : data [ self . uri ] = [ ] for client in data [ self . uri ] : if new_item [ 'id' ] == client [ 'id' ] : data [ self . uri ] . remove ( client ) continue if 'expires' in client : expires = dateutil . parser . parse ( client [ 'expires' ] ) if expires < datetime . datetime . now ( ) : data [ self . uri ] . remove ( client ) continue data [ self . uri ] . append ( new_item ) with open ( self . _cache_path , 'w' ) as output : output . write ( json . dumps ( data , sort_keys = True , indent = 4 ) )
|
Cache the client details into a cached file on disk .
|
4,268
|
def authenticate ( self , client_id , client_secret , use_cache = True ) : if use_cache : client = self . _get_client_from_cache ( client_id ) if ( client ) and ( not self . is_expired_token ( client ) ) : self . authenticated = True self . client = client return client = { 'id' : client_id , 'secret' : client_secret } res = self . _authenticate_client ( client_id , client_secret ) client . update ( res ) expires = datetime . datetime . now ( ) + datetime . timedelta ( seconds = res [ 'expires_in' ] ) client [ 'expires' ] = expires . isoformat ( ) self . _write_to_uaa_cache ( client ) self . client = client self . authenticated = True
|
Authenticate the given client against UAA . The resulting token will be cached for reuse .
|
4,269
|
def logout ( self ) : data = self . _read_uaa_cache ( ) if self . uri in data : for client in data [ self . uri ] : if client [ 'id' ] == self . client [ 'id' ] : data [ self . uri ] . remove ( client ) with open ( self . _cache_path , 'w' ) as output : output . write ( json . dumps ( data , sort_keys = True , indent = 4 ) )
|
Log currently authenticated user out invalidating any existing tokens .
|
4,270
|
def _post ( self , uri , data , headers = None ) : if not headers : headers = self . _get_headers ( ) logging . debug ( "URI=" + str ( uri ) ) logging . debug ( "HEADERS=" + str ( headers ) ) logging . debug ( "BODY=" + str ( data ) ) response = self . session . post ( uri , headers = headers , data = json . dumps ( data ) ) logging . debug ( "STATUS=" + str ( response . status_code ) ) if response . status_code in [ 200 , 201 ] : return response . json ( ) else : logging . error ( b"ERROR=" + response . content ) response . raise_for_status ( )
|
Simple POST request for a given uri path .
|
4,271
|
def get_token ( self ) : if not self . authenticated : raise ValueError ( "Must authenticate() as a client first." ) if self . is_expired_token ( self . client ) : logging . info ( "client token expired, will need to refresh token" ) self . authenticate ( self . client [ 'id' ] , self . client [ 'secret' ] , use_cache = False ) return self . client [ 'access_token' ]
|
Returns the bare access token for the authorized client .
|
4,272
|
def get_scopes ( self ) : 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 .
|
4,273
|
def assert_has_permission ( self , scope_required ) : if not self . authenticated : raise ValueError ( "Must first authenticate()" ) if scope_required not in self . get_scopes ( ) : logging . warning ( "Authenticated as %s" % ( self . client [ 'id' ] ) ) logging . warning ( "Have scopes: %s" % ( str . join ( ',' , self . get_scopes ( ) ) ) ) logging . warning ( "Insufficient scope %s for operation" % ( scope_required ) ) raise ValueError ( "Client does not have permission." ) return True
|
Warn that the required scope is not found in the scopes granted to the currently authenticated user .
|
4,274
|
def grant_client_permissions ( self , client_id , admin = False , write = False , read = False , secret = False ) : self . assert_has_permission ( 'clients.admin' ) perms = [ ] if admin : perms . append ( 'clients.admin' ) if write or admin : perms . append ( 'clients.write' ) if read or admin : perms . append ( 'clients.read' ) if secret or admin : perms . append ( 'clients.secret' ) if perms : self . update_client_grants ( client_id , scope = perms , authorities = perms )
|
Grant the given client_id permissions for managing clients .
|
4,275
|
def get_clients ( self ) : self . assert_has_permission ( 'clients.read' ) uri = self . uri + '/oauth/clients' headers = self . get_authorization_headers ( ) response = requests . get ( uri , headers = headers ) return response . json ( ) [ 'resources' ]
|
Returns the clients stored in the instance of UAA .
|
4,276
|
def get_client ( self , client_id ) : self . assert_has_permission ( 'clients.read' ) uri = self . uri + '/oauth/clients/' + client_id headers = self . get_authorization_headers ( ) response = requests . get ( uri , headers = headers ) if response . status_code == 200 : return response . json ( ) else : return
|
Returns details about a specific client by the client_id .
|
4,277
|
def update_client_grants ( self , client_id , scope = [ ] , authorities = [ ] , grant_types = [ ] , redirect_uri = [ ] , replace = False ) : self . assert_has_permission ( 'clients.write' ) client = self . get_client ( client_id ) if not client : raise ValueError ( "Must first create client: '%s'" % ( client_id ) ) if replace : changes = { 'client_id' : client_id , 'scope' : scope , 'authorities' : authorities , } else : changes = { 'client_id' : client_id } if scope : changes [ 'scope' ] = client [ 'scope' ] changes [ 'scope' ] . extend ( scope ) if authorities : changes [ 'authorities' ] = client [ 'authorities' ] changes [ 'authorities' ] . extend ( authorities ) if grant_types : if 'authorization_code' in grant_types and not redirect_uri : logging . warning ( "A redirect_uri is required for authorization_code." ) changes [ 'authorized_grant_types' ] = client [ 'authorized_grant_types' ] changes [ 'authorized_grant_types' ] . extend ( grant_types ) if redirect_uri : if 'redirect_uri' in client : changes [ 'redirect_uri' ] = client [ 'redirect_uri' ] changes [ 'redirect_uri' ] . extend ( redirect_uri ) else : changes [ 'redirect_uri' ] = redirect_uri uri = self . uri + '/oauth/clients/' + client_id headers = { "pragma" : "no-cache" , "Cache-Control" : "no-cache" , "Content-Type" : "application/json" , "Accepts" : "application/json" , "Authorization" : "Bearer " + self . get_token ( ) } logging . debug ( "URI=" + str ( uri ) ) logging . debug ( "HEADERS=" + str ( headers ) ) logging . debug ( "BODY=" + json . dumps ( changes ) ) response = requests . put ( uri , headers = headers , data = json . dumps ( changes ) ) logging . debug ( "STATUS=" + str ( response . status_code ) ) if response . status_code == 200 : return response else : logging . error ( response . content ) response . raise_for_status ( )
|
Will extend the client with additional scopes or authorities . Any existing scopes and authorities will be left as is unless asked to replace entirely .
|
4,278
|
def create_client ( self , client_id , client_secret , manifest = None , client_credentials = True , refresh_token = True , authorization_code = False , redirect_uri = [ ] ) : self . assert_has_permission ( 'clients.admin' ) if authorization_code and not redirect_uri : raise ValueError ( "Must provide a redirect_uri for clients used with authorization_code" ) client = self . get_client ( client_id ) if client : return client uri = self . uri + '/oauth/clients' headers = { "pragma" : "no-cache" , "Cache-Control" : "no-cache" , "Content-Type" : "application/json" , "Accepts" : "application/json" , "Authorization" : "Bearer " + self . get_token ( ) } grant_types = [ ] if client_credentials : grant_types . append ( 'client_credentials' ) if refresh_token : grant_types . append ( 'refresh_token' ) if authorization_code : grant_types . append ( 'authorization_code' ) params = { "client_id" : client_id , "client_secret" : client_secret , "scope" : [ "uaa.none" ] , "authorized_grant_types" : grant_types , "authorities" : [ "uaa.none" ] , "autoapprove" : [ ] } if redirect_uri : params . append ( redirect_uri ) response = requests . post ( uri , headers = headers , data = json . dumps ( params ) ) if response . status_code == 201 : if manifest : self . add_client_to_manifest ( client_id , client_secret , manifest ) client = { 'id' : client_id , 'secret' : client_secret } self . _write_to_uaa_cache ( client ) return response else : logging . error ( response . content ) response . raise_for_status ( )
|
Will create a new client for your application use .
|
4,279
|
def create_user ( self , username , password , family_name , given_name , primary_email , details = { } ) : self . assert_has_permission ( 'scim.write' ) data = { 'userName' : username , 'password' : password , 'name' : { 'familyName' : family_name , 'givenName' : given_name , } , 'emails' : [ { 'value' : primary_email , 'primary' : True , } ] } if details : data . update ( details ) return self . _post_user ( data )
|
Creates a new user account with the required details .
|
4,280
|
def delete_user ( self , 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 ) ) response = self . session . delete ( uri , headers = headers ) logging . debug ( "STATUS=" + str ( response . status_code ) ) if response . status_code == 200 : return response else : logging . error ( response . content ) response . raise_for_status ( )
|
Delete user with given id .
|
4,281
|
def get_user_by_username ( self , username ) : results = self . get_users ( filter = 'username eq "%s"' % ( username ) ) if results [ 'totalResults' ] == 0 : logging . warning ( "Found no matches for given username." ) return elif results [ 'totalResults' ] > 1 : logging . warning ( "Found %s matches for username %s" % ( results [ 'totalResults' ] , username ) ) return results [ 'resources' ] [ 0 ]
|
Returns details for user of the given username .
|
4,282
|
def get_user_by_email ( self , email ) : results = self . get_users ( filter = 'email eq "%s"' % ( email ) ) if results [ 'totalResults' ] == 0 : logging . warning ( "Found no matches for given email." ) return elif results [ 'totalResults' ] > 1 : logging . warning ( "Found %s matches for email %s" % ( results [ 'totalResults' ] , email ) ) return results [ 'resources' ] [ 0 ]
|
Returns details for user with the given email address .
|
4,283
|
def get_user ( self , id ) : self . assert_has_permission ( 'scim.read' ) return self . _get ( self . uri + '/Users/%s' % ( id ) )
|
Returns details about the user for the given id .
|
4,284
|
def grant_client ( self , client_id , read = True , write = True ) : scopes = [ 'openid' ] authorities = [ 'uaa.resource' ] if write : for zone in self . service . settings . data [ 'ingest' ] [ 'zone-token-scopes' ] : scopes . append ( zone ) authorities . append ( zone ) if read : for zone in self . service . settings . data [ 'query' ] [ 'zone-token-scopes' ] : scopes . append ( zone ) authorities . append ( zone ) self . service . uaa . uaac . update_client_grants ( client_id , scope = scopes , authorities = authorities ) return self . service . uaa . uaac . get_client ( client_id )
|
Grant the given client id all the scopes and authorities needed to work with the timeseries service .
|
4,285
|
def get_query_uri ( self ) : query_uri = self . service . settings . data [ 'query' ] [ 'uri' ] query_uri = urlparse ( query_uri ) return query_uri . scheme + '://' + query_uri . netloc
|
Return the uri used for queries on time series data .
|
4,286
|
def find_requirements ( path ) : requirements = [ ] setup_py = os . path . join ( path , 'setup.py' ) if os . path . exists ( setup_py ) and os . path . isfile ( setup_py ) : try : requirements = from_setup_py ( setup_py ) requirements . sort ( ) return requirements except CouldNotParseRequirements : pass for reqfile_name in ( 'requirements.txt' , 'requirements.pip' ) : reqfile_path = os . path . join ( path , reqfile_name ) if os . path . exists ( reqfile_path ) and os . path . isfile ( reqfile_path ) : try : requirements += from_requirements_txt ( reqfile_path ) except CouldNotParseRequirements as e : pass requirements_dir = os . path . join ( path , 'requirements' ) if os . path . exists ( requirements_dir ) and os . path . isdir ( requirements_dir ) : from_dir = from_requirements_dir ( requirements_dir ) if from_dir is not None : requirements += from_dir from_blob = from_requirements_blob ( path ) if from_blob is not None : requirements += from_blob requirements = list ( set ( requirements ) ) if len ( requirements ) > 0 : requirements . sort ( ) return requirements raise RequirementsNotFound
|
This method tries to determine the requirements of a particular project by inspecting the possible places that they could be defined .
|
4,287
|
def get_app_guid ( self , app_name ) : summary = self . space . get_space_summary ( ) for app in summary [ 'apps' ] : if app [ 'name' ] == app_name : return app [ 'guid' ]
|
Returns the GUID for the app instance with the given name .
|
4,288
|
def delete_app ( self , app_name ) : if app_name not in self . space . get_apps ( ) : logging . warning ( "App not found so... succeeded?" ) return True guid = self . get_app_guid ( app_name ) self . api . delete ( "/v2/apps/%s" % ( guid ) )
|
Delete the given app .
|
4,289
|
def _get_service_config ( self ) : if not os . path . exists ( self . config_path ) : try : os . makedirs ( os . path . dirname ( self . config_path ) ) except OSError as exc : if exc . errno != errno . EEXIST : raise return { } with open ( self . config_path , 'r' ) as data : return json . load ( data )
|
Reads in config file of UAA credential information or generates one as a side - effect if not yet initialized .
|
4,290
|
def _write_service_config ( self ) : with open ( self . config_path , 'w' ) as output : output . write ( json . dumps ( self . data , sort_keys = True , indent = 4 ) )
|
Will write the config out to disk .
|
4,291
|
def create ( self , ** kwargs ) : self . service . create ( ** kwargs ) predix . config . set_env_value ( self . use_class , 'url' , self . service . settings . data [ 'url' ] ) predix . config . set_env_value ( self . use_class , 'access_key_id' , self . service . settings . data [ 'access_key_id' ] ) predix . config . set_env_value ( self . use_class , 'bucket_name' , self . service . settings . data [ 'bucket_name' ] ) predix . config . set_env_value ( self . use_class , 'host' , self . service . settings . data [ 'host' ] ) predix . config . set_env_value ( self . use_class , 'secret_access_key' , self . service . settings . data [ 'secret_access_key' ] )
|
Create an instance of the Blob Store Service with the typical starting settings .
|
4,292
|
def _get_assets ( self , bbox , size = None , page = None , asset_type = None , device_type = None , event_type = None , media_type = None ) : uri = self . uri + '/v1/assets/search' headers = self . _get_headers ( ) params = { 'bbox' : bbox , } params [ 'q' ] = [ ] if device_type : if isinstance ( device_type , str ) : device_type = [ device_type ] for device in device_type : if device not in self . DEVICE_TYPES : logging . warning ( "Invalid device type: %s" % device ) params [ 'q' ] . append ( "device-type:%s" % device ) if asset_type : if isinstance ( asset_type , str ) : asset_type = [ asset_type ] for asset in asset_type : if asset not in self . ASSET_TYPES : logging . warning ( "Invalid asset type: %s" % asset ) params [ 'q' ] . append ( "assetType:%s" % asset ) if media_type : if isinstance ( media_type , str ) : media_type = [ media_type ] for media in media_type : if media not in self . MEDIA_TYPES : logging . warning ( "Invalid media type: %s" % media ) params [ 'q' ] . append ( "mediaType:%s" % media ) if event_type : if isinstance ( event_type , str ) : event_type = [ event_type ] for event in event_type : if event not in self . EVENT_TYPES : logging . warning ( "Invalid event type: %s" % event ) params [ 'q' ] . append ( "eventTypes:%s" % event ) if size : params [ 'size' ] = size if page : params [ 'page' ] = page return self . service . _get ( uri , params = params , headers = headers )
|
Returns the raw results of an asset search for a given bounding box .
|
4,293
|
def get_assets ( self , bbox , ** kwargs ) : response = self . _get_assets ( bbox , ** kwargs ) assets = [ ] for asset in response [ '_embedded' ] [ 'assets' ] : asset_url = asset [ '_links' ] [ 'self' ] uid = asset_url [ 'href' ] . split ( '/' ) [ - 1 ] asset [ 'uid' ] = uid del ( asset [ '_links' ] ) assets . append ( asset ) return assets
|
Query the assets stored in the intelligent environment for a given bounding box and query .
|
4,294
|
def _get_asset ( self , asset_uid ) : uri = self . uri + '/v2/assets/' + asset_uid headers = self . _get_headers ( ) return self . service . _get ( uri , headers = headers )
|
Returns raw response for an given asset by its unique id .
|
4,295
|
def label ( self , input_grid ) : unset = 0 high_labels , num_labels = label ( input_grid > self . high_thresh ) region_ranking = np . argsort ( maximum ( input_grid , high_labels , index = np . arange ( 1 , num_labels + 1 ) ) ) [ : : - 1 ] output_grid = np . zeros ( input_grid . shape , dtype = int ) stack = [ ] for rank in region_ranking : label_num = rank + 1 label_i , label_j = np . where ( high_labels == label_num ) for i in range ( label_i . size ) : if output_grid [ label_i [ i ] , label_j [ i ] ] == unset : stack . append ( ( label_i [ i ] , label_j [ i ] ) ) while len ( stack ) > 0 : index = stack . pop ( ) output_grid [ index ] = label_num for i in range ( index [ 0 ] - 1 , index [ 0 ] + 2 ) : for j in range ( index [ 1 ] - 1 , index [ 1 ] + 2 ) : if 0 <= i < output_grid . shape [ 0 ] and 0 <= j < output_grid . shape [ 1 ] : if ( input_grid [ i , j ] > self . low_thresh ) and ( output_grid [ i , j ] == unset ) : stack . append ( ( i , j ) ) return output_grid
|
Label input grid with hysteresis method .
|
4,296
|
def size_filter ( labeled_grid , min_size ) : out_grid = np . zeros ( labeled_grid . shape , dtype = int ) slices = find_objects ( labeled_grid ) j = 1 for i , s in enumerate ( slices ) : box = labeled_grid [ s ] size = np . count_nonzero ( box . ravel ( ) == ( i + 1 ) ) if size >= min_size and box . shape [ 0 ] > 1 and box . shape [ 1 ] > 1 : out_grid [ np . where ( labeled_grid == i + 1 ) ] = j j += 1 return out_grid
|
Remove labeled objects that do not meet size threshold criteria .
|
4,297
|
def get_string ( self , prompt , default_str = None ) -> str : accept_event = threading . Event ( ) value_ref = [ None ] def perform ( ) : def accepted ( text ) : value_ref [ 0 ] = text accept_event . set ( ) def rejected ( ) : accept_event . set ( ) self . __message_column . remove_all ( ) pose_get_string_message_box ( self . ui , self . __message_column , prompt , str ( default_str ) , accepted , rejected ) with self . __lock : self . __q . append ( perform ) self . document_controller . add_task ( "ui_" + str ( id ( self ) ) , self . __handle_output_and_q ) accept_event . wait ( ) def update_message_column ( ) : self . __message_column . remove_all ( ) self . __message_column . add ( self . __make_cancel_row ( ) ) self . document_controller . add_task ( "ui_" + str ( id ( self ) ) , update_message_column ) if value_ref [ 0 ] is None : raise Exception ( "Cancel" ) return value_ref [ 0 ]
|
Return a string value that the user enters . Raises exception for cancel .
|
4,298
|
def isfinite ( self ) : "Test whether the predicted values are finite" if self . _multiple_outputs : if self . hy_test is not None : r = [ ( hy . isfinite ( ) and ( hyt is None or hyt . isfinite ( ) ) ) for hy , hyt in zip ( self . hy , self . hy_test ) ] else : r = [ hy . isfinite ( ) for hy in self . hy ] return np . all ( r ) return self . hy . isfinite ( ) and ( self . hy_test is None or self . hy_test . isfinite ( ) )
|
Test whether the predicted values are finite
|
4,299
|
def value_of_named_argument_in_function ( argument_name , function_name , search_str , resolve_varname = False ) : try : search_str = unicode ( search_str ) except NameError : pass readline = StringIO ( search_str ) . readline try : token_generator = tokenize . generate_tokens ( readline ) tokens = [ SimplifiedToken ( toknum , tokval ) for toknum , tokval , _ , _ , _ in token_generator ] except tokenize . TokenError as e : raise ValueError ( 'search_str is not parse-able python code: ' + str ( e ) ) in_function = False is_var = False for i in range ( len ( tokens ) ) : if ( not in_function and tokens [ i ] . typenum == tokenize . NAME and tokens [ i ] . value == function_name and tokens [ i + 1 ] . typenum == tokenize . OP and tokens [ i + 1 ] . value == '(' ) : in_function = True continue elif ( in_function and tokens [ i ] . typenum == tokenize . NAME and tokens [ i ] . value == argument_name and tokens [ i + 1 ] . typenum == tokenize . OP and tokens [ i + 1 ] . value == '=' ) : if resolve_varname and tokens [ i + 2 ] . typenum == 1 : is_var = True argument_name = tokens [ i + 2 ] . value break j = 3 while True : if tokens [ i + j ] . value in ( ',' , ')' ) or tokens [ i + j ] . typenum == 58 : break j += 1 return '' . join ( [ t . value for t in tokens [ i + 2 : i + j ] ] ) . strip ( ) if is_var : for i in range ( len ( tokens ) ) : if ( tokens [ i ] . typenum == tokenize . NAME and tokens [ i ] . value == argument_name and tokens [ i + 1 ] . typenum == tokenize . OP and tokens [ i + 1 ] . value == '=' ) : return tokens [ i + 2 ] . value . strip ( ) return None
|
Parse an arbitrary block of python code to get the value of a named argument from inside a function call
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.