repository_name
stringlengths 7
55
| func_path_in_repository
stringlengths 4
223
| func_name
stringlengths 1
134
| whole_func_string
stringlengths 75
104k
| language
stringclasses 1
value | func_code_string
stringlengths 75
104k
| func_code_tokens
listlengths 19
28.4k
| func_documentation_string
stringlengths 1
46.9k
| func_documentation_tokens
listlengths 1
1.97k
| split_name
stringclasses 1
value | func_code_url
stringlengths 87
315
|
|---|---|---|---|---|---|---|---|---|---|---|
PredixDev/predixpy
|
predix/data/eventhub/client.py
|
Eventhub._health_check_thread
|
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)
return
|
python
|
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)
return
|
[
"def",
"_health_check_thread",
"(",
"self",
")",
":",
"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",
")",
"return"
] |
Health checker thread that pings the service every 30 seconds
:return: None
|
[
"Health",
"checker",
"thread",
"that",
"pings",
"the",
"service",
"every",
"30",
"seconds",
":",
"return",
":",
"None"
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/eventhub/client.py#L116-L125
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
create_temp_space
|
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('-')[-1]
admin = predix.admin.cf.spaces.Space()
res = admin.create_space(unique_name)
space = predix.admin.cf.spaces.Space(
guid=res['metadata']['guid'],
name=res['entity']['name'])
space.target()
return space
|
python
|
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('-')[-1]
admin = predix.admin.cf.spaces.Space()
res = admin.create_space(unique_name)
space = predix.admin.cf.spaces.Space(
guid=res['metadata']['guid'],
name=res['entity']['name'])
space.target()
return space
|
[
"def",
"create_temp_space",
"(",
")",
":",
"# 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",
"(",
"'-'",
")",
"[",
"-",
"1",
"]",
"admin",
"=",
"predix",
".",
"admin",
".",
"cf",
".",
"spaces",
".",
"Space",
"(",
")",
"res",
"=",
"admin",
".",
"create_space",
"(",
"unique_name",
")",
"space",
"=",
"predix",
".",
"admin",
".",
"cf",
".",
"spaces",
".",
"Space",
"(",
"guid",
"=",
"res",
"[",
"'metadata'",
"]",
"[",
"'guid'",
"]",
",",
"name",
"=",
"res",
"[",
"'entity'",
"]",
"[",
"'name'",
"]",
")",
"space",
".",
"target",
"(",
")",
"return",
"space"
] |
Create a new temporary cloud foundry space for
a project.
|
[
"Create",
"a",
"new",
"temporary",
"cloud",
"foundry",
"space",
"for",
"a",
"project",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L11-L29
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space._get_spaces
|
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)
|
python
|
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",
"_get_spaces",
"(",
"self",
")",
":",
"guid",
"=",
"self",
".",
"api",
".",
"config",
".",
"get_organization_guid",
"(",
")",
"uri",
"=",
"'/v2/organizations/%s/spaces'",
"%",
"(",
"guid",
")",
"return",
"self",
".",
"api",
".",
"get",
"(",
"uri",
")"
] |
Get the marketplace services.
|
[
"Get",
"the",
"marketplace",
"services",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L46-L52
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.target
|
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_NAME'] = self.org.name
|
python
|
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_NAME'] = self.org.name
|
[
"def",
"target",
"(",
"self",
")",
":",
"# 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_NAME'",
"]",
"=",
"self",
".",
"org",
".",
"name"
] |
Target the current space for any forthcoming Cloud Foundry
operations.
|
[
"Target",
"the",
"current",
"space",
"for",
"any",
"forthcoming",
"Cloud",
"Foundry",
"operations",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L54-L63
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.get_spaces
|
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
|
python
|
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",
"get_spaces",
"(",
"self",
")",
":",
"self",
".",
"spaces",
"=",
"[",
"]",
"for",
"resource",
"in",
"self",
".",
"_get_spaces",
"(",
")",
"[",
"'resources'",
"]",
":",
"self",
".",
"spaces",
".",
"append",
"(",
"resource",
"[",
"'entity'",
"]",
"[",
"'name'",
"]",
")",
"return",
"self",
".",
"spaces"
] |
Return a flat list of the names for spaces in the organization.
|
[
"Return",
"a",
"flat",
"list",
"of",
"the",
"names",
"for",
"spaces",
"in",
"the",
"organization",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L65-L73
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.create_space
|
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 = 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)
|
python
|
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 = 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)
|
[
"def",
"create_space",
"(",
"self",
",",
"space_name",
",",
"add_users",
"=",
"True",
")",
":",
"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",
"=",
"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.
|
[
"Create",
"a",
"new",
"space",
"with",
"the",
"given",
"name",
"in",
"the",
"current",
"target",
"organization",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L83-L104
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.delete_space
|
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 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'})
|
python
|
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 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'})
|
[
"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.
|
[
"Delete",
"the",
"current",
"space",
"or",
"a",
"space",
"with",
"the",
"given",
"name",
"or",
"guid",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L112-L133
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.get_services
|
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
|
python
|
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_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.
|
[
"Returns",
"a",
"flat",
"list",
"of",
"the",
"service",
"names",
"available",
"from",
"the",
"marketplace",
"for",
"this",
"space",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L177-L186
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space._get_instances
|
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.get(json_response['next_url'])
instances += json_response['resources']
return instances
|
python
|
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.get(json_response['next_url'])
instances += json_response['resources']
return instances
|
[
"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.
|
[
"Returns",
"the",
"service",
"instances",
"activated",
"in",
"this",
"space",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L188-L200
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.get_instances
|
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
|
python
|
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",
"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.
|
[
"Returns",
"a",
"flat",
"list",
"of",
"the",
"names",
"of",
"services",
"created",
"in",
"this",
"space",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L202-L211
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.has_service_of_type
|
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
|
python
|
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",
"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.
|
[
"Tests",
"whether",
"a",
"service",
"instance",
"exists",
"for",
"the",
"given",
"service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L220-L231
|
PredixDev/predixpy
|
predix/admin/cf/spaces.py
|
Space.purge
|
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 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)
|
python
|
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 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)
|
[
"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.
Will leave the space itself, call delete_space() if you
want to remove that too.
Similar to `cf delete-space -f <space-name>`.
|
[
"Remove",
"all",
"services",
"and",
"apps",
"from",
"the",
"space",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/cf/spaces.py#L233-L251
|
PredixDev/predixpy
|
predix/admin/dbaas.py
|
PostgreSQL.create
|
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 allocated_storage: int for GBs to be allocated for storage
:param encryption_at_rest: boolean for encrypting data that is stored
:param restore_to_time: UTC date within recovery period for 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(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
# Now get the service env (via service keys)
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']
|
python
|
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 allocated_storage: int for GBs to be allocated for storage
:param encryption_at_rest: boolean for encrypting data that is stored
:param restore_to_time: UTC date within recovery period for 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(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
# Now get the service env (via service keys)
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']
|
[
"def",
"create",
"(",
"self",
",",
"max_wait",
"=",
"300",
",",
"allocated_storage",
"=",
"None",
",",
"encryption_at_rest",
"=",
"None",
",",
"restore_to_time",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# 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",
"(",
"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",
"# Now get the service env (via service keys)",
"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.
: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 encryption_at_rest: boolean for encrypting data that is stored
:param restore_to_time: UTC date within recovery period for db
backup to be used when initiating
|
[
"Create",
"an",
"instance",
"of",
"the",
"PostgreSQL",
"service",
"with",
"the",
"typical",
"starting",
"settings",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/dbaas.py#L43-L93
|
PredixDev/predixpy
|
predix/admin/dbaas.py
|
PostgreSQL.add_to_manifest
|
def add_to_manifest(self, manifest):
"""
Add useful details to the manifest about this service so
that it can be used in an application.
:param manifest: A predix.admin.app.Manifest object instance
that manages reading/writing manifest config for a
cloud foundry app.
"""
manifest.add_service(self.service.name)
hostname = predix.config.get_env_key(self.use_class, 'hostname')
manifest.add_env_var(hostname, self.service.settings.data['hostname'])
password = predix.config.get_env_key(self.use_class, 'password')
manifest.add_env_var(password, self.service.settings.data['password'])
port = predix.config.get_env_key(self.use_class, 'port')
manifest.add_env_var(port, self.service.settings.data['port'])
username = predix.config.get_env_key(self.use_class, 'username')
manifest.add_env_var(username, self.service.settings.data['username'])
uri = predix.config.get_env_key(self.use_class, 'uri')
manifest.add_env_var(uri, self.service.settings.data['uri'])
manifest.write_manifest()
|
python
|
def add_to_manifest(self, manifest):
"""
Add useful details to the manifest about this service so
that it can be used in an application.
:param manifest: A predix.admin.app.Manifest object instance
that manages reading/writing manifest config for a
cloud foundry app.
"""
manifest.add_service(self.service.name)
hostname = predix.config.get_env_key(self.use_class, 'hostname')
manifest.add_env_var(hostname, self.service.settings.data['hostname'])
password = predix.config.get_env_key(self.use_class, 'password')
manifest.add_env_var(password, self.service.settings.data['password'])
port = predix.config.get_env_key(self.use_class, 'port')
manifest.add_env_var(port, self.service.settings.data['port'])
username = predix.config.get_env_key(self.use_class, 'username')
manifest.add_env_var(username, self.service.settings.data['username'])
uri = predix.config.get_env_key(self.use_class, 'uri')
manifest.add_env_var(uri, self.service.settings.data['uri'])
manifest.write_manifest()
|
[
"def",
"add_to_manifest",
"(",
"self",
",",
"manifest",
")",
":",
"manifest",
".",
"add_service",
"(",
"self",
".",
"service",
".",
"name",
")",
"hostname",
"=",
"predix",
".",
"config",
".",
"get_env_key",
"(",
"self",
".",
"use_class",
",",
"'hostname'",
")",
"manifest",
".",
"add_env_var",
"(",
"hostname",
",",
"self",
".",
"service",
".",
"settings",
".",
"data",
"[",
"'hostname'",
"]",
")",
"password",
"=",
"predix",
".",
"config",
".",
"get_env_key",
"(",
"self",
".",
"use_class",
",",
"'password'",
")",
"manifest",
".",
"add_env_var",
"(",
"password",
",",
"self",
".",
"service",
".",
"settings",
".",
"data",
"[",
"'password'",
"]",
")",
"port",
"=",
"predix",
".",
"config",
".",
"get_env_key",
"(",
"self",
".",
"use_class",
",",
"'port'",
")",
"manifest",
".",
"add_env_var",
"(",
"port",
",",
"self",
".",
"service",
".",
"settings",
".",
"data",
"[",
"'port'",
"]",
")",
"username",
"=",
"predix",
".",
"config",
".",
"get_env_key",
"(",
"self",
".",
"use_class",
",",
"'username'",
")",
"manifest",
".",
"add_env_var",
"(",
"username",
",",
"self",
".",
"service",
".",
"settings",
".",
"data",
"[",
"'username'",
"]",
")",
"uri",
"=",
"predix",
".",
"config",
".",
"get_env_key",
"(",
"self",
".",
"use_class",
",",
"'uri'",
")",
"manifest",
".",
"add_env_var",
"(",
"uri",
",",
"self",
".",
"service",
".",
"settings",
".",
"data",
"[",
"'uri'",
"]",
")",
"manifest",
".",
"write_manifest",
"(",
")"
] |
Add useful details to the manifest about this service so
that it can be used in an application.
:param manifest: A predix.admin.app.Manifest object instance
that manages reading/writing manifest config for a
cloud foundry app.
|
[
"Add",
"useful",
"details",
"to",
"the",
"manifest",
"about",
"this",
"service",
"so",
"that",
"it",
"can",
"be",
"used",
"in",
"an",
"application",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/dbaas.py#L95-L121
|
PredixDev/predixpy
|
predix/admin/analytics.py
|
AnalyticsFramework.create
|
def create(self, asset, timeseries, client_id, client_secret,
ui_client_id=None, ui_client_secret=None):
"""
Create an instance of the Analytics Framework Service with the
typical starting settings.
If not provided, will reuse the runtime client for the ui
as well.
"""
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)
|
python
|
def create(self, asset, timeseries, client_id, client_secret,
ui_client_id=None, ui_client_secret=None):
"""
Create an instance of the Analytics Framework Service with the
typical starting settings.
If not provided, will reuse the runtime client for the ui
as well.
"""
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)
|
[
"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.
If not provided, will reuse the runtime client for the ui
as well.
|
[
"Create",
"an",
"instance",
"of",
"the",
"Analytics",
"Framework",
"Service",
"with",
"the",
"typical",
"starting",
"settings",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/analytics.py#L23-L47
|
PredixDev/predixpy
|
predix/admin/logstash.py
|
Logging._find_service_name
|
def _find_service_name(self):
"""
For cloud operations there is support for multiple pools of resources
dedicated to logstash. The service name as a result follows the
pattern logstash-{n} where n is some number. We can find it from the
service marketplace.
"""
space = predix.admin.cf.spaces.Space()
services = space.get_services()
for service in services:
if service.startswith('logstash'):
return service
return 'logstash-3'
|
python
|
def _find_service_name(self):
"""
For cloud operations there is support for multiple pools of resources
dedicated to logstash. The service name as a result follows the
pattern logstash-{n} where n is some number. We can find it from the
service marketplace.
"""
space = predix.admin.cf.spaces.Space()
services = space.get_services()
for service in services:
if service.startswith('logstash'):
return service
return 'logstash-3'
|
[
"def",
"_find_service_name",
"(",
"self",
")",
":",
"space",
"=",
"predix",
".",
"admin",
".",
"cf",
".",
"spaces",
".",
"Space",
"(",
")",
"services",
"=",
"space",
".",
"get_services",
"(",
")",
"for",
"service",
"in",
"services",
":",
"if",
"service",
".",
"startswith",
"(",
"'logstash'",
")",
":",
"return",
"service",
"return",
"'logstash-3'"
] |
For cloud operations there is support for multiple pools of resources
dedicated to logstash. The service name as a result follows the
pattern logstash-{n} where n is some number. We can find it from the
service marketplace.
|
[
"For",
"cloud",
"operations",
"there",
"is",
"support",
"for",
"multiple",
"pools",
"of",
"resources",
"dedicated",
"to",
"logstash",
".",
"The",
"service",
"name",
"as",
"a",
"result",
"follows",
"the",
"pattern",
"logstash",
"-",
"{",
"n",
"}",
"where",
"n",
"is",
"some",
"number",
".",
"We",
"can",
"find",
"it",
"from",
"the",
"service",
"marketplace",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/logstash.py#L27-L40
|
PredixDev/predixpy
|
predix/admin/logstash.py
|
Logging.add_to_manifest
|
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()
|
python
|
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()
|
[
"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.
|
[
"Add",
"to",
"the",
"manifest",
"to",
"make",
"sure",
"it",
"is",
"bound",
"to",
"the",
"application",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/logstash.py#L54-L60
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset._get_zone_id
|
def _get_zone_id(self):
"""
Returns the Predix Zone Id for the service that is a required
header in service calls.
"""
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_asset = services['predix-asset'][0]['credentials']
return predix_asset['zone']['http-header-value']
else:
return predix.config.get_env_value(self, 'zone_id')
|
python
|
def _get_zone_id(self):
"""
Returns the Predix Zone Id for the service that is a required
header in service calls.
"""
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_asset = services['predix-asset'][0]['credentials']
return predix_asset['zone']['http-header-value']
else:
return predix.config.get_env_value(self, 'zone_id')
|
[
"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.
|
[
"Returns",
"the",
"Predix",
"Zone",
"Id",
"for",
"the",
"service",
"that",
"is",
"a",
"required",
"header",
"in",
"service",
"calls",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L39-L49
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.get_collections
|
def get_collections(self):
"""
Returns a flat list of the names of collections in the asset
service.
..
['wind-turbines', 'jet-engines']
"""
collections = []
for result in self._get_collections():
collections.append(result['collection'])
return collections
|
python
|
def get_collections(self):
"""
Returns a flat list of the names of collections in the asset
service.
..
['wind-turbines', 'jet-engines']
"""
collections = []
for result in self._get_collections():
collections.append(result['collection'])
return collections
|
[
"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.
..
['wind-turbines', 'jet-engines']
|
[
"Returns",
"a",
"flat",
"list",
"of",
"the",
"names",
"of",
"collections",
"in",
"the",
"asset",
"service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L70-L84
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.get_collection
|
def get_collection(self, collection, filter=None, fields=None,
page_size=None):
"""
Returns a specific collection from the asset service with
the given collection endpoint.
Supports passing through parameters such as...
- filters such as "name=Vesuvius" following GEL spec
- fields such as "uri,description" comma delimited
- page_size such as "100" (the default)
"""
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)
|
python
|
def get_collection(self, collection, filter=None, fields=None,
page_size=None):
"""
Returns a specific collection from the asset service with
the given collection endpoint.
Supports passing through parameters such as...
- filters such as "name=Vesuvius" following GEL spec
- fields such as "uri,description" comma delimited
- page_size such as "100" (the default)
"""
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)
|
[
"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.
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",
"specific",
"collection",
"from",
"the",
"asset",
"service",
"with",
"the",
"given",
"collection",
"endpoint",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L86-L107
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.create_guid
|
def create_guid(self, collection=None):
"""
Returns a new guid for use in posting a new asset to a collection.
"""
guid = str(uuid.uuid4())
if collection:
return str.join('/', [collection, guid])
else:
return guid
|
python
|
def create_guid(self, collection=None):
"""
Returns a new guid for use in posting a new asset to a collection.
"""
guid = str(uuid.uuid4())
if collection:
return str.join('/', [collection, guid])
else:
return guid
|
[
"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.
|
[
"Returns",
"a",
"new",
"guid",
"for",
"use",
"in",
"posting",
"a",
"new",
"asset",
"to",
"a",
"collection",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L109-L117
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.post_collection
|
def post_collection(self, collection, body):
"""
Creates a new collection. This is mostly just transport layer
and passes collection and body along. It presumes the body
already has generated.
The collection is *not* expected to have the id.
"""
assert 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)
|
python
|
def post_collection(self, collection, body):
"""
Creates a new collection. This is mostly just transport layer
and passes collection and body along. It presumes the body
already has generated.
The collection is *not* expected to have the id.
"""
assert 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)
|
[
"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.
The collection is *not* expected to have the id.
|
[
"Creates",
"a",
"new",
"collection",
".",
"This",
"is",
"mostly",
"just",
"transport",
"layer",
"and",
"passes",
"collection",
"and",
"body",
"along",
".",
"It",
"presumes",
"the",
"body",
"already",
"has",
"generated",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L119-L130
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.put_collection
|
def put_collection(self, collection, body):
"""
Updates an existing collection.
The collection being updated *is* expected to include the id.
"""
uri = self.uri + '/v1' + collection
return self.service._put(uri, body)
|
python
|
def put_collection(self, collection, body):
"""
Updates an existing collection.
The collection being updated *is* expected to include the id.
"""
uri = self.uri + '/v1' + collection
return self.service._put(uri, body)
|
[
"def",
"put_collection",
"(",
"self",
",",
"collection",
",",
"body",
")",
":",
"uri",
"=",
"self",
".",
"uri",
"+",
"'/v1'",
"+",
"collection",
"return",
"self",
".",
"service",
".",
"_put",
"(",
"uri",
",",
"body",
")"
] |
Updates an existing collection.
The collection being updated *is* expected to include the id.
|
[
"Updates",
"an",
"existing",
"collection",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L132-L140
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.delete_collection
|
def delete_collection(self, collection):
"""
Deletes an existing collection.
The collection being updated *is* expected to include the id.
"""
uri = str.join('/', [self.uri, collection])
return self.service._delete(uri)
|
python
|
def delete_collection(self, collection):
"""
Deletes an existing collection.
The collection being updated *is* expected to include the id.
"""
uri = str.join('/', [self.uri, collection])
return self.service._delete(uri)
|
[
"def",
"delete_collection",
"(",
"self",
",",
"collection",
")",
":",
"uri",
"=",
"str",
".",
"join",
"(",
"'/'",
",",
"[",
"self",
".",
"uri",
",",
"collection",
"]",
")",
"return",
"self",
".",
"service",
".",
"_delete",
"(",
"uri",
")"
] |
Deletes an existing collection.
The collection being updated *is* expected to include the id.
|
[
"Deletes",
"an",
"existing",
"collection",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L142-L149
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.patch_collection
|
def patch_collection(self, collection, changes):
"""
Will make specific updates to a record based on JSON Patch
documentation.
https://tools.ietf.org/html/rfc6902
the format of changes is something like::
[{
'op': 'add',
'path': '/newfield',
'value': 'just added'
}]
"""
uri = str.join('/', [self.uri, collection])
return self.service._patch(uri, changes)
|
python
|
def patch_collection(self, collection, changes):
"""
Will make specific updates to a record based on JSON Patch
documentation.
https://tools.ietf.org/html/rfc6902
the format of changes is something like::
[{
'op': 'add',
'path': '/newfield',
'value': 'just added'
}]
"""
uri = str.join('/', [self.uri, collection])
return self.service._patch(uri, changes)
|
[
"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.
https://tools.ietf.org/html/rfc6902
the format of changes is something like::
[{
'op': 'add',
'path': '/newfield',
'value': 'just added'
}]
|
[
"Will",
"make",
"specific",
"updates",
"to",
"a",
"record",
"based",
"on",
"JSON",
"Patch",
"documentation",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L151-L168
|
PredixDev/predixpy
|
predix/data/asset.py
|
Asset.save
|
def save(self, collection):
"""
Save an asset collection to the service.
"""
assert isinstance(collection, predix.data.asset.AssetCollection), "Expected AssetCollection"
collection.validate()
self.put_collection(collection.uri, collection.__dict__)
|
python
|
def save(self, collection):
"""
Save an asset collection to the service.
"""
assert isinstance(collection, predix.data.asset.AssetCollection), "Expected AssetCollection"
collection.validate()
self.put_collection(collection.uri, collection.__dict__)
|
[
"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.
|
[
"Save",
"an",
"asset",
"collection",
"to",
"the",
"service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/data/asset.py#L212-L218
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_manifest_from_space
|
def create_manifest_from_space(self):
"""
Populate a manifest file generated from details from the
cloud foundry space environment.
"""
space = predix.admin.cf.spaces.Space()
summary = space.get_space_summary()
for instance in summary['services']:
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)
|
python
|
def create_manifest_from_space(self):
"""
Populate a manifest file generated from details from the
cloud foundry space environment.
"""
space = predix.admin.cf.spaces.Space()
summary = space.get_space_summary()
for instance in summary['services']:
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)
|
[
"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.
|
[
"Populate",
"a",
"manifest",
"file",
"generated",
"from",
"details",
"from",
"the",
"cloud",
"foundry",
"space",
"environment",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L40-L58
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.lock_to_org_space
|
def lock_to_org_space(self):
"""
Lock the manifest to the current organization and space regardless of
Cloud Foundry target.
"""
self.add_env_var('PREDIX_ORGANIZATION_GUID', self.space.org.guid)
self.add_env_var('PREDIX_ORGANIZATION_NAME', self.space.org.name)
self.add_env_var('PREDIX_SPACE_GUID', self.space.guid)
self.add_env_var('PREDIX_SPACE_NAME', self.space.name)
self.write_manifest()
|
python
|
def lock_to_org_space(self):
"""
Lock the manifest to the current organization and space regardless of
Cloud Foundry target.
"""
self.add_env_var('PREDIX_ORGANIZATION_GUID', self.space.org.guid)
self.add_env_var('PREDIX_ORGANIZATION_NAME', self.space.org.name)
self.add_env_var('PREDIX_SPACE_GUID', self.space.guid)
self.add_env_var('PREDIX_SPACE_NAME', self.space.name)
self.write_manifest()
|
[
"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.
|
[
"Lock",
"the",
"manifest",
"to",
"the",
"current",
"organization",
"and",
"space",
"regardless",
"of",
"Cloud",
"Foundry",
"target",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L60-L69
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_uaa
|
def create_uaa(self, admin_secret, **kwargs):
"""
Creates an instance of UAA Service.
:param admin_secret: The secret password for administering the service
such as adding clients and users.
"""
uaa = predix.admin.uaa.UserAccountAuthentication(**kwargs)
if not uaa.exists():
uaa.create(admin_secret, **kwargs)
uaa.add_to_manifest(self)
return uaa
|
python
|
def create_uaa(self, admin_secret, **kwargs):
"""
Creates an instance of UAA Service.
:param admin_secret: The secret password for administering the service
such as adding clients and users.
"""
uaa = predix.admin.uaa.UserAccountAuthentication(**kwargs)
if not uaa.exists():
uaa.create(admin_secret, **kwargs)
uaa.add_to_manifest(self)
return uaa
|
[
"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.
:param admin_secret: The secret password for administering the service
such as adding clients and users.
|
[
"Creates",
"an",
"instance",
"of",
"UAA",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L71-L83
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_client
|
def create_client(self, client_id=None, client_secret=None, uaa=None):
"""
Create a client and add it to the manifest.
:param client_id: The client id used to authenticate as a client
in UAA.
:param client_secret: The secret password used by a client to
authenticate and generate a UAA token.
:param uaa: The UAA to create client with
"""
if not uaa:
uaa = predix.admin.uaa.UserAccountAuthentication()
# Client id and secret can be generated if not provided as arguments
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)
|
python
|
def create_client(self, client_id=None, client_secret=None, uaa=None):
"""
Create a client and add it to the manifest.
:param client_id: The client id used to authenticate as a client
in UAA.
:param client_secret: The secret password used by a client to
authenticate and generate a UAA token.
:param uaa: The UAA to create client with
"""
if not uaa:
uaa = predix.admin.uaa.UserAccountAuthentication()
# Client id and secret can be generated if not provided as arguments
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)
|
[
"def",
"create_client",
"(",
"self",
",",
"client_id",
"=",
"None",
",",
"client_secret",
"=",
"None",
",",
"uaa",
"=",
"None",
")",
":",
"if",
"not",
"uaa",
":",
"uaa",
"=",
"predix",
".",
"admin",
".",
"uaa",
".",
"UserAccountAuthentication",
"(",
")",
"# Client id and secret can be generated if not provided as arguments",
"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.
:param client_id: The client id used to authenticate as a client
in UAA.
:param client_secret: The secret password used by a client to
authenticate and generate a UAA token.
:param uaa: The UAA to create client with
|
[
"Create",
"a",
"client",
"and",
"add",
"it",
"to",
"the",
"manifest",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L85-L109
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_timeseries
|
def create_timeseries(self, **kwargs):
"""
Creates an instance of the Time Series Service.
"""
ts = predix.admin.timeseries.TimeSeries(**kwargs)
ts.create()
client_id = self.get_client_id()
if client_id:
ts.grant_client(client_id)
ts.add_to_manifest(self)
return ts
|
python
|
def create_timeseries(self, **kwargs):
"""
Creates an instance of the Time Series Service.
"""
ts = predix.admin.timeseries.TimeSeries(**kwargs)
ts.create()
client_id = self.get_client_id()
if client_id:
ts.grant_client(client_id)
ts.add_to_manifest(self)
return ts
|
[
"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.
|
[
"Creates",
"an",
"instance",
"of",
"the",
"Time",
"Series",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L111-L123
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_asset
|
def create_asset(self, **kwargs):
"""
Creates an instance of the Asset Service.
"""
asset = predix.admin.asset.Asset(**kwargs)
asset.create()
client_id = self.get_client_id()
if client_id:
asset.grant_client(client_id)
asset.add_to_manifest(self)
return asset
|
python
|
def create_asset(self, **kwargs):
"""
Creates an instance of the Asset Service.
"""
asset = predix.admin.asset.Asset(**kwargs)
asset.create()
client_id = self.get_client_id()
if client_id:
asset.grant_client(client_id)
asset.add_to_manifest(self)
return asset
|
[
"def",
"create_asset",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"asset",
"=",
"predix",
".",
"admin",
".",
"asset",
".",
"Asset",
"(",
"*",
"*",
"kwargs",
")",
"asset",
".",
"create",
"(",
")",
"client_id",
"=",
"self",
".",
"get_client_id",
"(",
")",
"if",
"client_id",
":",
"asset",
".",
"grant_client",
"(",
"client_id",
")",
"asset",
".",
"add_to_manifest",
"(",
"self",
")",
"return",
"asset"
] |
Creates an instance of the Asset Service.
|
[
"Creates",
"an",
"instance",
"of",
"the",
"Asset",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L125-L137
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_acs
|
def create_acs(self, **kwargs):
"""
Creates an instance of the Asset Service.
"""
acs = predix.admin.acs.AccessControl(**kwargs)
acs.create()
client_id = self.get_client_id()
if client_id:
acs.grant_client(client_id)
acs.grant_client(client_id)
acs.add_to_manifest(self)
return acs
|
python
|
def create_acs(self, **kwargs):
"""
Creates an instance of the Asset Service.
"""
acs = predix.admin.acs.AccessControl(**kwargs)
acs.create()
client_id = self.get_client_id()
if client_id:
acs.grant_client(client_id)
acs.grant_client(client_id)
acs.add_to_manifest(self)
return acs
|
[
"def",
"create_acs",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"acs",
"=",
"predix",
".",
"admin",
".",
"acs",
".",
"AccessControl",
"(",
"*",
"*",
"kwargs",
")",
"acs",
".",
"create",
"(",
")",
"client_id",
"=",
"self",
".",
"get_client_id",
"(",
")",
"if",
"client_id",
":",
"acs",
".",
"grant_client",
"(",
"client_id",
")",
"acs",
".",
"grant_client",
"(",
"client_id",
")",
"acs",
".",
"add_to_manifest",
"(",
"self",
")",
"return",
"acs"
] |
Creates an instance of the Asset Service.
|
[
"Creates",
"an",
"instance",
"of",
"the",
"Asset",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L139-L152
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_weather
|
def create_weather(self, **kwargs):
"""
Creates an instance of the Asset Service.
"""
weather = predix.admin.weather.WeatherForecast(**kwargs)
weather.create()
client_id = self.get_client_id()
if client_id:
weather.grant_client(client_id)
weather.grant_client(client_id)
weather.add_to_manifest(self)
return weather
|
python
|
def create_weather(self, **kwargs):
"""
Creates an instance of the Asset Service.
"""
weather = predix.admin.weather.WeatherForecast(**kwargs)
weather.create()
client_id = self.get_client_id()
if client_id:
weather.grant_client(client_id)
weather.grant_client(client_id)
weather.add_to_manifest(self)
return weather
|
[
"def",
"create_weather",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"weather",
"=",
"predix",
".",
"admin",
".",
"weather",
".",
"WeatherForecast",
"(",
"*",
"*",
"kwargs",
")",
"weather",
".",
"create",
"(",
")",
"client_id",
"=",
"self",
".",
"get_client_id",
"(",
")",
"if",
"client_id",
":",
"weather",
".",
"grant_client",
"(",
"client_id",
")",
"weather",
".",
"grant_client",
"(",
"client_id",
")",
"weather",
".",
"add_to_manifest",
"(",
"self",
")",
"return",
"weather"
] |
Creates an instance of the Asset Service.
|
[
"Creates",
"an",
"instance",
"of",
"the",
"Asset",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L154-L167
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_blobstore
|
def create_blobstore(self, **kwargs):
"""
Creates an instance of the BlobStore Service.
"""
blobstore = predix.admin.blobstore.BlobStore(**kwargs)
blobstore.create()
blobstore.add_to_manifest(self)
return blobstore
|
python
|
def create_blobstore(self, **kwargs):
"""
Creates an instance of the BlobStore Service.
"""
blobstore = predix.admin.blobstore.BlobStore(**kwargs)
blobstore.create()
blobstore.add_to_manifest(self)
return blobstore
|
[
"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.
|
[
"Creates",
"an",
"instance",
"of",
"the",
"BlobStore",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L169-L177
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_logstash
|
def create_logstash(self, **kwargs):
"""
Creates an instance of the Logging Service.
"""
logstash = predix.admin.logstash.Logging(**kwargs)
logstash.create()
logstash.add_to_manifest(self)
logging.info('Install Kibana-Me-Logs application by following GitHub instructions')
logging.info('git clone https://github.com/cloudfoundry-community/kibana-me-logs.git')
return logstash
|
python
|
def create_logstash(self, **kwargs):
"""
Creates an instance of the Logging Service.
"""
logstash = predix.admin.logstash.Logging(**kwargs)
logstash.create()
logstash.add_to_manifest(self)
logging.info('Install Kibana-Me-Logs application by following GitHub instructions')
logging.info('git clone https://github.com/cloudfoundry-community/kibana-me-logs.git')
return logstash
|
[
"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.
|
[
"Creates",
"an",
"instance",
"of",
"the",
"Logging",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L179-L190
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_cache
|
def create_cache(self, **kwargs):
"""
Creates an instance of the Cache Service.
"""
cache = predix.admin.cache.Cache(**kwargs)
cache.create(**kwargs)
cache.add_to_manifest(self)
return cache
|
python
|
def create_cache(self, **kwargs):
"""
Creates an instance of the Cache Service.
"""
cache = predix.admin.cache.Cache(**kwargs)
cache.create(**kwargs)
cache.add_to_manifest(self)
return cache
|
[
"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.
|
[
"Creates",
"an",
"instance",
"of",
"the",
"Cache",
"Service",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L192-L199
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.create_eventhub
|
def create_eventhub(self, **kwargs):
"""
todo make it so the client can be customised to publish/subscribe
Creates an instance of eventhub service
"""
eventhub = predix.admin.eventhub.EventHub(**kwargs)
eventhub.create()
eventhub.add_to_manifest(self)
eventhub.grant_client(client_id=self.get_client_id(), **kwargs)
eventhub.add_to_manifest(self)
return eventhub
|
python
|
def create_eventhub(self, **kwargs):
"""
todo make it so the client can be customised to publish/subscribe
Creates an instance of eventhub service
"""
eventhub = predix.admin.eventhub.EventHub(**kwargs)
eventhub.create()
eventhub.add_to_manifest(self)
eventhub.grant_client(client_id=self.get_client_id(), **kwargs)
eventhub.add_to_manifest(self)
return eventhub
|
[
"def",
"create_eventhub",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"eventhub",
"=",
"predix",
".",
"admin",
".",
"eventhub",
".",
"EventHub",
"(",
"*",
"*",
"kwargs",
")",
"eventhub",
".",
"create",
"(",
")",
"eventhub",
".",
"add_to_manifest",
"(",
"self",
")",
"eventhub",
".",
"grant_client",
"(",
"client_id",
"=",
"self",
".",
"get_client_id",
"(",
")",
",",
"*",
"*",
"kwargs",
")",
"eventhub",
".",
"add_to_manifest",
"(",
"self",
")",
"return",
"eventhub"
] |
todo make it so the client can be customised to publish/subscribe
Creates an instance of eventhub service
|
[
"todo",
"make",
"it",
"so",
"the",
"client",
"can",
"be",
"customised",
"to",
"publish",
"/",
"subscribe",
"Creates",
"an",
"instance",
"of",
"eventhub",
"service"
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L209-L219
|
PredixDev/predixpy
|
predix/admin/app.py
|
Manifest.get_service_marketplace
|
def get_service_marketplace(self, available=True, unavailable=False,
deprecated=False):
"""
Returns a list of service names. Can return all services, just
those supported by PredixPy, or just those not yet supported by
PredixPy.
:param available: Return the services that are
available in PredixPy. (Defaults to True)
:param unavailable: Return the services that are not yet
supported by PredixPy. (Defaults to False)
:param deprecated: Return the services that are
supported by PredixPy but no longer available. (True)
"""
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)
|
python
|
def get_service_marketplace(self, available=True, unavailable=False,
deprecated=False):
"""
Returns a list of service names. Can return all services, just
those supported by PredixPy, or just those not yet supported by
PredixPy.
:param available: Return the services that are
available in PredixPy. (Defaults to True)
:param unavailable: Return the services that are not yet
supported by PredixPy. (Defaults to False)
:param deprecated: Return the services that are
supported by PredixPy but no longer available. (True)
"""
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)
|
[
"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.
:param available: Return the services that are
available in PredixPy. (Defaults to True)
:param unavailable: Return the services that are not yet
supported by PredixPy. (Defaults to False)
:param deprecated: Return the services that are
supported by PredixPy but no longer available. (True)
|
[
"Returns",
"a",
"list",
"of",
"service",
"names",
".",
"Can",
"return",
"all",
"services",
"just",
"those",
"supported",
"by",
"PredixPy",
"or",
"just",
"those",
"not",
"yet",
"supported",
"by",
"PredixPy",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/app.py#L222-L250
|
PredixDev/predixpy
|
predix/service.py
|
Service._auto_authenticate
|
def _auto_authenticate(self):
"""
If we are in an app context we can authenticate immediately.
"""
client_id = predix.config.get_env_value(predix.app.Manifest, 'client_id')
client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret')
if client_id and client_secret:
logging.info("Automatically authenticated as %s" % (client_id))
self.uaa.authenticate(client_id, client_secret)
|
python
|
def _auto_authenticate(self):
"""
If we are in an app context we can authenticate immediately.
"""
client_id = predix.config.get_env_value(predix.app.Manifest, 'client_id')
client_secret = predix.config.get_env_value(predix.app.Manifest, 'client_secret')
if client_id and client_secret:
logging.info("Automatically authenticated as %s" % (client_id))
self.uaa.authenticate(client_id, client_secret)
|
[
"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.
|
[
"If",
"we",
"are",
"in",
"an",
"app",
"context",
"we",
"can",
"authenticate",
"immediately",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/service.py#L29-L38
|
PredixDev/predixpy
|
predix/service.py
|
Service._get
|
def _get(self, uri, params=None, headers=None):
"""
Simple GET request for a given path.
"""
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.get(uri, 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()
|
python
|
def _get(self, uri, params=None, headers=None):
"""
Simple GET request for a given path.
"""
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.get(uri, 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()
|
[
"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.
|
[
"Simple",
"GET",
"request",
"for",
"a",
"given",
"path",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/service.py#L58-L74
|
PredixDev/predixpy
|
predix/service.py
|
Service._post
|
def _post(self, uri, data):
"""
Simple POST request for a given path.
"""
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("BODY=" + json.dumps(data))
response = self.session.post(uri, headers=headers,
data=json.dumps(data))
if response.status_code in [200, 204]:
try:
return response.json()
except ValueError:
return "{}"
else:
logging.error(response.content)
response.raise_for_status()
|
python
|
def _post(self, uri, data):
"""
Simple POST request for a given path.
"""
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("BODY=" + json.dumps(data))
response = self.session.post(uri, headers=headers,
data=json.dumps(data))
if response.status_code in [200, 204]:
try:
return response.json()
except ValueError:
return "{}"
else:
logging.error(response.content)
response.raise_for_status()
|
[
"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.
|
[
"Simple",
"POST",
"request",
"for",
"a",
"given",
"path",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/service.py#L76-L94
|
PredixDev/predixpy
|
predix/service.py
|
Service._put
|
def _put(self, uri, data):
"""
Simple PUT operation for a given path.
"""
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("BODY=" + json.dumps(data))
response = self.session.put(uri, headers=headers,
data=json.dumps(data))
if response.status_code in [201, 204]:
return data
else:
logging.error(response.content)
response.raise_for_status()
|
python
|
def _put(self, uri, data):
"""
Simple PUT operation for a given path.
"""
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("BODY=" + json.dumps(data))
response = self.session.put(uri, headers=headers,
data=json.dumps(data))
if response.status_code in [201, 204]:
return data
else:
logging.error(response.content)
response.raise_for_status()
|
[
"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.
|
[
"Simple",
"PUT",
"operation",
"for",
"a",
"given",
"path",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/service.py#L96-L111
|
PredixDev/predixpy
|
predix/service.py
|
Service._delete
|
def _delete(self, uri):
"""
Simple DELETE operation for a given path.
"""
headers = self._get_headers()
response = self.session.delete(uri, headers=headers)
# Will return a 204 on successful delete
if response.status_code == 204:
return response
else:
logging.error(response.content)
response.raise_for_status()
|
python
|
def _delete(self, uri):
"""
Simple DELETE operation for a given path.
"""
headers = self._get_headers()
response = self.session.delete(uri, headers=headers)
# Will return a 204 on successful delete
if response.status_code == 204:
return response
else:
logging.error(response.content)
response.raise_for_status()
|
[
"def",
"_delete",
"(",
"self",
",",
"uri",
")",
":",
"headers",
"=",
"self",
".",
"_get_headers",
"(",
")",
"response",
"=",
"self",
".",
"session",
".",
"delete",
"(",
"uri",
",",
"headers",
"=",
"headers",
")",
"# Will return a 204 on successful delete",
"if",
"response",
".",
"status_code",
"==",
"204",
":",
"return",
"response",
"else",
":",
"logging",
".",
"error",
"(",
"response",
".",
"content",
")",
"response",
".",
"raise_for_status",
"(",
")"
] |
Simple DELETE operation for a given path.
|
[
"Simple",
"DELETE",
"operation",
"for",
"a",
"given",
"path",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/service.py#L113-L126
|
PredixDev/predixpy
|
predix/service.py
|
Service._patch
|
def _patch(self, uri, data):
"""
Simple PATCH operation for a given path.
The body is expected to list operations to perform to update
the data. Operations include:
- add
- remove
- replace
- move
- copy
- test
[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
]
"""
headers = self._get_headers()
response = self.session.patch(uri, headers=headers,
data=json.dumps(data))
# Will return a 204 on successful patch
if response.status_code == 204:
return response
else:
logging.error(response.content)
response.raise_for_status()
|
python
|
def _patch(self, uri, data):
"""
Simple PATCH operation for a given path.
The body is expected to list operations to perform to update
the data. Operations include:
- add
- remove
- replace
- move
- copy
- test
[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
]
"""
headers = self._get_headers()
response = self.session.patch(uri, headers=headers,
data=json.dumps(data))
# Will return a 204 on successful patch
if response.status_code == 204:
return response
else:
logging.error(response.content)
response.raise_for_status()
|
[
"def",
"_patch",
"(",
"self",
",",
"uri",
",",
"data",
")",
":",
"headers",
"=",
"self",
".",
"_get_headers",
"(",
")",
"response",
"=",
"self",
".",
"session",
".",
"patch",
"(",
"uri",
",",
"headers",
"=",
"headers",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",
")",
"# Will return a 204 on successful patch",
"if",
"response",
".",
"status_code",
"==",
"204",
":",
"return",
"response",
"else",
":",
"logging",
".",
"error",
"(",
"response",
".",
"content",
")",
"response",
".",
"raise_for_status",
"(",
")"
] |
Simple PATCH operation for a given path.
The body is expected to list operations to perform to update
the data. Operations include:
- add
- remove
- replace
- move
- copy
- test
[
{ "op": "test", "path": "/a/b/c", "value": "foo" },
]
|
[
"Simple",
"PATCH",
"operation",
"for",
"a",
"given",
"path",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/service.py#L128-L154
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._get_resource_uri
|
def _get_resource_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the resource endpoint.
"""
uri = self.uri + '/v1/resource'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri
|
python
|
def _get_resource_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the resource endpoint.
"""
uri = self.uri + '/v1/resource'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri
|
[
"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.
|
[
"Returns",
"the",
"full",
"path",
"that",
"uniquely",
"identifies",
"the",
"resource",
"endpoint",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L64-L72
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.get_resource
|
def get_resource(self, resource_id):
"""
Returns a specific resource by resource id.
"""
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._get(uri)
|
python
|
def get_resource(self, resource_id):
"""
Returns a specific resource by resource id.
"""
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._get(uri)
|
[
"def",
"get_resource",
"(",
"self",
",",
"resource_id",
")",
":",
"# resource_id could be a path such as '/asset/123' so quote",
"uri",
"=",
"self",
".",
"_get_resource_uri",
"(",
"guid",
"=",
"resource_id",
")",
"return",
"self",
".",
"service",
".",
"_get",
"(",
"uri",
")"
] |
Returns a specific resource by resource id.
|
[
"Returns",
"a",
"specific",
"resource",
"by",
"resource",
"id",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L81-L87
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._post_resource
|
def _post_resource(self, body):
"""
Create new resources and associated attributes.
Example:
acs.post_resource([
{
"resourceIdentifier": "masaya",
"parents": [],
"attributes": [
{
"issuer": "default",
"name": "country",
"value": "Nicaragua"
}
],
}
])
The issuer is effectively a namespace, and in policy evaluations you
identify an attribute by a specific namespace. Many examples provide
a URL but it could be any arbitrary string.
The body is a list, so many resources can be added at the same time.
"""
assert isinstance(body, (list)), "POST for requires body to be a list"
uri = self._get_resource_uri()
return self.service._post(uri, body)
|
python
|
def _post_resource(self, body):
"""
Create new resources and associated attributes.
Example:
acs.post_resource([
{
"resourceIdentifier": "masaya",
"parents": [],
"attributes": [
{
"issuer": "default",
"name": "country",
"value": "Nicaragua"
}
],
}
])
The issuer is effectively a namespace, and in policy evaluations you
identify an attribute by a specific namespace. Many examples provide
a URL but it could be any arbitrary string.
The body is a list, so many resources can be added at the same time.
"""
assert isinstance(body, (list)), "POST for requires body to be a list"
uri = self._get_resource_uri()
return self.service._post(uri, body)
|
[
"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.
Example:
acs.post_resource([
{
"resourceIdentifier": "masaya",
"parents": [],
"attributes": [
{
"issuer": "default",
"name": "country",
"value": "Nicaragua"
}
],
}
])
The issuer is effectively a namespace, and in policy evaluations you
identify an attribute by a specific namespace. Many examples provide
a URL but it could be any arbitrary string.
The body is a list, so many resources can be added at the same time.
|
[
"Create",
"new",
"resources",
"and",
"associated",
"attributes",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L89-L117
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.delete_resource
|
def delete_resource(self, resource_id):
"""
Remove a specific resource by its identifier.
"""
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._delete(uri)
|
python
|
def delete_resource(self, resource_id):
"""
Remove a specific resource by its identifier.
"""
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._delete(uri)
|
[
"def",
"delete_resource",
"(",
"self",
",",
"resource_id",
")",
":",
"# resource_id could be a path such as '/asset/123' so quote",
"uri",
"=",
"self",
".",
"_get_resource_uri",
"(",
"guid",
"=",
"resource_id",
")",
"return",
"self",
".",
"service",
".",
"_delete",
"(",
"uri",
")"
] |
Remove a specific resource by its identifier.
|
[
"Remove",
"a",
"specific",
"resource",
"by",
"its",
"identifier",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L119-L125
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._put_resource
|
def _put_resource(self, resource_id, body):
"""
Update a resource for the given resource id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._put(uri, body)
|
python
|
def _put_resource(self, resource_id, body):
"""
Update a resource for the given resource id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
# resource_id could be a path such as '/asset/123' so quote
uri = self._get_resource_uri(guid=resource_id)
return self.service._put(uri, body)
|
[
"def",
"_put_resource",
"(",
"self",
",",
"resource_id",
",",
"body",
")",
":",
"assert",
"isinstance",
"(",
"body",
",",
"(",
"dict",
")",
")",
",",
"\"PUT requires body to be a dict.\"",
"# resource_id could be a path such as '/asset/123' so quote",
"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.
|
[
"Update",
"a",
"resource",
"for",
"the",
"given",
"resource",
"id",
".",
"The",
"body",
"is",
"not",
"a",
"list",
"but",
"a",
"dictionary",
"of",
"a",
"single",
"resource",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L127-L135
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.add_resource
|
def add_resource(self, resource_id, attributes, parents=[],
issuer='default'):
"""
Will add the given resource with a given identifier and attribute
dictionary.
example/
add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'})
"""
# MAINT: consider test to avoid adding duplicate resource id
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)
|
python
|
def add_resource(self, resource_id, attributes, parents=[],
issuer='default'):
"""
Will add the given resource with a given identifier and attribute
dictionary.
example/
add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'})
"""
# MAINT: consider test to avoid adding duplicate resource id
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)
|
[
"def",
"add_resource",
"(",
"self",
",",
"resource_id",
",",
"attributes",
",",
"parents",
"=",
"[",
"]",
",",
"issuer",
"=",
"'default'",
")",
":",
"# MAINT: consider test to avoid adding duplicate resource id",
"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.
example/
add_resource('/asset/12', {'id': 12, 'manufacturer': 'GE'})
|
[
"Will",
"add",
"the",
"given",
"resource",
"with",
"a",
"given",
"identifier",
"and",
"attribute",
"dictionary",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L137-L164
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._get_subject_uri
|
def _get_subject_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/subject'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri
|
python
|
def _get_subject_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/subject'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri
|
[
"def",
"_get_subject_uri",
"(",
"self",
",",
"guid",
"=",
"None",
")",
":",
"uri",
"=",
"self",
".",
"uri",
"+",
"'/v1/subject'",
"if",
"guid",
":",
"uri",
"+=",
"'/'",
"+",
"urllib",
".",
"quote_plus",
"(",
"guid",
")",
"return",
"uri"
] |
Returns the full path that uniquely identifies
the subject endpoint.
|
[
"Returns",
"the",
"full",
"path",
"that",
"uniquely",
"identifies",
"the",
"subject",
"endpoint",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L166-L174
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.get_subject
|
def get_subject(self, subject_id):
"""
Returns a specific subject by subject id.
"""
# subject_id could be a path such as '/user/j12y' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._get(uri)
|
python
|
def get_subject(self, subject_id):
"""
Returns a specific subject by subject id.
"""
# subject_id could be a path such as '/user/j12y' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._get(uri)
|
[
"def",
"get_subject",
"(",
"self",
",",
"subject_id",
")",
":",
"# subject_id could be a path such as '/user/j12y' so quote",
"uri",
"=",
"self",
".",
"_get_subject_uri",
"(",
"guid",
"=",
"subject_id",
")",
"return",
"self",
".",
"service",
".",
"_get",
"(",
"uri",
")"
] |
Returns a specific subject by subject id.
|
[
"Returns",
"a",
"specific",
"subject",
"by",
"subject",
"id",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L183-L189
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._post_subject
|
def _post_subject(self, body):
"""
Create new subjects and associated attributes.
Example:
acs.post_subject([
{
"subjectIdentifier": "/role/evangelist",
"parents": [],
"attributes": [
{
"issuer": "default",
"name": "role",
"value": "developer evangelist",
}
]
}
])
The issuer is effectively a namespace, and in policy evaluations
you identify an attribute by a specific namespace. Many examples
provide a URL but it could be any arbitrary string.
The body is a list, so many subjects can be added at the same time.
"""
assert isinstance(body, (list)), "POST requires body to be a list"
uri = self._get_subject_uri()
return self.service._post(uri, body)
|
python
|
def _post_subject(self, body):
"""
Create new subjects and associated attributes.
Example:
acs.post_subject([
{
"subjectIdentifier": "/role/evangelist",
"parents": [],
"attributes": [
{
"issuer": "default",
"name": "role",
"value": "developer evangelist",
}
]
}
])
The issuer is effectively a namespace, and in policy evaluations
you identify an attribute by a specific namespace. Many examples
provide a URL but it could be any arbitrary string.
The body is a list, so many subjects can be added at the same time.
"""
assert isinstance(body, (list)), "POST requires body to be a list"
uri = self._get_subject_uri()
return self.service._post(uri, body)
|
[
"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.
Example:
acs.post_subject([
{
"subjectIdentifier": "/role/evangelist",
"parents": [],
"attributes": [
{
"issuer": "default",
"name": "role",
"value": "developer evangelist",
}
]
}
])
The issuer is effectively a namespace, and in policy evaluations
you identify an attribute by a specific namespace. Many examples
provide a URL but it could be any arbitrary string.
The body is a list, so many subjects can be added at the same time.
|
[
"Create",
"new",
"subjects",
"and",
"associated",
"attributes",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L191-L220
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.delete_subject
|
def delete_subject(self, subject_id):
"""
Remove a specific subject by its identifier.
"""
# subject_id could be a path such as '/role/analyst' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._delete(uri)
|
python
|
def delete_subject(self, subject_id):
"""
Remove a specific subject by its identifier.
"""
# subject_id could be a path such as '/role/analyst' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._delete(uri)
|
[
"def",
"delete_subject",
"(",
"self",
",",
"subject_id",
")",
":",
"# subject_id could be a path such as '/role/analyst' so quote",
"uri",
"=",
"self",
".",
"_get_subject_uri",
"(",
"guid",
"=",
"subject_id",
")",
"return",
"self",
".",
"service",
".",
"_delete",
"(",
"uri",
")"
] |
Remove a specific subject by its identifier.
|
[
"Remove",
"a",
"specific",
"subject",
"by",
"its",
"identifier",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L222-L228
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._put_subject
|
def _put_subject(self, subject_id, body):
"""
Update a subject for the given subject id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, (dict)), "PUT requires body to be dict."
# subject_id could be a path such as '/asset/123' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._put(uri, body)
|
python
|
def _put_subject(self, subject_id, body):
"""
Update a subject for the given subject id. The body is not
a list but a dictionary of a single resource.
"""
assert isinstance(body, (dict)), "PUT requires body to be dict."
# subject_id could be a path such as '/asset/123' so quote
uri = self._get_subject_uri(guid=subject_id)
return self.service._put(uri, body)
|
[
"def",
"_put_subject",
"(",
"self",
",",
"subject_id",
",",
"body",
")",
":",
"assert",
"isinstance",
"(",
"body",
",",
"(",
"dict",
")",
")",
",",
"\"PUT requires body to be dict.\"",
"# subject_id could be a path such as '/asset/123' so quote",
"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.
|
[
"Update",
"a",
"subject",
"for",
"the",
"given",
"subject",
"id",
".",
"The",
"body",
"is",
"not",
"a",
"list",
"but",
"a",
"dictionary",
"of",
"a",
"single",
"resource",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L230-L239
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.add_subject
|
def add_subject(self, subject_id, attributes, parents=[],
issuer='default'):
"""
Will add the given subject with a given identifier and attribute
dictionary.
example/
add_subject('/user/j12y', {'username': 'j12y'})
"""
# MAINT: consider test to avoid adding duplicate subject id
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)
|
python
|
def add_subject(self, subject_id, attributes, parents=[],
issuer='default'):
"""
Will add the given subject with a given identifier and attribute
dictionary.
example/
add_subject('/user/j12y', {'username': 'j12y'})
"""
# MAINT: consider test to avoid adding duplicate subject id
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)
|
[
"def",
"add_subject",
"(",
"self",
",",
"subject_id",
",",
"attributes",
",",
"parents",
"=",
"[",
"]",
",",
"issuer",
"=",
"'default'",
")",
":",
"# MAINT: consider test to avoid adding duplicate subject id",
"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.
example/
add_subject('/user/j12y', {'username': 'j12y'})
|
[
"Will",
"add",
"the",
"given",
"subject",
"with",
"a",
"given",
"identifier",
"and",
"attribute",
"dictionary",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L241-L268
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._get_monitoring_heartbeat
|
def _get_monitoring_heartbeat(self):
"""
Tests whether or not the ACS service being monitored is alive.
"""
target = self.uri + '/monitoring/heartbeat'
response = self.session.get(target)
return response
|
python
|
def _get_monitoring_heartbeat(self):
"""
Tests whether or not the ACS service being monitored is alive.
"""
target = self.uri + '/monitoring/heartbeat'
response = self.session.get(target)
return response
|
[
"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.
|
[
"Tests",
"whether",
"or",
"not",
"the",
"ACS",
"service",
"being",
"monitored",
"is",
"alive",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L270-L276
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.is_alive
|
def is_alive(self):
"""
Will test whether the ACS service is up and alive.
"""
response = self.get_monitoring_heartbeat()
if response.status_code == 200 and response.content == 'alive':
return True
return False
|
python
|
def is_alive(self):
"""
Will test whether the ACS service is up and alive.
"""
response = self.get_monitoring_heartbeat()
if response.status_code == 200 and response.content == 'alive':
return True
return False
|
[
"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.
|
[
"Will",
"test",
"whether",
"the",
"ACS",
"service",
"is",
"up",
"and",
"alive",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L278-L286
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._get_policy_set_uri
|
def _get_policy_set_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/policy-set'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri
|
python
|
def _get_policy_set_uri(self, guid=None):
"""
Returns the full path that uniquely identifies
the subject endpoint.
"""
uri = self.uri + '/v1/policy-set'
if guid:
uri += '/' + urllib.quote_plus(guid)
return uri
|
[
"def",
"_get_policy_set_uri",
"(",
"self",
",",
"guid",
"=",
"None",
")",
":",
"uri",
"=",
"self",
".",
"uri",
"+",
"'/v1/policy-set'",
"if",
"guid",
":",
"uri",
"+=",
"'/'",
"+",
"urllib",
".",
"quote_plus",
"(",
"guid",
")",
"return",
"uri"
] |
Returns the full path that uniquely identifies
the subject endpoint.
|
[
"Returns",
"the",
"full",
"path",
"that",
"uniquely",
"identifies",
"the",
"subject",
"endpoint",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L288-L296
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._put_policy_set
|
def _put_policy_set(self, policy_set_id, body):
"""
Will create or update a policy set for the given path.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._put(uri, body)
|
python
|
def _put_policy_set(self, policy_set_id, body):
"""
Will create or update a policy set for the given path.
"""
assert isinstance(body, (dict)), "PUT requires body to be a dict."
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._put(uri, body)
|
[
"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.
|
[
"Will",
"create",
"or",
"update",
"a",
"policy",
"set",
"for",
"the",
"given",
"path",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L305-L311
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl._get_policy_set
|
def _get_policy_set(self, policy_set_id):
"""
Get a specific policy set by id.
"""
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._get(uri)
|
python
|
def _get_policy_set(self, policy_set_id):
"""
Get a specific policy set by id.
"""
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._get(uri)
|
[
"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.
|
[
"Get",
"a",
"specific",
"policy",
"set",
"by",
"id",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L313-L318
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.delete_policy_set
|
def delete_policy_set(self, policy_set_id):
"""
Delete a specific policy set by id. Method is idempotent.
"""
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._delete(uri)
|
python
|
def delete_policy_set(self, policy_set_id):
"""
Delete a specific policy set by id. Method is idempotent.
"""
uri = self._get_policy_set_uri(guid=policy_set_id)
return self.service._delete(uri)
|
[
"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.
|
[
"Delete",
"a",
"specific",
"policy",
"set",
"by",
"id",
".",
"Method",
"is",
"idempotent",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L320-L325
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.add_policy
|
def add_policy(self, name, action, resource, subject, condition,
policy_set_id=None, effect='PERMIT'):
"""
Will create a new policy set to enforce the given policy details.
The name is just a helpful descriptor for the policy.
The action maps to a HTTP verb.
Policies are evaluated against resources and subjects. They are
identified by matching a uriTemplate or attributes.
Examples::
resource = {
"uriTemplate": "/asset/{id}"
}
subject: {
"attributes": [{
"issuer": "default",
"name": "role"
}]
}
The condition is expected to be a string that defines a groovy
operation that can be evaluated.
Examples::
condition = "match.single(subject.attributes('default', 'role'),
'admin')
"""
# If not given a policy set id will generate one
if not policy_set_id:
policy_set_id = str(uuid.uuid4())
# Only a few operations / actions are supported in policy definitions
if action not in ['GET', 'PUT', 'POST', 'DELETE']:
raise ValueError("Invalid action")
# Defines a single policy to be part of the policy set.
policy = {
"name": name,
"target": {
"resource": resource,
"subject": subject,
"action": action,
},
"conditions": [{
"name": "",
"condition": condition,
}],
"effect": effect,
}
# Body of the request is a list of policies
body = {
"name": policy_set_id,
"policies": [policy],
}
result = self._put_policy_set(policy_set_id, body)
return result
|
python
|
def add_policy(self, name, action, resource, subject, condition,
policy_set_id=None, effect='PERMIT'):
"""
Will create a new policy set to enforce the given policy details.
The name is just a helpful descriptor for the policy.
The action maps to a HTTP verb.
Policies are evaluated against resources and subjects. They are
identified by matching a uriTemplate or attributes.
Examples::
resource = {
"uriTemplate": "/asset/{id}"
}
subject: {
"attributes": [{
"issuer": "default",
"name": "role"
}]
}
The condition is expected to be a string that defines a groovy
operation that can be evaluated.
Examples::
condition = "match.single(subject.attributes('default', 'role'),
'admin')
"""
# If not given a policy set id will generate one
if not policy_set_id:
policy_set_id = str(uuid.uuid4())
# Only a few operations / actions are supported in policy definitions
if action not in ['GET', 'PUT', 'POST', 'DELETE']:
raise ValueError("Invalid action")
# Defines a single policy to be part of the policy set.
policy = {
"name": name,
"target": {
"resource": resource,
"subject": subject,
"action": action,
},
"conditions": [{
"name": "",
"condition": condition,
}],
"effect": effect,
}
# Body of the request is a list of policies
body = {
"name": policy_set_id,
"policies": [policy],
}
result = self._put_policy_set(policy_set_id, body)
return result
|
[
"def",
"add_policy",
"(",
"self",
",",
"name",
",",
"action",
",",
"resource",
",",
"subject",
",",
"condition",
",",
"policy_set_id",
"=",
"None",
",",
"effect",
"=",
"'PERMIT'",
")",
":",
"# If not given a policy set id will generate one",
"if",
"not",
"policy_set_id",
":",
"policy_set_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"# Only a few operations / actions are supported in policy definitions",
"if",
"action",
"not",
"in",
"[",
"'GET'",
",",
"'PUT'",
",",
"'POST'",
",",
"'DELETE'",
"]",
":",
"raise",
"ValueError",
"(",
"\"Invalid action\"",
")",
"# Defines a single policy to be part of the policy set.",
"policy",
"=",
"{",
"\"name\"",
":",
"name",
",",
"\"target\"",
":",
"{",
"\"resource\"",
":",
"resource",
",",
"\"subject\"",
":",
"subject",
",",
"\"action\"",
":",
"action",
",",
"}",
",",
"\"conditions\"",
":",
"[",
"{",
"\"name\"",
":",
"\"\"",
",",
"\"condition\"",
":",
"condition",
",",
"}",
"]",
",",
"\"effect\"",
":",
"effect",
",",
"}",
"# Body of the request is a list of policies",
"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.
The name is just a helpful descriptor for the policy.
The action maps to a HTTP verb.
Policies are evaluated against resources and subjects. They are
identified by matching a uriTemplate or attributes.
Examples::
resource = {
"uriTemplate": "/asset/{id}"
}
subject: {
"attributes": [{
"issuer": "default",
"name": "role"
}]
}
The condition is expected to be a string that defines a groovy
operation that can be evaluated.
Examples::
condition = "match.single(subject.attributes('default', 'role'),
'admin')
|
[
"Will",
"create",
"a",
"new",
"policy",
"set",
"to",
"enforce",
"the",
"given",
"policy",
"details",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L327-L391
|
PredixDev/predixpy
|
predix/security/acs.py
|
AccessControl.is_allowed
|
def is_allowed(self, subject_id, action, resource_id, policy_sets=[]):
"""
Evaluate a policy-set against a subject and resource.
example/
is_allowed('/user/j12y', 'GET', '/asset/12')
"""
body = {
"action": action,
"subjectIdentifier": subject_id,
"resourceIdentifier": resource_id,
}
if policy_sets:
body['policySetsEvaluationOrder'] = policy_sets
# Will return a 200 with decision
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
|
python
|
def is_allowed(self, subject_id, action, resource_id, policy_sets=[]):
"""
Evaluate a policy-set against a subject and resource.
example/
is_allowed('/user/j12y', 'GET', '/asset/12')
"""
body = {
"action": action,
"subjectIdentifier": subject_id,
"resourceIdentifier": resource_id,
}
if policy_sets:
body['policySetsEvaluationOrder'] = policy_sets
# Will return a 200 with decision
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
|
[
"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",
"# Will return a 200 with decision",
"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.
example/
is_allowed('/user/j12y', 'GET', '/asset/12')
|
[
"Evaluate",
"a",
"policy",
"-",
"set",
"against",
"a",
"subject",
"and",
"resource",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/acs.py#L393-L423
|
shichao-an/homura
|
homura.py
|
download
|
def download(url, path=None, headers=None, session=None, show_progress=True,
resume=True, auto_retry=True, max_rst_retries=5,
pass_through_opts=None, cainfo=None, user_agent=None, auth=None):
"""Main download function"""
hm = Homura(url, path, headers, session, show_progress, resume,
auto_retry, max_rst_retries, pass_through_opts, cainfo,
user_agent, auth)
hm.start()
|
python
|
def download(url, path=None, headers=None, session=None, show_progress=True,
resume=True, auto_retry=True, max_rst_retries=5,
pass_through_opts=None, cainfo=None, user_agent=None, auth=None):
"""Main download function"""
hm = Homura(url, path, headers, session, show_progress, resume,
auto_retry, max_rst_retries, pass_through_opts, cainfo,
user_agent, auth)
hm.start()
|
[
"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
|
[
"Main",
"download",
"function"
] |
train
|
https://github.com/shichao-an/homura/blob/87d1b698e1196963a23fc1c615c12020daf77dcc/homura.py#L304-L311
|
shichao-an/homura
|
homura.py
|
Homura._fill_in_cainfo
|
def _fill_in_cainfo(self):
"""Fill in the path of the PEM file containing the CA certificate.
The priority is: 1. user provided path, 2. path to the cacert.pem
bundle provided by certifi (if installed), 3. let pycurl use the
system path where libcurl's cacert bundle is assumed to be stored,
as established at libcurl build time.
"""
if self.cainfo:
cainfo = self.cainfo
else:
try:
cainfo = certifi.where()
except AttributeError:
cainfo = None
if cainfo:
self._pycurl.setopt(pycurl.CAINFO, cainfo)
|
python
|
def _fill_in_cainfo(self):
"""Fill in the path of the PEM file containing the CA certificate.
The priority is: 1. user provided path, 2. path to the cacert.pem
bundle provided by certifi (if installed), 3. let pycurl use the
system path where libcurl's cacert bundle is assumed to be stored,
as established at libcurl build time.
"""
if self.cainfo:
cainfo = self.cainfo
else:
try:
cainfo = certifi.where()
except AttributeError:
cainfo = None
if cainfo:
self._pycurl.setopt(pycurl.CAINFO, cainfo)
|
[
"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.
The priority is: 1. user provided path, 2. path to the cacert.pem
bundle provided by certifi (if installed), 3. let pycurl use the
system path where libcurl's cacert bundle is assumed to be stored,
as established at libcurl build time.
|
[
"Fill",
"in",
"the",
"path",
"of",
"the",
"PEM",
"file",
"containing",
"the",
"CA",
"certificate",
"."
] |
train
|
https://github.com/shichao-an/homura/blob/87d1b698e1196963a23fc1c615c12020daf77dcc/homura.py#L159-L175
|
shichao-an/homura
|
homura.py
|
Homura.curl
|
def curl(self):
"""Sending a single cURL request to download"""
c = self._pycurl
# Resume download
if os.path.exists(self.path) and self.resume:
mode = 'ab'
self.downloaded = os.path.getsize(self.path)
c.setopt(pycurl.RESUME_FROM, self.downloaded)
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()
|
python
|
def curl(self):
"""Sending a single cURL request to download"""
c = self._pycurl
# Resume download
if os.path.exists(self.path) and self.resume:
mode = 'ab'
self.downloaded = os.path.getsize(self.path)
c.setopt(pycurl.RESUME_FROM, self.downloaded)
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()
|
[
"def",
"curl",
"(",
"self",
")",
":",
"c",
"=",
"self",
".",
"_pycurl",
"# Resume download",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
"and",
"self",
".",
"resume",
":",
"mode",
"=",
"'ab'",
"self",
".",
"downloaded",
"=",
"os",
".",
"path",
".",
"getsize",
"(",
"self",
".",
"path",
")",
"c",
".",
"setopt",
"(",
"pycurl",
".",
"RESUME_FROM",
",",
"self",
".",
"downloaded",
")",
"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
|
[
"Sending",
"a",
"single",
"cURL",
"request",
"to",
"download"
] |
train
|
https://github.com/shichao-an/homura/blob/87d1b698e1196963a23fc1c615c12020daf77dcc/homura.py#L177-L203
|
shichao-an/homura
|
homura.py
|
Homura.start
|
def start(self):
"""
Start downloading, handling auto retry, download resume and path
moving
"""
if not self.auto_retry:
self.curl()
return
while not self.is_finished:
try:
self.curl()
except pycurl.error as e:
# transfer closed with n bytes remaining to read
if e.args[0] == pycurl.E_PARTIAL_FILE:
pass
# HTTP server doesn't seem to support byte ranges.
# Cannot resume.
elif e.args[0] == pycurl.E_HTTP_RANGE_ERROR:
break
# Recv failure: Connection reset by peer
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()
|
python
|
def start(self):
"""
Start downloading, handling auto retry, download resume and path
moving
"""
if not self.auto_retry:
self.curl()
return
while not self.is_finished:
try:
self.curl()
except pycurl.error as e:
# transfer closed with n bytes remaining to read
if e.args[0] == pycurl.E_PARTIAL_FILE:
pass
# HTTP server doesn't seem to support byte ranges.
# Cannot resume.
elif e.args[0] == pycurl.E_HTTP_RANGE_ERROR:
break
# Recv failure: Connection reset by peer
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()
|
[
"def",
"start",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"auto_retry",
":",
"self",
".",
"curl",
"(",
")",
"return",
"while",
"not",
"self",
".",
"is_finished",
":",
"try",
":",
"self",
".",
"curl",
"(",
")",
"except",
"pycurl",
".",
"error",
"as",
"e",
":",
"# transfer closed with n bytes remaining to read",
"if",
"e",
".",
"args",
"[",
"0",
"]",
"==",
"pycurl",
".",
"E_PARTIAL_FILE",
":",
"pass",
"# HTTP server doesn't seem to support byte ranges.",
"# Cannot resume.",
"elif",
"e",
".",
"args",
"[",
"0",
"]",
"==",
"pycurl",
".",
"E_HTTP_RANGE_ERROR",
":",
"break",
"# Recv failure: Connection reset by peer",
"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
|
[
"Start",
"downloading",
"handling",
"auto",
"retry",
"download",
"resume",
"and",
"path",
"moving"
] |
train
|
https://github.com/shichao-an/homura/blob/87d1b698e1196963a23fc1c615c12020daf77dcc/homura.py#L205-L234
|
shichao-an/homura
|
homura.py
|
Homura._move_path
|
def _move_path(self):
"""
Move the downloaded file to the authentic path (identified by
effective URL)
"""
if is_temp_path(self._path) and self._pycurl is not None:
eurl = self._pycurl.getinfo(pycurl.EFFECTIVE_URL)
er = get_resource_name(eurl)
r = get_resource_name(self.url)
if er != r and os.path.exists(self.path):
new_path = self._get_path(self._path, eurl)
shutil.move(self.path, new_path)
self.path = new_path
|
python
|
def _move_path(self):
"""
Move the downloaded file to the authentic path (identified by
effective URL)
"""
if is_temp_path(self._path) and self._pycurl is not None:
eurl = self._pycurl.getinfo(pycurl.EFFECTIVE_URL)
er = get_resource_name(eurl)
r = get_resource_name(self.url)
if er != r and os.path.exists(self.path):
new_path = self._get_path(self._path, eurl)
shutil.move(self.path, new_path)
self.path = new_path
|
[
"def",
"_move_path",
"(",
"self",
")",
":",
"if",
"is_temp_path",
"(",
"self",
".",
"_path",
")",
"and",
"self",
".",
"_pycurl",
"is",
"not",
"None",
":",
"eurl",
"=",
"self",
".",
"_pycurl",
".",
"getinfo",
"(",
"pycurl",
".",
"EFFECTIVE_URL",
")",
"er",
"=",
"get_resource_name",
"(",
"eurl",
")",
"r",
"=",
"get_resource_name",
"(",
"self",
".",
"url",
")",
"if",
"er",
"!=",
"r",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"new_path",
"=",
"self",
".",
"_get_path",
"(",
"self",
".",
"_path",
",",
"eurl",
")",
"shutil",
".",
"move",
"(",
"self",
".",
"path",
",",
"new_path",
")",
"self",
".",
"path",
"=",
"new_path"
] |
Move the downloaded file to the authentic path (identified by
effective URL)
|
[
"Move",
"the",
"downloaded",
"file",
"to",
"the",
"authentic",
"path",
"(",
"identified",
"by",
"effective",
"URL",
")"
] |
train
|
https://github.com/shichao-an/homura/blob/87d1b698e1196963a23fc1c615c12020daf77dcc/homura.py#L289-L301
|
PredixDev/predixpy
|
predix/admin/uaa.py
|
UserAccountAuthentication.create
|
def create(self, secret, **kwargs):
"""
Create a new instance of the UAA service. Requires a
secret password for the 'admin' user account.
"""
parameters = {"adminClientSecret": secret}
self.service.create(parameters=parameters)
# Store URI into environment variable
predix.config.set_env_value(self.use_class, 'uri', self._get_uri())
# Once we create it login
self.authenticate()
|
python
|
def create(self, secret, **kwargs):
"""
Create a new instance of the UAA service. Requires a
secret password for the 'admin' user account.
"""
parameters = {"adminClientSecret": secret}
self.service.create(parameters=parameters)
# Store URI into environment variable
predix.config.set_env_value(self.use_class, 'uri', self._get_uri())
# Once we create it login
self.authenticate()
|
[
"def",
"create",
"(",
"self",
",",
"secret",
",",
"*",
"*",
"kwargs",
")",
":",
"parameters",
"=",
"{",
"\"adminClientSecret\"",
":",
"secret",
"}",
"self",
".",
"service",
".",
"create",
"(",
"parameters",
"=",
"parameters",
")",
"# Store URI into environment variable",
"predix",
".",
"config",
".",
"set_env_value",
"(",
"self",
".",
"use_class",
",",
"'uri'",
",",
"self",
".",
"_get_uri",
"(",
")",
")",
"# Once we create it login",
"self",
".",
"authenticate",
"(",
")"
] |
Create a new instance of the UAA service. Requires a
secret password for the 'admin' user account.
|
[
"Create",
"a",
"new",
"instance",
"of",
"the",
"UAA",
"service",
".",
"Requires",
"a",
"secret",
"password",
"for",
"the",
"admin",
"user",
"account",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/uaa.py#L53-L65
|
PredixDev/predixpy
|
predix/admin/uaa.py
|
UserAccountAuthentication.add_to_manifest
|
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.add_service(self.service.name)
# Add environment variable to manifest
varname = predix.config.set_env_value(self.use_class, 'uri',
self._get_uri())
manifest.add_env_var(varname, self._get_uri())
manifest.write_manifest()
|
python
|
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.add_service(self.service.name)
# Add environment variable to manifest
varname = predix.config.set_env_value(self.use_class, 'uri',
self._get_uri())
manifest.add_env_var(varname, self._get_uri())
manifest.write_manifest()
|
[
"def",
"add_to_manifest",
"(",
"self",
",",
"manifest",
")",
":",
"# Add this service to list of services",
"manifest",
".",
"add_service",
"(",
"self",
".",
"service",
".",
"name",
")",
"# Add environment variable to manifest",
"varname",
"=",
"predix",
".",
"config",
".",
"set_env_value",
"(",
"self",
".",
"use_class",
",",
"'uri'",
",",
"self",
".",
"_get_uri",
"(",
")",
")",
"manifest",
".",
"add_env_var",
"(",
"varname",
",",
"self",
".",
"_get_uri",
"(",
")",
")",
"manifest",
".",
"write_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",
"useful",
"details",
"to",
"the",
"manifest",
"about",
"this",
"service",
"so",
"that",
"it",
"can",
"be",
"used",
"in",
"an",
"application",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/uaa.py#L67-L84
|
PredixDev/predixpy
|
predix/admin/uaa.py
|
UserAccountAuthentication.authenticate
|
def authenticate(self):
"""
Authenticate into the UAA instance as the admin user.
"""
# Make sure we've stored uri for use
predix.config.set_env_value(self.use_class, 'uri', self._get_uri())
self.uaac = predix.security.uaa.UserAccountAuthentication()
self.uaac.authenticate('admin', self._get_admin_secret(),
use_cache=False)
self.is_admin = True
|
python
|
def authenticate(self):
"""
Authenticate into the UAA instance as the admin user.
"""
# Make sure we've stored uri for use
predix.config.set_env_value(self.use_class, 'uri', self._get_uri())
self.uaac = predix.security.uaa.UserAccountAuthentication()
self.uaac.authenticate('admin', self._get_admin_secret(),
use_cache=False)
self.is_admin = True
|
[
"def",
"authenticate",
"(",
"self",
")",
":",
"# Make sure we've stored uri for use",
"predix",
".",
"config",
".",
"set_env_value",
"(",
"self",
".",
"use_class",
",",
"'uri'",
",",
"self",
".",
"_get_uri",
"(",
")",
")",
"self",
".",
"uaac",
"=",
"predix",
".",
"security",
".",
"uaa",
".",
"UserAccountAuthentication",
"(",
")",
"self",
".",
"uaac",
".",
"authenticate",
"(",
"'admin'",
",",
"self",
".",
"_get_admin_secret",
"(",
")",
",",
"use_cache",
"=",
"False",
")",
"self",
".",
"is_admin",
"=",
"True"
] |
Authenticate into the UAA instance as the admin user.
|
[
"Authenticate",
"into",
"the",
"UAA",
"instance",
"as",
"the",
"admin",
"user",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/uaa.py#L86-L96
|
PredixDev/predixpy
|
predix/admin/uaa.py
|
UserAccountAuthentication._create_secret
|
def _create_secret(self, length=12):
"""
Use a cryptograhically-secure Pseudorandom number generator for picking
a combination of letters, digits, and punctuation to be our secret.
:param length: how long to make the secret (12 seems ok most of the time)
"""
# Charset will have 64 +- characters
charset = string.digits + string.ascii_letters + '+-'
return "".join(random.SystemRandom().choice(charset) for _ in
range(length))
|
python
|
def _create_secret(self, length=12):
"""
Use a cryptograhically-secure Pseudorandom number generator for picking
a combination of letters, digits, and punctuation to be our secret.
:param length: how long to make the secret (12 seems ok most of the time)
"""
# Charset will have 64 +- characters
charset = string.digits + string.ascii_letters + '+-'
return "".join(random.SystemRandom().choice(charset) for _ in
range(length))
|
[
"def",
"_create_secret",
"(",
"self",
",",
"length",
"=",
"12",
")",
":",
"# Charset will have 64 +- characters",
"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.
:param length: how long to make the secret (12 seems ok most of the time)
|
[
"Use",
"a",
"cryptograhically",
"-",
"secure",
"Pseudorandom",
"number",
"generator",
"for",
"picking",
"a",
"combination",
"of",
"letters",
"digits",
"and",
"punctuation",
"to",
"be",
"our",
"secret",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/uaa.py#L104-L115
|
PredixDev/predixpy
|
predix/admin/uaa.py
|
UserAccountAuthentication.create_client
|
def create_client(self, client_id, client_secret):
"""
Create a new client for use by applications.
"""
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.create_client(client_id, client_secret)
|
python
|
def create_client(self, client_id, client_secret):
"""
Create a new client for use by applications.
"""
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.create_client(client_id, client_secret)
|
[
"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.
|
[
"Create",
"a",
"new",
"client",
"for",
"use",
"by",
"applications",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/uaa.py#L117-L122
|
PredixDev/predixpy
|
predix/admin/uaa.py
|
UserAccountAuthentication.add_client_to_manifest
|
def add_client_to_manifest(self, client_id, client_secret, manifest):
"""
Add the client credentials to the specified manifest.
"""
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.add_client_to_manifest(client_id, client_secret,
manifest)
|
python
|
def add_client_to_manifest(self, client_id, client_secret, manifest):
"""
Add the client credentials to the specified manifest.
"""
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.add_client_to_manifest(client_id, client_secret,
manifest)
|
[
"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.
|
[
"Add",
"the",
"client",
"credentials",
"to",
"the",
"specified",
"manifest",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/admin/uaa.py#L124-L130
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._get_uaa_uri
|
def _get_uaa_uri(self):
"""
Returns the URI endpoint for an instance of a UAA
service instance from environment inspection.
"""
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_uaa = services['predix-uaa'][0]['credentials']
return predix_uaa['uri']
else:
return predix.config.get_env_value(self, 'uri')
|
python
|
def _get_uaa_uri(self):
"""
Returns the URI endpoint for an instance of a UAA
service instance from environment inspection.
"""
if 'VCAP_SERVICES' in os.environ:
services = json.loads(os.getenv('VCAP_SERVICES'))
predix_uaa = services['predix-uaa'][0]['credentials']
return predix_uaa['uri']
else:
return predix.config.get_env_value(self, 'uri')
|
[
"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.
|
[
"Returns",
"the",
"URI",
"endpoint",
"for",
"an",
"instance",
"of",
"a",
"UAA",
"service",
"instance",
"from",
"environment",
"inspection",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L35-L45
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._authenticate_client
|
def _authenticate_client(self, client, secret):
"""
Returns response of authenticating with the given client and
secret.
"""
client_s = str.join(':', [client, secret])
credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8')
headers = {
'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()
|
python
|
def _authenticate_client(self, client, secret):
"""
Returns response of authenticating with the given client and
secret.
"""
client_s = str.join(':', [client, secret])
credentials = base64.b64encode(client_s.encode('utf-8')).decode('utf-8')
headers = {
'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()
|
[
"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.
|
[
"Returns",
"response",
"of",
"authenticating",
"with",
"the",
"given",
"client",
"and",
"secret",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L47-L76
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._authenticate_user
|
def _authenticate_user(self, user, password):
"""
Returns the response of authenticating with the given
user and password.
"""
headers = self._get_headers()
params = {
'username': user,
'password': password,
'grant_type': '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()
|
python
|
def _authenticate_user(self, user, password):
"""
Returns the response of authenticating with the given
user and password.
"""
headers = self._get_headers()
params = {
'username': user,
'password': password,
'grant_type': '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()
|
[
"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.
|
[
"Returns",
"the",
"response",
"of",
"authenticating",
"with",
"the",
"given",
"user",
"and",
"password",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L78-L101
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.is_expired_token
|
def is_expired_token(self, client):
"""
For a given client will test whether or not the token
has expired.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id.
"""
if 'expires' not in client:
return True
expires = dateutil.parser.parse(client['expires'])
if expires < datetime.datetime.now():
return True
return False
|
python
|
def is_expired_token(self, client):
"""
For a given client will test whether or not the token
has expired.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id.
"""
if 'expires' not in client:
return True
expires = dateutil.parser.parse(client['expires'])
if expires < datetime.datetime.now():
return True
return False
|
[
"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.
This is for testing a client object and does not look up
from client_id. You can use _get_client_from_cache() to
lookup a client from client_id.
|
[
"For",
"a",
"given",
"client",
"will",
"test",
"whether",
"or",
"not",
"the",
"token",
"has",
"expired",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L103-L119
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._initialize_uaa_cache
|
def _initialize_uaa_cache(self):
"""
If we don't yet have a uaa cache we need to
initialize it. As there may be more than one
UAA instance we index by issuer and then store
any clients, users, etc.
"""
try:
os.makedirs(os.path.dirname(self._cache_path))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
data = {}
data[self.uri] = []
return data
|
python
|
def _initialize_uaa_cache(self):
"""
If we don't yet have a uaa cache we need to
initialize it. As there may be more than one
UAA instance we index by issuer and then store
any clients, users, etc.
"""
try:
os.makedirs(os.path.dirname(self._cache_path))
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
data = {}
data[self.uri] = []
return data
|
[
"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.
|
[
"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",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L121-L137
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._read_uaa_cache
|
def _read_uaa_cache(self):
"""
Read cache of UAA client/user details.
"""
self._cache_path = os.path.expanduser('~/.predix/uaa.json')
if not os.path.exists(self._cache_path):
return self._initialize_uaa_cache()
with open(self._cache_path, 'r') as data:
return json.load(data)
|
python
|
def _read_uaa_cache(self):
"""
Read cache of UAA client/user details.
"""
self._cache_path = os.path.expanduser('~/.predix/uaa.json')
if not os.path.exists(self._cache_path):
return self._initialize_uaa_cache()
with open(self._cache_path, 'r') as data:
return json.load(data)
|
[
"def",
"_read_uaa_cache",
"(",
"self",
")",
":",
"self",
".",
"_cache_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.predix/uaa.json'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_cache_path",
")",
":",
"return",
"self",
".",
"_initialize_uaa_cache",
"(",
")",
"with",
"open",
"(",
"self",
".",
"_cache_path",
",",
"'r'",
")",
"as",
"data",
":",
"return",
"json",
".",
"load",
"(",
"data",
")"
] |
Read cache of UAA client/user details.
|
[
"Read",
"cache",
"of",
"UAA",
"client",
"/",
"user",
"details",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L139-L148
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._get_client_from_cache
|
def _get_client_from_cache(self, client_id):
"""
For the given client_id return what is
cached.
"""
data = self._read_uaa_cache()
# Only if we've cached any for this issuer
if self.uri not in data:
return
for client in data[self.uri]:
if client['id'] == client_id:
return client
|
python
|
def _get_client_from_cache(self, client_id):
"""
For the given client_id return what is
cached.
"""
data = self._read_uaa_cache()
# Only if we've cached any for this issuer
if self.uri not in data:
return
for client in data[self.uri]:
if client['id'] == client_id:
return client
|
[
"def",
"_get_client_from_cache",
"(",
"self",
",",
"client_id",
")",
":",
"data",
"=",
"self",
".",
"_read_uaa_cache",
"(",
")",
"# Only if we've cached any for this issuer",
"if",
"self",
".",
"uri",
"not",
"in",
"data",
":",
"return",
"for",
"client",
"in",
"data",
"[",
"self",
".",
"uri",
"]",
":",
"if",
"client",
"[",
"'id'",
"]",
"==",
"client_id",
":",
"return",
"client"
] |
For the given client_id return what is
cached.
|
[
"For",
"the",
"given",
"client_id",
"return",
"what",
"is",
"cached",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L150-L163
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._write_to_uaa_cache
|
def _write_to_uaa_cache(self, new_item):
"""
Cache the client details into a cached file on disk.
"""
data = self._read_uaa_cache()
# Initialize client list if first time
if self.uri not in data:
data[self.uri] = []
# Remove existing client record and any expired tokens
for client in data[self.uri]:
if new_item['id'] == client['id']:
data[self.uri].remove(client)
continue
# May have old tokens laying around to be cleaned up
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))
|
python
|
def _write_to_uaa_cache(self, new_item):
"""
Cache the client details into a cached file on disk.
"""
data = self._read_uaa_cache()
# Initialize client list if first time
if self.uri not in data:
data[self.uri] = []
# Remove existing client record and any expired tokens
for client in data[self.uri]:
if new_item['id'] == client['id']:
data[self.uri].remove(client)
continue
# May have old tokens laying around to be cleaned up
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))
|
[
"def",
"_write_to_uaa_cache",
"(",
"self",
",",
"new_item",
")",
":",
"data",
"=",
"self",
".",
"_read_uaa_cache",
"(",
")",
"# Initialize client list if first time",
"if",
"self",
".",
"uri",
"not",
"in",
"data",
":",
"data",
"[",
"self",
".",
"uri",
"]",
"=",
"[",
"]",
"# Remove existing client record and any expired tokens",
"for",
"client",
"in",
"data",
"[",
"self",
".",
"uri",
"]",
":",
"if",
"new_item",
"[",
"'id'",
"]",
"==",
"client",
"[",
"'id'",
"]",
":",
"data",
"[",
"self",
".",
"uri",
"]",
".",
"remove",
"(",
"client",
")",
"continue",
"# May have old tokens laying around to be cleaned up",
"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.
|
[
"Cache",
"the",
"client",
"details",
"into",
"a",
"cached",
"file",
"on",
"disk",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L165-L191
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.authenticate
|
def authenticate(self, client_id, client_secret, use_cache=True):
"""
Authenticate the given client against UAA. The resulting token
will be cached for reuse.
"""
# We will reuse a token for as long as we have one cached
# and it hasn't expired.
if use_cache:
client = self._get_client_from_cache(client_id)
if (client) and (not self.is_expired_token(client)):
self.authenticated = True
self.client = client
return
# Let's authenticate the client
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()
# Cache it for repeated use until expired
self._write_to_uaa_cache(client)
self.client = client
self.authenticated = True
|
python
|
def authenticate(self, client_id, client_secret, use_cache=True):
"""
Authenticate the given client against UAA. The resulting token
will be cached for reuse.
"""
# We will reuse a token for as long as we have one cached
# and it hasn't expired.
if use_cache:
client = self._get_client_from_cache(client_id)
if (client) and (not self.is_expired_token(client)):
self.authenticated = True
self.client = client
return
# Let's authenticate the client
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()
# Cache it for repeated use until expired
self._write_to_uaa_cache(client)
self.client = client
self.authenticated = True
|
[
"def",
"authenticate",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"use_cache",
"=",
"True",
")",
":",
"# We will reuse a token for as long as we have one cached",
"# and it hasn't expired.",
"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",
"# Let's authenticate the client",
"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",
"(",
")",
"# Cache it for repeated use until expired",
"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.
|
[
"Authenticate",
"the",
"given",
"client",
"against",
"UAA",
".",
"The",
"resulting",
"token",
"will",
"be",
"cached",
"for",
"reuse",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L193-L224
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.logout
|
def logout(self):
"""
Log currently authenticated user out, invalidating any existing tokens.
"""
# Remove token from local cache
# MAINT: need to expire token on server
data = self._read_uaa_cache()
if self.uri in data:
for client in data[self.uri]:
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))
|
python
|
def logout(self):
"""
Log currently authenticated user out, invalidating any existing tokens.
"""
# Remove token from local cache
# MAINT: need to expire token on server
data = self._read_uaa_cache()
if self.uri in data:
for client in data[self.uri]:
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))
|
[
"def",
"logout",
"(",
"self",
")",
":",
"# Remove token from local cache",
"# MAINT: need to expire token on server",
"data",
"=",
"self",
".",
"_read_uaa_cache",
"(",
")",
"if",
"self",
".",
"uri",
"in",
"data",
":",
"for",
"client",
"in",
"data",
"[",
"self",
".",
"uri",
"]",
":",
"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.
|
[
"Log",
"currently",
"authenticated",
"user",
"out",
"invalidating",
"any",
"existing",
"tokens",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L226-L239
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication._post
|
def _post(self, uri, data, headers=None):
"""
Simple POST request for a given uri path.
"""
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
logging.debug("BODY=" + str(data))
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()
|
python
|
def _post(self, uri, data, headers=None):
"""
Simple POST request for a given uri path.
"""
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
logging.debug("BODY=" + str(data))
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()
|
[
"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.
|
[
"Simple",
"POST",
"request",
"for",
"a",
"given",
"uri",
"path",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L272-L291
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.get_token
|
def get_token(self):
"""
Returns the bare access token for the authorized client.
"""
if not self.authenticated:
raise ValueError("Must authenticate() as a client first.")
# If token has expired we'll need to refresh and get a new
# client credential
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']
|
python
|
def get_token(self):
"""
Returns the bare access token for the authorized client.
"""
if not self.authenticated:
raise ValueError("Must authenticate() as a client first.")
# If token has expired we'll need to refresh and get a new
# client credential
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']
|
[
"def",
"get_token",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"authenticated",
":",
"raise",
"ValueError",
"(",
"\"Must authenticate() as a client first.\"",
")",
"# If token has expired we'll need to refresh and get a new",
"# client credential",
"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.
|
[
"Returns",
"the",
"bare",
"access",
"token",
"for",
"the",
"authorized",
"client",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L293-L307
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.get_scopes
|
def get_scopes(self):
"""
Returns the scopes for the authenticated client.
"""
if not self.authenticated:
raise ValueError("Must authenticate() as a client first.")
scope = self.client['scope']
return scope.split()
|
python
|
def get_scopes(self):
"""
Returns the scopes for the authenticated client.
"""
if not self.authenticated:
raise ValueError("Must authenticate() as a client first.")
scope = self.client['scope']
return scope.split()
|
[
"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.
|
[
"Returns",
"the",
"scopes",
"for",
"the",
"authenticated",
"client",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L309-L317
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.assert_has_permission
|
def assert_has_permission(self, scope_required):
"""
Warn that the required scope is not found in the scopes
granted to the currently authenticated user.
::
# The admin user should have client admin permissions
uaa.assert_has_permission('admin', 'clients.admin')
"""
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
|
python
|
def assert_has_permission(self, scope_required):
"""
Warn that the required scope is not found in the scopes
granted to the currently authenticated user.
::
# The admin user should have client admin permissions
uaa.assert_has_permission('admin', 'clients.admin')
"""
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
|
[
"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.
::
# The admin user should have client admin permissions
uaa.assert_has_permission('admin', 'clients.admin')
|
[
"Warn",
"that",
"the",
"required",
"scope",
"is",
"not",
"found",
"in",
"the",
"scopes",
"granted",
"to",
"the",
"currently",
"authenticated",
"user",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L334-L355
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.grant_client_permissions
|
def grant_client_permissions(self, client_id, admin=False, write=False,
read=False, secret=False):
"""
Grant the given client_id permissions for managing clients.
- clients.admin: super user scope to create, modify, delete
- clients.write: scope ot create and modify clients
- clients.read: scope to read info about clients
- clients.secret: scope to change password of a client
"""
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)
|
python
|
def grant_client_permissions(self, client_id, admin=False, write=False,
read=False, secret=False):
"""
Grant the given client_id permissions for managing clients.
- clients.admin: super user scope to create, modify, delete
- clients.write: scope ot create and modify clients
- clients.read: scope to read info about clients
- clients.secret: scope to change password of a client
"""
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)
|
[
"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.
- clients.admin: super user scope to create, modify, delete
- clients.write: scope ot create and modify clients
- clients.read: scope to read info about clients
- clients.secret: scope to change password of a client
|
[
"Grant",
"the",
"given",
"client_id",
"permissions",
"for",
"managing",
"clients",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L357-L385
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.get_clients
|
def get_clients(self):
"""
Returns the clients stored in the instance of UAA.
"""
self.assert_has_permission('clients.read')
uri = self.uri + '/oauth/clients'
headers = self.get_authorization_headers()
response = requests.get(uri, headers=headers)
return response.json()['resources']
|
python
|
def get_clients(self):
"""
Returns the clients stored in the instance of UAA.
"""
self.assert_has_permission('clients.read')
uri = self.uri + '/oauth/clients'
headers = self.get_authorization_headers()
response = requests.get(uri, headers=headers)
return response.json()['resources']
|
[
"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.
|
[
"Returns",
"the",
"clients",
"stored",
"in",
"the",
"instance",
"of",
"UAA",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L387-L396
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.get_client
|
def get_client(self, client_id):
"""
Returns details about a specific client by the client_id.
"""
self.assert_has_permission('clients.read')
uri = self.uri + '/oauth/clients/' + client_id
headers = self.get_authorization_headers()
response = requests.get(uri, headers=headers)
if response.status_code == 200:
return response.json()
else:
# Not found but don't raise
return
|
python
|
def get_client(self, client_id):
"""
Returns details about a specific client by the client_id.
"""
self.assert_has_permission('clients.read')
uri = self.uri + '/oauth/clients/' + client_id
headers = self.get_authorization_headers()
response = requests.get(uri, headers=headers)
if response.status_code == 200:
return response.json()
else:
# Not found but don't raise
return
|
[
"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",
":",
"# Not found but don't raise",
"return"
] |
Returns details about a specific client by the client_id.
|
[
"Returns",
"details",
"about",
"a",
"specific",
"client",
"by",
"the",
"client_id",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L398-L411
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.update_client_grants
|
def update_client_grants(self, client_id, scope=[], authorities=[],
grant_types=[], redirect_uri=[], replace=False):
"""
Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely.
"""
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()
|
python
|
def update_client_grants(self, client_id, scope=[], authorities=[],
grant_types=[], redirect_uri=[], replace=False):
"""
Will extend the client with additional scopes or
authorities. Any existing scopes and authorities will be left
as is unless asked to replace entirely.
"""
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()
|
[
"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.
|
[
"Will",
"extend",
"the",
"client",
"with",
"additional",
"scopes",
"or",
"authorities",
".",
"Any",
"existing",
"scopes",
"and",
"authorities",
"will",
"be",
"left",
"as",
"is",
"unless",
"asked",
"to",
"replace",
"entirely",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L413-L476
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.grant_scim_permissions
|
def grant_scim_permissions(self, client_id, read=False, write=False,
create=False, userids=False, zones=False, invite=False,
openid=False):
"""
Grant the given client_id permissions for managing users. System
for Cross-domain Identity Management (SCIM) are required for accessing
/Users and /Groups endpoints of UAA.
- scim.read: scope for read access to all SCIM endpoints
- scim.write: scope for write access to all SCIM endpoints
- scim.create: scope to create/invite users and verify an account only
- scim.userids: scope for id and username+origin conversion
- scim.zones: scope for group management of users only
- scim.invite: scope to participate in invitations
- openid: scope to access /userinfo
"""
self.assert_has_permission('clients.admin')
perms = []
if read:
perms.append('scim.read')
if write:
perms.append('scim.write')
if create:
perms.append('scim.create')
if userids:
perms.append('scim.userids')
if zones:
perms.append('scim.zones')
if invite:
perms.append('scim.invite')
if openid:
perms.append('openid')
if perms:
self.update_client_grants(client_id, scope=perms, authorities=perms)
|
python
|
def grant_scim_permissions(self, client_id, read=False, write=False,
create=False, userids=False, zones=False, invite=False,
openid=False):
"""
Grant the given client_id permissions for managing users. System
for Cross-domain Identity Management (SCIM) are required for accessing
/Users and /Groups endpoints of UAA.
- scim.read: scope for read access to all SCIM endpoints
- scim.write: scope for write access to all SCIM endpoints
- scim.create: scope to create/invite users and verify an account only
- scim.userids: scope for id and username+origin conversion
- scim.zones: scope for group management of users only
- scim.invite: scope to participate in invitations
- openid: scope to access /userinfo
"""
self.assert_has_permission('clients.admin')
perms = []
if read:
perms.append('scim.read')
if write:
perms.append('scim.write')
if create:
perms.append('scim.create')
if userids:
perms.append('scim.userids')
if zones:
perms.append('scim.zones')
if invite:
perms.append('scim.invite')
if openid:
perms.append('openid')
if perms:
self.update_client_grants(client_id, scope=perms, authorities=perms)
|
[
"def",
"grant_scim_permissions",
"(",
"self",
",",
"client_id",
",",
"read",
"=",
"False",
",",
"write",
"=",
"False",
",",
"create",
"=",
"False",
",",
"userids",
"=",
"False",
",",
"zones",
"=",
"False",
",",
"invite",
"=",
"False",
",",
"openid",
"=",
"False",
")",
":",
"self",
".",
"assert_has_permission",
"(",
"'clients.admin'",
")",
"perms",
"=",
"[",
"]",
"if",
"read",
":",
"perms",
".",
"append",
"(",
"'scim.read'",
")",
"if",
"write",
":",
"perms",
".",
"append",
"(",
"'scim.write'",
")",
"if",
"create",
":",
"perms",
".",
"append",
"(",
"'scim.create'",
")",
"if",
"userids",
":",
"perms",
".",
"append",
"(",
"'scim.userids'",
")",
"if",
"zones",
":",
"perms",
".",
"append",
"(",
"'scim.zones'",
")",
"if",
"invite",
":",
"perms",
".",
"append",
"(",
"'scim.invite'",
")",
"if",
"openid",
":",
"perms",
".",
"append",
"(",
"'openid'",
")",
"if",
"perms",
":",
"self",
".",
"update_client_grants",
"(",
"client_id",
",",
"scope",
"=",
"perms",
",",
"authorities",
"=",
"perms",
")"
] |
Grant the given client_id permissions for managing users. System
for Cross-domain Identity Management (SCIM) are required for accessing
/Users and /Groups endpoints of UAA.
- scim.read: scope for read access to all SCIM endpoints
- scim.write: scope for write access to all SCIM endpoints
- scim.create: scope to create/invite users and verify an account only
- scim.userids: scope for id and username+origin conversion
- scim.zones: scope for group management of users only
- scim.invite: scope to participate in invitations
- openid: scope to access /userinfo
|
[
"Grant",
"the",
"given",
"client_id",
"permissions",
"for",
"managing",
"users",
".",
"System",
"for",
"Cross",
"-",
"domain",
"Identity",
"Management",
"(",
"SCIM",
")",
"are",
"required",
"for",
"accessing",
"/",
"Users",
"and",
"/",
"Groups",
"endpoints",
"of",
"UAA",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L478-L520
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.create_client
|
def create_client(self, client_id, client_secret, manifest=None,
client_credentials=True, refresh_token=True,
authorization_code=False, redirect_uri=[]):
"""
Will create a new client for your application use.
- client_credentials: allows client to get access token
- refresh_token: can be used to get new access token when expired
without re-authenticating
- authorization_code: redirection-based flow for user authentication
More details about Grant types:
- https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-Security.md
- https://tools.ietf.org/html/rfc6749
A redirect_uri is required when using authorization_code. See:
https://www.predix.io/support/article/KB0013026
"""
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")
# Check if client already exists
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()
|
python
|
def create_client(self, client_id, client_secret, manifest=None,
client_credentials=True, refresh_token=True,
authorization_code=False, redirect_uri=[]):
"""
Will create a new client for your application use.
- client_credentials: allows client to get access token
- refresh_token: can be used to get new access token when expired
without re-authenticating
- authorization_code: redirection-based flow for user authentication
More details about Grant types:
- https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-Security.md
- https://tools.ietf.org/html/rfc6749
A redirect_uri is required when using authorization_code. See:
https://www.predix.io/support/article/KB0013026
"""
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")
# Check if client already exists
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()
|
[
"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\"",
")",
"# Check if client already exists",
"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.
- client_credentials: allows client to get access token
- refresh_token: can be used to get new access token when expired
without re-authenticating
- authorization_code: redirection-based flow for user authentication
More details about Grant types:
- https://github.com/cloudfoundry/uaa/blob/master/docs/UAA-Security.md
- https://tools.ietf.org/html/rfc6749
A redirect_uri is required when using authorization_code. See:
https://www.predix.io/support/article/KB0013026
|
[
"Will",
"create",
"a",
"new",
"client",
"for",
"your",
"application",
"use",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L522-L594
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.add_client_to_manifest
|
def add_client_to_manifest(self, client_id, client_secret, manifest):
"""
Add the given client / secret to the manifest for use in
the application.
"""
client_id_key = 'PREDIX_APP_CLIENT_ID'
manifest.add_env_var(client_id_key, client_id)
client_secret_key = 'PREDIX_APP_CLIENT_SECRET'
manifest.add_env_var(client_secret_key, client_secret)
manifest.write_manifest()
|
python
|
def add_client_to_manifest(self, client_id, client_secret, manifest):
"""
Add the given client / secret to the manifest for use in
the application.
"""
client_id_key = 'PREDIX_APP_CLIENT_ID'
manifest.add_env_var(client_id_key, client_id)
client_secret_key = 'PREDIX_APP_CLIENT_SECRET'
manifest.add_env_var(client_secret_key, client_secret)
manifest.write_manifest()
|
[
"def",
"add_client_to_manifest",
"(",
"self",
",",
"client_id",
",",
"client_secret",
",",
"manifest",
")",
":",
"client_id_key",
"=",
"'PREDIX_APP_CLIENT_ID'",
"manifest",
".",
"add_env_var",
"(",
"client_id_key",
",",
"client_id",
")",
"client_secret_key",
"=",
"'PREDIX_APP_CLIENT_SECRET'",
"manifest",
".",
"add_env_var",
"(",
"client_secret_key",
",",
"client_secret",
")",
"manifest",
".",
"write_manifest",
"(",
")"
] |
Add the given client / secret to the manifest for use in
the application.
|
[
"Add",
"the",
"given",
"client",
"/",
"secret",
"to",
"the",
"manifest",
"for",
"use",
"in",
"the",
"application",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L596-L607
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.create_user
|
def create_user(self, username, password, family_name, given_name, primary_email,
details={}):
"""
Creates a new user account with the required details.
::
create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com')
"""
self.assert_has_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)
|
python
|
def create_user(self, username, password, family_name, given_name, primary_email,
details={}):
"""
Creates a new user account with the required details.
::
create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com')
"""
self.assert_has_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)
|
[
"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.
::
create_user('j12y', 'my-secret', 'Delancey', 'Jayson', 'volcano@ge.com')
|
[
"Creates",
"a",
"new",
"user",
"account",
"with",
"the",
"required",
"details",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L619-L647
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.delete_user
|
def delete_user(self, id):
"""
Delete user with given id.
"""
self.assert_has_permission('scim.write')
uri = self.uri + '/Users/%s' % id
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
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()
|
python
|
def delete_user(self, id):
"""
Delete user with given id.
"""
self.assert_has_permission('scim.write')
uri = self.uri + '/Users/%s' % id
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
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()
|
[
"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.
|
[
"Delete",
"user",
"with",
"given",
"id",
"."
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L649-L667
|
PredixDev/predixpy
|
predix/security/uaa.py
|
UserAccountAuthentication.get_users
|
def get_users(self, filter=None, sortBy=None, sortOrder=None,
startIndex=None, count=None):
"""
Returns users accounts stored in UAA.
See https://docs.cloudfoundry.org/api/uaa/#list63
For filtering help, see:
http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources
"""
self.assert_has_permission('scim.read')
params = {}
if filter:
params['filter'] = filter
if sortBy:
params['sortBy'] = sortBy
if sortOrder:
params['sortOrder'] = sortOrder
if startIndex:
params['startIndex'] = startIndex
if count:
params['count'] = count
return self._get(self.uri + '/Users', params=params)
|
python
|
def get_users(self, filter=None, sortBy=None, sortOrder=None,
startIndex=None, count=None):
"""
Returns users accounts stored in UAA.
See https://docs.cloudfoundry.org/api/uaa/#list63
For filtering help, see:
http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources
"""
self.assert_has_permission('scim.read')
params = {}
if filter:
params['filter'] = filter
if sortBy:
params['sortBy'] = sortBy
if sortOrder:
params['sortOrder'] = sortOrder
if startIndex:
params['startIndex'] = startIndex
if count:
params['count'] = count
return self._get(self.uri + '/Users', params=params)
|
[
"def",
"get_users",
"(",
"self",
",",
"filter",
"=",
"None",
",",
"sortBy",
"=",
"None",
",",
"sortOrder",
"=",
"None",
",",
"startIndex",
"=",
"None",
",",
"count",
"=",
"None",
")",
":",
"self",
".",
"assert_has_permission",
"(",
"'scim.read'",
")",
"params",
"=",
"{",
"}",
"if",
"filter",
":",
"params",
"[",
"'filter'",
"]",
"=",
"filter",
"if",
"sortBy",
":",
"params",
"[",
"'sortBy'",
"]",
"=",
"sortBy",
"if",
"sortOrder",
":",
"params",
"[",
"'sortOrder'",
"]",
"=",
"sortOrder",
"if",
"startIndex",
":",
"params",
"[",
"'startIndex'",
"]",
"=",
"startIndex",
"if",
"count",
":",
"params",
"[",
"'count'",
"]",
"=",
"count",
"return",
"self",
".",
"_get",
"(",
"self",
".",
"uri",
"+",
"'/Users'",
",",
"params",
"=",
"params",
")"
] |
Returns users accounts stored in UAA.
See https://docs.cloudfoundry.org/api/uaa/#list63
For filtering help, see:
http://www.simplecloud.info/specs/draft-scim-api-01.html#query-resources
|
[
"Returns",
"users",
"accounts",
"stored",
"in",
"UAA",
".",
"See",
"https",
":",
"//",
"docs",
".",
"cloudfoundry",
".",
"org",
"/",
"api",
"/",
"uaa",
"/",
"#list63"
] |
train
|
https://github.com/PredixDev/predixpy/blob/a0cb34cf40f716229351bb6d90d6ecace958c81f/predix/security/uaa.py#L669-L696
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.