text
stringlengths 81
112k
|
---|
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific
ssh template from the IMC system
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param template_name: str value of template name
:param template_id: str value template template_id value
:return: int HTTP response code
:rtype int
def delete_ssh_template(auth, url, template_name= None, template_id= None):
"""
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific
ssh template from the IMC system
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param template_name: str value of template name
:param template_id: str value template template_id value
:return: int HTTP response code
:rtype int
"""
try:
if template_id is None:
ssh_templates = get_ssh_template(auth, url)
if template_name is None:
template_name = ssh_template['name']
template_id = None
for template in ssh_templates:
if template['name'] == template_name:
template_id = template['id']
f_url = url + "/imcrs/plat/res/ssh/%s/delete" % template_id
response = requests.delete(f_url, auth=auth, headers=HEADERS)
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " delete_ssh_template: An Error has occured"
|
Takes no input, or template_name as input to issue RESTUL call to HP IMC
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param template_name: str value of template name
:return list object containing one or more dictionaries where each dictionary represents one
snmp template
:rtype list
def get_snmp_templates(auth, url, template_name=None):
"""
Takes no input, or template_name as input to issue RESTUL call to HP IMC
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param template_name: str value of template name
:return list object containing one or more dictionaries where each dictionary represents one
snmp template
:rtype list
"""
f_url = url + "/imcrs/plat/res/snmp?start=0&size=10000&desc=false&total=false"
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
snmp_templates = (json.loads(response.text))
template = None
if type(snmp_templates['snmpParamTemplate']) is dict:
my_templates = [snmp_templates['snmpParamTemplate']]
snmp_templates['snmpParamTemplate'] = my_templates
if template_name is None:
return snmp_templates['snmpParamTemplate']
elif template_name is not None:
for snmp_template in snmp_templates['snmpParamTemplate']:
if snmp_template['name'] == template_name:
template = [snmp_template]
if template == None:
return 404
else:
return template
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_snmp_templates: An Error has occured"
|
Function takes input of a dictionry containing the required key/value pair for the modification
of a snmp template.
:param auth:
:param url:
:param ssh_template: Human readable label which is the name of the specific ssh template
:param template_id Internal IMC number which designates the specific ssh template
:return: int value of HTTP response code 201 for proper creation or 404 for failed creation
:rtype int
Sample of proper KV pairs. Please see documentation for valid values for different fields.
snmp_template = {
"version": "2",
"name": "new_snmp_template",
"type": "0",
"paraType": "SNMPv2c",
"roCommunity": "newpublic",
"rwCommunity": "newprivate",
"timeout": "4",
"retries": "4",
"contextName": "",
"securityName": " ",
"securityMode": "1",
"authScheme": "0",
"authPassword": "",
"privScheme": "0",
"privPassword": "",
"snmpPort": "161",
"isAutodiscoverTemp": "1",
"creator": "admin",
"accessType": "1",
"operatorGroupStr": ""
}
def modify_snmp_template(auth, url, snmp_template, template_name= None, template_id = None):
"""
Function takes input of a dictionry containing the required key/value pair for the modification
of a snmp template.
:param auth:
:param url:
:param ssh_template: Human readable label which is the name of the specific ssh template
:param template_id Internal IMC number which designates the specific ssh template
:return: int value of HTTP response code 201 for proper creation or 404 for failed creation
:rtype int
Sample of proper KV pairs. Please see documentation for valid values for different fields.
snmp_template = {
"version": "2",
"name": "new_snmp_template",
"type": "0",
"paraType": "SNMPv2c",
"roCommunity": "newpublic",
"rwCommunity": "newprivate",
"timeout": "4",
"retries": "4",
"contextName": "",
"securityName": " ",
"securityMode": "1",
"authScheme": "0",
"authPassword": "",
"privScheme": "0",
"privPassword": "",
"snmpPort": "161",
"isAutodiscoverTemp": "1",
"creator": "admin",
"accessType": "1",
"operatorGroupStr": ""
}
"""
if template_name is None:
template_name = snmp_template['name']
if template_id is None:
snmp_templates = get_snmp_templates(auth, url)
template_id = None
for template in snmp_templates:
if template['name'] == template_name:
template_id = template['id']
f_url = url + "/imcrs/plat/res/snmp/"+str(template_id)+"/update"
response = requests.put(f_url, data = json.dumps(snmp_template), auth=auth, headers=HEADERS)
try:
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " modify_snmp_template: An Error has occured"
|
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific
snmp template from the IMC system
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param template_name: str value of template name
:param template_id: str value template template_id value
:return: int HTTP response code
:rtype int
def delete_snmp_template(auth, url, template_name= None, template_id= None):
"""
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific
snmp template from the IMC system
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param template_name: str value of template name
:param template_id: str value template template_id value
:return: int HTTP response code
:rtype int
"""
try:
if template_id is None:
snmp_templates = get_snmp_templates(auth, url)
if template_name is None:
template_name = snmp_template['name']
template_id = None
for template in snmp_templates:
if template['name'] == template_name:
template_id = template['id']
f_url = url + "/imcrs/plat/res/snmp/%s/delete" % template_id
response = requests.delete(f_url, auth=auth, headers=HEADERS)
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " delete_snmp_template: An Error has occured"
|
Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API
:param ipaddress: IP address of the device you wish to gather the asset details
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: object of type list containing the device asset details, with each asset contained
in a dictionary
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.netassets import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> single_asset = get_dev_asset_details('10.101.0.1', auth.creds, auth.url)
>>> assert type(single_asset) is list
>>> assert 'name' in single_asset[0]
def get_dev_asset_details(ipaddress, auth, url):
"""Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API
:param ipaddress: IP address of the device you wish to gather the asset details
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: object of type list containing the device asset details, with each asset contained
in a dictionary
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.netassets import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> single_asset = get_dev_asset_details('10.101.0.1', auth.creds, auth.url)
>>> assert type(single_asset) is list
>>> assert 'name' in single_asset[0]
"""
ipaddress = get_dev_details(ipaddress, auth, url)
if isinstance(ipaddress, dict):
ipaddress = ipaddress['ip']
else:
print("Asset Doesn't Exist")
return 403
f_url = url + "/imcrs/netasset/asset?assetDevice.ip=" + str(ipaddress)
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
dev_asset_info = (json.loads(response.text))
if len(dev_asset_info) > 0:
dev_asset_info = dev_asset_info['netAsset']
if isinstance(dev_asset_info, dict):
dev_asset_info = [dev_asset_info]
if isinstance(dev_asset_info, list):
dev_asset_info[:] = [dev for dev in dev_asset_info if dev.get('deviceIp') ==
ipaddress]
return dev_asset_info
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + ' get_dev_asset_details: An Error has occured'
|
Takes no input to fetch device assett details from HP IMC RESTFUL API
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionatires containing the device asset details
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.netassets import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> all_assets = get_dev_asset_details_all( auth.creds, auth.url)
>>> assert type(all_assets) is list
>>> assert 'asset' in all_assets[0]
def get_dev_asset_details_all(auth, url):
"""Takes no input to fetch device assett details from HP IMC RESTFUL API
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionatires containing the device asset details
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.netassets import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> all_assets = get_dev_asset_details_all( auth.creds, auth.url)
>>> assert type(all_assets) is list
>>> assert 'asset' in all_assets[0]
"""
f_url = url + "/imcrs/netasset/asset?start=0&size=15000"
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
dev_asset_info = (json.loads(response.text))['netAsset']
return dev_asset_info
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + ' get_dev_asset_details: An Error has occured'
|
Run a non-encrypted non-authorized API proxy server.
Use this only for development and testing!
def proxy(ctx, bind, port):
"""
Run a non-encrypted non-authorized API proxy server.
Use this only for development and testing!
"""
app = web.Application()
app.on_startup.append(startup_proxy)
app.on_cleanup.append(cleanup_proxy)
app.router.add_route("GET", r'/stream/{path:.*$}', websocket_handler)
app.router.add_route("GET", r'/wsproxy/{path:.*$}', websocket_handler)
app.router.add_route('*', r'/{path:.*$}', web_handler)
if getattr(ctx.args, 'testing', False):
return app
web.run_app(app, host=bind, port=port)
|
Takes string input of IP address to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param network_address: str IPv4 Network Address
:param category: str or int corresponding to device category (0=router, 1=switches, see API docs for other examples)
:return: dictionary of device details
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.')
>>> assert type(dev_list) is list
>>> assert 'sysName' in dev_list[0]
def get_all_devs(auth, url, network_address=None, category=None, label=None):
"""Takes string input of IP address to issue RESTUL call to HP IMC\n
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param network_address: str IPv4 Network Address
:param category: str or int corresponding to device category (0=router, 1=switches, see API docs for other examples)
:return: dictionary of device details
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_list = get_all_devs( auth.creds, auth.url, network_address= '10.11.')
>>> assert type(dev_list) is list
>>> assert 'sysName' in dev_list[0]
"""
base_url = "/imcrs/plat/res/device?resPrivilegeFilter=false"
end_url = "&start=0&size=1000&orderBy=id&desc=false&total=false"
if network_address:
network_address = "&ip=" + str(network_address)
else:
network_address = ''
if label:
label = "&label=" + str(label)
else:
label = ''
if category:
category = "&category" + category
else:
category = ''
f_url = url + base_url + str(network_address) + str(label) + str(category) + end_url
print(f_url)
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
dev_details = (json.loads(response.text))
if len(dev_details) == 0:
print("Device not found")
return "Device not found"
elif type(dev_details['device']) is dict:
return [dev_details['device']]
else:
return dev_details['device']
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_dev_details: An Error has occured"
|
Takes string input of IP address to issue RESTUL call to HP IMC
:param ip_address: string object of dotted decimal notation of IPv4 address
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: dictionary of device details
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url)
>>> assert type(dev_1) is dict
>>> assert 'sysName' in dev_1
>>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url)
Device not found
>>> assert type(dev_2) is str
def get_dev_details(ip_address, auth, url):
"""Takes string input of IP address to issue RESTUL call to HP IMC
:param ip_address: string object of dotted decimal notation of IPv4 address
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: dictionary of device details
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_1 = get_dev_details('10.101.0.221', auth.creds, auth.url)
>>> assert type(dev_1) is dict
>>> assert 'sysName' in dev_1
>>> dev_2 = get_dev_details('8.8.8.8', auth.creds, auth.url)
Device not found
>>> assert type(dev_2) is str
"""
get_dev_details_url = "/imcrs/plat/res/device?resPrivilegeFilter=false&ip=" + \
str(ip_address) + "&start=0&size=1000&orderBy=id&desc=false&total=false"
f_url = url + get_dev_details_url
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
dev_details = (json.loads(response.text))
if len(dev_details) == 0:
print("Device not found")
return "Device not found"
elif isinstance(dev_details['device'], list):
for i in dev_details['device']:
if i['ip'] == ip_address:
dev_details = i
return dev_details
elif isinstance(dev_details['device'], dict):
return dev_details['device']
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_dev_details: An Error has occured"
|
Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device
interfaces
:param devid: optional devid as the input
:param devip: str of ipv4 address of the target device
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list object which contains a dictionary per interface
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devid='15')
>>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devip='10.101.0.221')
>>> assert type(dev_interfaces) is list
>>> assert 'ifAlias' in dev_interfaces[0]
def get_dev_interface(auth, url, devid=None, devip=None):
"""
Function takes devid as input to RESTFUL call to HP IMC platform and returns list of device
interfaces
:param devid: optional devid as the input
:param devip: str of ipv4 address of the target device
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list object which contains a dictionary per interface
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devid='15')
>>> dev_interfaces = get_dev_interface(auth.creds, auth.url, devip='10.101.0.221')
>>> assert type(dev_interfaces) is list
>>> assert 'ifAlias' in dev_interfaces[0]
"""
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
get_dev_interface_url = "/imcrs/plat/res/device/" + str(devid) + \
"/interface?start=0&size=1000&desc=false&total=false"
f_url = url + get_dev_interface_url
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
int_list = json.loads(response.text)
if 'interface' in int_list:
return int_list['interface']
else:
return []
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_dev_interface: An Error has occured"
|
function takes devid of specific device and issues a RESTFUL call to gather the current
IP-MAC learning entries on the target device.
:param devid: int value of the target device
:param devip: ipv4 address of the target device
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dict objects which contain the mac learn table of target device id
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devid='10')
>>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devip='10.101.0.221')
>>> assert type(dev_mac_learn) is list
>>> assert 'deviceId' in dev_mac_learn[0]
def get_dev_mac_learn(auth, url, devid=None, devip=None):
"""
function takes devid of specific device and issues a RESTFUL call to gather the current
IP-MAC learning entries on the target device.
:param devid: int value of the target device
:param devip: ipv4 address of the target device
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dict objects which contain the mac learn table of target device id
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devid='10')
>>> dev_mac_learn = get_dev_mac_learn( auth.creds, auth.url, devip='10.101.0.221')
>>> assert type(dev_mac_learn) is list
>>> assert 'deviceId' in dev_mac_learn[0]
"""
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
f_url = url + '/imcrs/res/access/ipMacLearn/' + str(devid)
try:
response = requests.get(f_url, auth=auth, headers=HEADERS)
if response.status_code == 200:
if len(json.loads(response.text)) < 1:
mac_learn_query = []
return mac_learn_query
else:
mac_learn_query = (json.loads(response.text))['ipMacLearnResult']
if isinstance(mac_learn_query, dict):
mac_learn_query = [mac_learn_query]
return mac_learn_query
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_dev_mac_learn: An Error has occured"
|
Function takes devid of target device and a sequential list of strings which define the
specific commands to be run on the target device and returns a str object containing the
output of the commands.
:param devid: int devid of the target device
:param cmd_list: list of strings
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param devip: str of ipv4 address of the target device
:return: str containing the response of the commands
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> cmd_list = ['display version']
>>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devid ='10')
>>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devip='10.101.0.221')
>>> assert type(cmd_output) is dict
>>> assert 'cmdlist' in cmd_output
>>> assert 'success' in cmd_output
def run_dev_cmd(cmd_list, auth, url, devid=None, devip=None):
"""
Function takes devid of target device and a sequential list of strings which define the
specific commands to be run on the target device and returns a str object containing the
output of the commands.
:param devid: int devid of the target device
:param cmd_list: list of strings
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param devip: str of ipv4 address of the target device
:return: str containing the response of the commands
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> cmd_list = ['display version']
>>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devid ='10')
>>> cmd_output = run_dev_cmd( cmd_list, auth.creds, auth.url, devip='10.101.0.221')
>>> assert type(cmd_output) is dict
>>> assert 'cmdlist' in cmd_output
>>> assert 'success' in cmd_output
"""
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
run_dev_cmd_url = '/imcrs/icc/confFile/executeCmd'
f_url = url + run_dev_cmd_url
cmd_list = _make_cmd_list(cmd_list)
payload = '''{ "deviceId" : "''' + str(devid) + '''",
"cmdlist" : { "cmd" :
[''' + cmd_list + ''']
}
}'''
try:
response = requests.post(f_url, data=payload, auth=auth, headers=HEADERS)
if response.status_code == 200:
if len(response.text) < 1:
return ''
else:
return json.loads(response.text)
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " run_dev_cmd: An Error has occured"
|
function takes the devId of a specific device and the ifindex value assigned to a specific
interface and issues a RESTFUL call to get the interface details file as known by the HP IMC
Base Platform ICC module for the target device.
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param devid: int or str value of the devId of the target device
:param devip: ipv4 address of the target device
:return: list of dict objects which contains the details of all interfaces on the target device
:retype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devId='10')
>>> all_interface_details = get_all_interface_details( auth.creds, auth.url,
devip='10.101.0.221')
>>> assert type(all_interface_details) is list
>>> assert 'ifAlias' in all_interface_details[0]
def get_all_interface_details(auth, url, devid=None, devip=None):
"""
function takes the devId of a specific device and the ifindex value assigned to a specific
interface and issues a RESTFUL call to get the interface details file as known by the HP IMC
Base Platform ICC module for the target device.
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:param devid: int or str value of the devId of the target device
:param devip: ipv4 address of the target device
:return: list of dict objects which contains the details of all interfaces on the target device
:retype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> all_interface_details = get_all_interface_details( auth.creds, auth.url, devId='10')
>>> all_interface_details = get_all_interface_details( auth.creds, auth.url,
devip='10.101.0.221')
>>> assert type(all_interface_details) is list
>>> assert 'ifAlias' in all_interface_details[0]
"""
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
get_all_interface_details_url = "/imcrs/plat/res/device/" + str(
devid) + "/interface/?start=0&size=1000&desc=false&total=false"
f_url = url + get_all_interface_details_url
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
dev_details = (json.loads(response.text))
return dev_details['interface']
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_all_interface_details: An Error has occured"
|
function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to " shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 address of the target devices
:param ifindex: int or str value of the target interface
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: HTTP status code 204 with no values.
:rtype:int
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')
204
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devip = '10.101.0.221')
204
>>> assert type(int_down_response) is int
>>> assert int_down_response is 204
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
def set_interface_down(ifindex, auth, url, devid=None, devip=None):
"""
function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to " shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 address of the target devices
:param ifindex: int or str value of the target interface
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: HTTP status code 204 with no values.
:rtype:int
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')
204
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devip = '10.101.0.221')
204
>>> assert type(int_down_response) is int
>>> assert int_down_response is 204
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
"""
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
set_int_down_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + \
"/down"
f_url = url + set_int_down_url
try:
response = requests.put(f_url, auth=auth, headers=HEADERS)
print(response.status_code)
if response.status_code == 204:
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " set_inteface_down: An Error has occured"
|
function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to "undo shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 address of the target devices
:param ifindex: int or str value of the target interface
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: HTTP status code 204 with no values.
:rype: int
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')
204
>>> int_up_response = set_inteface_up( '9', auth.creds, auth.url, devid = '10')
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')
204
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
>>> assert type(int_up_response) is int
>>> assert int_up_response is 204
def set_inteface_up(ifindex, auth, url, devid=None, devip=None):
"""
function takest devid and ifindex of specific device and interface and issues a RESTFUL call
to "undo shut" the specified interface on the target device.
:param devid: int or str value of the target device
:param devip: ipv4 address of the target devices
:param ifindex: int or str value of the target interface
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: HTTP status code 204 with no values.
:rype: int
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.device import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')
204
>>> int_up_response = set_inteface_up( '9', auth.creds, auth.url, devid = '10')
>>> int_down_response = set_interface_down( '9', auth.creds, auth.url, devid = '10')
204
>>> int_up_response = set_inteface_up('9', auth.creds, auth.url, devip = '10.101.0.221')
>>> assert type(int_up_response) is int
>>> assert int_up_response is 204
"""
if devip is not None:
devid = get_dev_details(devip, auth, url)['id']
set_int_up_url = "/imcrs/plat/res/device/" + str(devid) + "/interface/" + str(ifindex) + "/up"
f_url = url + set_int_up_url
try:
response = requests.put(f_url, auth=auth, headers=HEADERS)
if response.status_code == 204:
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " set_inteface_up: An Error has occured"
|
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
def _make_cmd_list(cmd_list):
"""
Helper function to easily create the proper json formated string from a list of strs
:param cmd_list: list of strings
:return: str json formatted
"""
cmd = ''
for i in cmd_list:
cmd = cmd + '"' + i + '",'
cmd = cmd[:-1]
return cmd
|
Creates a new keypair with the given options.
You need an admin privilege for this operation.
async def create(cls, user_id: Union[int, str],
is_active: bool = True,
is_admin: bool = False,
resource_policy: str = None,
rate_limit: int = None,
fields: Iterable[str] = None) -> dict:
'''
Creates a new keypair with the given options.
You need an admin privilege for this operation.
'''
if fields is None:
fields = ('access_key', 'secret_key')
uid_type = 'Int!' if isinstance(user_id, int) else 'String!'
q = 'mutation($user_id: {0}, $input: KeyPairInput!) {{'.format(uid_type) + \
' create_keypair(user_id: $user_id, props: $input) {' \
' ok msg keypair { $fields }' \
' }' \
'}'
q = q.replace('$fields', ' '.join(fields))
variables = {
'user_id': user_id,
'input': {
'is_active': is_active,
'is_admin': is_admin,
'resource_policy': resource_policy,
'rate_limit': rate_limit,
},
}
rqst = Request(cls.session, 'POST', '/admin/graphql')
rqst.set_json({
'query': q,
'variables': variables,
})
async with rqst.fetch() as resp:
data = await resp.json()
return data['create_keypair']
|
Creates a new keypair with the given options.
You need an admin privilege for this operation.
async def update(cls, access_key: str,
is_active: bool = None,
is_admin: bool = None,
resource_policy: str = None,
rate_limit: int = None) -> dict:
"""
Creates a new keypair with the given options.
You need an admin privilege for this operation.
"""
q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \
' modify_keypair(access_key: $access_key, props: $input) {' \
' ok msg' \
' }' \
'}'
variables = {
'access_key': access_key,
'input': {
'is_active': is_active,
'is_admin': is_admin,
'resource_policy': resource_policy,
'rate_limit': rate_limit,
},
}
rqst = Request(cls.session, 'POST', '/admin/graphql')
rqst.set_json({
'query': q,
'variables': variables,
})
async with rqst.fetch() as resp:
data = await resp.json()
return data['modify_keypair']
|
Deletes an existing keypair with given ACCESSKEY.
async def delete(cls, access_key: str):
"""
Deletes an existing keypair with given ACCESSKEY.
"""
q = 'mutation($access_key: String!) {' \
' delete_keypair(access_key: $access_key) {' \
' ok msg' \
' }' \
'}'
variables = {
'access_key': access_key,
}
rqst = Request(cls.session, 'POST', '/admin/graphql')
rqst.set_json({
'query': q,
'variables': variables,
})
async with rqst.fetch() as resp:
data = await resp.json()
return data['delete_keypair']
|
Lists the keypairs.
You need an admin privilege for this operation.
async def list(cls, user_id: Union[int, str] = None,
is_active: bool = None,
fields: Iterable[str] = None) -> Sequence[dict]:
'''
Lists the keypairs.
You need an admin privilege for this operation.
'''
if fields is None:
fields = (
'access_key', 'secret_key',
'is_active', 'is_admin',
)
if user_id is None:
q = 'query($is_active: Boolean) {' \
' keypairs(is_active: $is_active) {' \
' $fields' \
' }' \
'}'
else:
uid_type = 'Int!' if isinstance(user_id, int) else 'String!'
q = 'query($user_id: {0}, $is_active: Boolean) {{'.format(uid_type) + \
' keypairs(user_id: $user_id, is_active: $is_active) {' \
' $fields' \
' }' \
'}'
q = q.replace('$fields', ' '.join(fields))
variables = {
'is_active': is_active,
}
if user_id is not None:
variables['user_id'] = user_id
rqst = Request(cls.session, 'POST', '/admin/graphql')
rqst.set_json({
'query': q,
'variables': variables,
})
async with rqst.fetch() as resp:
data = await resp.json()
return data['keypairs']
|
Returns the keypair's information such as resource limits.
:param fields: Additional per-agent query fields to fetch.
.. versionadded:: 18.12
async def info(self, fields: Iterable[str] = None) -> dict:
'''
Returns the keypair's information such as resource limits.
:param fields: Additional per-agent query fields to fetch.
.. versionadded:: 18.12
'''
if fields is None:
fields = (
'access_key', 'secret_key',
'is_active', 'is_admin',
)
q = 'query {' \
' keypair {' \
' $fields' \
' }' \
'}'
q = q.replace('$fields', ' '.join(fields))
rqst = Request(self.session, 'POST', '/admin/graphql')
rqst.set_json({
'query': q,
})
async with rqst.fetch() as resp:
data = await resp.json()
return data['keypair']
|
Activates this keypair.
You need an admin privilege for this operation.
async def activate(cls, access_key: str) -> dict:
'''
Activates this keypair.
You need an admin privilege for this operation.
'''
q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \
' modify_keypair(access_key: $access_key, props: $input) {' \
' ok msg' \
' }' \
'}'
variables = {
'access_key': access_key,
'input': {
'is_active': True,
'is_admin': None,
'resource_policy': None,
'rate_limit': None,
},
}
rqst = Request(cls.session, 'POST', '/admin/graphql')
rqst.set_json({
'query': q,
'variables': variables,
})
async with rqst.fetch() as resp:
data = await resp.json()
return data['modify_keypair']
|
Deactivates this keypair.
Deactivated keypairs cannot make any API requests
unless activated again by an administrator.
You need an admin privilege for this operation.
async def deactivate(cls, access_key: str) -> dict:
'''
Deactivates this keypair.
Deactivated keypairs cannot make any API requests
unless activated again by an administrator.
You need an admin privilege for this operation.
'''
q = 'mutation($access_key: String!, $input: ModifyKeyPairInput!) {' + \
' modify_keypair(access_key: $access_key, props: $input) {' \
' ok msg' \
' }' \
'}'
variables = {
'access_key': access_key,
'input': {
'is_active': False,
'is_admin': None,
'resource_policy': None,
'rate_limit': None,
},
}
rqst = Request(cls.session, 'POST', '/admin/graphql')
rqst.set_json({
'query': q,
'variables': variables,
})
async with rqst.fetch() as resp:
data = await resp.json()
return data['modify_keypair']
|
Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access
in the HPE IMC base platform
:param startIp: str Start of IP address scope ex. '10.101.0.1'
:param endIp: str End of IP address scope ex. '10.101.0.254'
:param name: str Name of the owner of this IP scope ex. 'admin'
:param description: str description of the Ip scope
:return:
def add_ip_scope(auth, url,startIp, endIp, name, description):
"""
Function takes input of four strings Start Ip, endIp, name, and description to add new Ip Scope to terminal access
in the HPE IMC base platform
:param startIp: str Start of IP address scope ex. '10.101.0.1'
:param endIp: str End of IP address scope ex. '10.101.0.254'
:param name: str Name of the owner of this IP scope ex. 'admin'
:param description: str description of the Ip scope
:return:
"""
if auth is None or url is None: # checks to see if the imc credentials are already available
set_imc_creds()
add_ip_scope_url = "/imcrs/res/access/assignedIpScope"
f_url = url + add_ip_scope_url
payload = ('''{ "startIp": "%s", "endIp": "%s","name": "%s","description": "%s" }'''
%(str(startIp), str(endIp), str(name), str(description)))
r = requests.post(f_url, auth=auth, headers=HEADERS, data=payload) # creates the URL using the payload variable as the contents
try:
if r.status_code == 200:
print("IP Scope Successfully Created")
return r.status_code
elif r.status_code == 409:
print ("IP Scope Already Exists")
return r.status_code
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " add_ip_scope: An Error has occured"
#Add host to IP scope
#http://10.101.0.203:8080/imcrs/res/access/assignedIpScope/ip?ipScopeId=1
'''{
"ip": "10.101.0.1",
"name": "Cisco2811.lab.local",
"description": "Cisco 2811",
"parentId": "1"
}'''
|
Lists all resource presets in the current scaling group with additiona
information.
async def check_presets(cls):
'''
Lists all resource presets in the current scaling group with additiona
information.
'''
rqst = Request(cls.session, 'POST', '/resource/check-presets')
async with rqst.fetch() as resp:
return await resp.json()
|
function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into
JSON and issues a RESTFUL call to create the performance task.
device.
:param task: dictionary containing all required fields for performance tasks
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: 204
:rtype: str
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.perf import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> new_task = {'indexDesc': '1.3.6.1.4.1.9.9.13.1.3.1.3','indexType': '[index1[0]:ciscoEnvMonTemperatureStatusValue:1:0]','itemFunction': '1.3.6.1.4.1.9.9.13.1.3.1.3','itemName': 'Cisco_Temperature','selectDefaultUnit': '400','unit': 'Celsius'}
>>> new_perf_task = add_perf_task(new_task, auth.creds, auth.url)
def add_perf_task(task, auth, url):
"""
function takes the a python dict containing all necessary fields for a performance tasks, transforms the dict into
JSON and issues a RESTFUL call to create the performance task.
device.
:param task: dictionary containing all required fields for performance tasks
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: 204
:rtype: str
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.perf import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> new_task = {'indexDesc': '1.3.6.1.4.1.9.9.13.1.3.1.3','indexType': '[index1[0]:ciscoEnvMonTemperatureStatusValue:1:0]','itemFunction': '1.3.6.1.4.1.9.9.13.1.3.1.3','itemName': 'Cisco_Temperature','selectDefaultUnit': '400','unit': 'Celsius'}
>>> new_perf_task = add_perf_task(new_task, auth.creds, auth.url)
"""
add_perf_task_url = "/imcrs/perf/task"
f_url = url + add_perf_task_url
payload = json.dumps(task)
# creates the URL using the payload variable as the contents
r = requests.post(f_url, data = payload, auth=auth, headers=headers)
try:
return r.status_code
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
|
function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call
to the IMC REST service. It will return a list
:param task_name: str containing the name of the performance task
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: 204
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.perf import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> selected_task = get_perf_task('Cisco_Temperature', auth.creds, auth.url)
>>> assert type(selected_task) is dict
>>> assert 'taskName' in selected_task
def get_perf_task(task_name, auth, url):
"""
function takes the a str object containing the name of an existing performance tasks and issues a RESTFUL call
to the IMC REST service. It will return a list
:param task_name: str containing the name of the performance task
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: 204
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.perf import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> selected_task = get_perf_task('Cisco_Temperature', auth.creds, auth.url)
>>> assert type(selected_task) is dict
>>> assert 'taskName' in selected_task
"""
get_perf_task_url = "/imcrs/perf/task?name="+task_name+"&orderBy=taskId&desc=false"
f_url = url + get_perf_task_url
# creates the URL using the payload variable as the contents
r = requests.get(f_url, auth=auth, headers=headers)
try:
if r.status_code == 200:
perf_task_info = (json.loads(r.text))['task']
return perf_task_info
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + ' get_dev_alarms: An Error has occured'
|
function takes hostId as input to RESTFUL call to HP IMC
:param hostip: int or string of hostip of Hypervisor host
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: Dictionary contraining the information for the target VM host
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.vrm import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url)
>>> assert type(host_info) is dict
>>> assert len(host_info) == 10
>>> assert 'cpuFeg' in host_info
>>> assert 'cpuNum' in host_info
>>> assert 'devId' in host_info
>>> assert 'devIp' in host_info
>>> assert 'diskSize' in host_info
>>> assert 'memory' in host_info
>>> assert 'parentDevId' in host_info
>>> assert 'porductFlag' in host_info
>>> assert 'serverName' in host_info
>>> assert 'vendor' in host_info
def get_vm_host_info(hostip, auth, url):
"""
function takes hostId as input to RESTFUL call to HP IMC
:param hostip: int or string of hostip of Hypervisor host
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: Dictionary contraining the information for the target VM host
:rtype: dict
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.plat.vrm import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> host_info = get_vm_host_info('10.101.0.6', auth.creds, auth.url)
>>> assert type(host_info) is dict
>>> assert len(host_info) == 10
>>> assert 'cpuFeg' in host_info
>>> assert 'cpuNum' in host_info
>>> assert 'devId' in host_info
>>> assert 'devIp' in host_info
>>> assert 'diskSize' in host_info
>>> assert 'memory' in host_info
>>> assert 'parentDevId' in host_info
>>> assert 'porductFlag' in host_info
>>> assert 'serverName' in host_info
>>> assert 'vendor' in host_info
"""
hostId = get_dev_details(hostip, auth, url)['id']
get_vm_host_info_url = "/imcrs/vrm/host?hostId=" + str(hostId)
f_url = url + get_vm_host_info_url
payload = None
r = requests.get(f_url, auth=auth,
headers=HEADERS) # creates the URL using the payload variable as the contents
# print(r.status_code)
try:
if r.status_code == 200:
if len(r.text) > 0:
return json.loads(r.text)
elif r.status_code == 204:
print("Device is not a supported Hypervisor")
return "Device is not a supported Hypervisor"
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " get_vm_host_info: An Error has occured"
|
function takes no input as input to RESTFUL call to HP IMC
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each element of the list represents a single wireless
controller which has been discovered in the HPE IMC WSM module
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.wsm.acinfo import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> ac_info_all = get_ac_info_all(auth.creds, auth.url)
def get_ac_info_all(auth, url):
"""
function takes no input as input to RESTFUL call to HP IMC
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass
:return: list of dictionaries where each element of the list represents a single wireless
controller which has been discovered in the HPE IMC WSM module
:rtype: list
>>> from pyhpeimc.auth import *
>>> from pyhpeimc.wsm.acinfo import *
>>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin")
>>> ac_info_all = get_ac_info_all(auth.creds, auth.url)
"""
f_url = url + "/imcrs/wlan/acInfo/queryAcBasicInfo"
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
if len(response.text) > 0:
acs = json.loads(response.text)['acBasicInfo']
if type(acs) is dict:
acs = [acs]
return acs
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_ac_info_all: An Error has occured"
|
This function prompts user for IMC server information and credentuials and stores
values in url and auth global variables
def set_imc_creds(h_url=None, imc_server=None, imc_port=None, imc_user=None,imc_pw=None):
""" This function prompts user for IMC server information and credentuials and stores
values in url and auth global variables"""
global auth, url
if h_url is None:
imc_protocol = input(
"What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:")
if imc_protocol == "1":
h_url = 'http://'
else:
h_url = 'https://'
imc_server = input("What is the ip address of the IMC server?")
imc_port = input("What is the port number of the IMC server?")
imc_user = input("What is the username of the IMC eAPI user?")
imc_pw = input('''What is the password of the IMC eAPI user?''')
url = h_url + imc_server + ":" + imc_port
auth = requests.auth.HTTPDigestAuth(imc_user, imc_pw)
test_url = '/imcrs'
f_url = url + test_url
try:
r = requests.get(f_url, auth=auth, headers=headers, verify=False)
print (r.status_code)
return auth
# checks for reqeusts exceptions
except requests.exceptions.RequestException as e:
print("Error:\n" + str(e))
print("\n\nThe IMC server address is invalid. Please try again\n\n")
set_imc_creds()
if r.status_code != 200: # checks for valid IMC credentials
print("Error: \n You're credentials are invalid. Please try again\n\n")
set_imc_creds()
else:
print("You've successfully access the IMC eAPI")
|
Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt
:param: Object: object of type str, list, or dict
:return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt
def print_to_file(object):
"""
Function takes in object of type str, list, or dict and prints out to current working directory as pyoutput.txt
:param: Object: object of type str, list, or dict
:return: No return. Just prints out to file handler and save to current working directory as pyoutput.txt
"""
with open ('pyoutput.txt', 'w') as fh:
x = None
if type(object) is list:
x = json.dumps(object, indent = 4)
if type(object) is dict:
x = json.dumps(object, indent = 4)
if type (object) is str:
x = object
fh.write(x)
|
This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object
:return:
def get_auth(self):
"""
This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object
:return:
"""
url = self.h_url + self.server + ":" + self.port
auth = requests.auth.HTTPDigestAuth(self.username,self.password)
auth_url = "/imcrs"
f_url = url + auth_url
try:
r = requests.get(f_url, auth=auth, headers=headers, verify=False)
return r.status_code
# checks for reqeusts exceptions
except requests.exceptions.RequestException as e:
return ("Error:\n" + str(e) + '\n\nThe IMC server address is invalid. Please try again')
set_imc_creds()
if r.status_code != 200: # checks for valid IMC credentials
return ("Error:\n" + str(e) +"Error: \n You're credentials are invalid. Please try again\n\n")
set_imc_creds()
|
Load and return the contents of version.json.
:param root: The root path that the ``version.json`` file will be opened
:type root: str
:returns: Content of ``version.json`` or None
:rtype: dict or None
def get_version(root):
"""
Load and return the contents of version.json.
:param root: The root path that the ``version.json`` file will be opened
:type root: str
:returns: Content of ``version.json`` or None
:rtype: dict or None
"""
version_json = os.path.join(root, 'version.json')
if os.path.exists(version_json):
with open(version_json, 'r') as version_json_file:
return json.load(version_json_file)
return None
|
Calls this instance's request_client's post method with the
specified component endpoint
Args:
- endpoint_name (str) - The endpoint to call like "property/value".
- identifier_input - One or more identifiers to request data for. An identifier can
be in one of these forms:
- A list of property identifier dicts:
- A property identifier dict can contain the following keys:
(address, zipcode, unit, city, state, slug, meta).
One of 'address' or 'slug' is required.
Ex: [{"address": "82 County Line Rd",
"zipcode": "72173",
"meta": "some ID"}]
A slug is a URL-safe string that identifies a property.
These are obtained from HouseCanary.
Ex: [{"slug": "123-Example-St-San-Francisco-CA-94105"}]
- A list of dicts representing a block:
- A block identifier dict can contain the following keys:
(block_id, num_bins, property_type, meta).
'block_id' is required.
Ex: [{"block_id": "060750615003005", "meta": "some ID"}]
- A list of dicts representing a zipcode:
Ex: [{"zipcode": "90274", "meta": "some ID"}]
- A list of dicts representing an MSA:
Ex: [{"msa": "41860", "meta": "some ID"}]
The "meta" field is always optional.
Returns:
A Response object, or the output of a custom OutputGenerator
if one was specified in the constructor.
def fetch(self, endpoint_name, identifier_input, query_params=None):
"""Calls this instance's request_client's post method with the
specified component endpoint
Args:
- endpoint_name (str) - The endpoint to call like "property/value".
- identifier_input - One or more identifiers to request data for. An identifier can
be in one of these forms:
- A list of property identifier dicts:
- A property identifier dict can contain the following keys:
(address, zipcode, unit, city, state, slug, meta).
One of 'address' or 'slug' is required.
Ex: [{"address": "82 County Line Rd",
"zipcode": "72173",
"meta": "some ID"}]
A slug is a URL-safe string that identifies a property.
These are obtained from HouseCanary.
Ex: [{"slug": "123-Example-St-San-Francisco-CA-94105"}]
- A list of dicts representing a block:
- A block identifier dict can contain the following keys:
(block_id, num_bins, property_type, meta).
'block_id' is required.
Ex: [{"block_id": "060750615003005", "meta": "some ID"}]
- A list of dicts representing a zipcode:
Ex: [{"zipcode": "90274", "meta": "some ID"}]
- A list of dicts representing an MSA:
Ex: [{"msa": "41860", "meta": "some ID"}]
The "meta" field is always optional.
Returns:
A Response object, or the output of a custom OutputGenerator
if one was specified in the constructor.
"""
endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name
if query_params is None:
query_params = {}
if len(identifier_input) == 1:
# If only one identifier specified, use a GET request
query_params.update(identifier_input[0])
return self._request_client.get(endpoint_url, query_params)
# when more than one address, use a POST request
return self._request_client.post(endpoint_url, identifier_input, query_params)
|
Calls this instance's request_client's get method with the
specified component endpoint
def fetch_synchronous(self, endpoint_name, query_params=None):
"""Calls this instance's request_client's get method with the
specified component endpoint"""
endpoint_url = constants.URL_PREFIX + "/" + self._version + "/" + endpoint_name
if query_params is None:
query_params = {}
return self._request_client.get(endpoint_url, query_params)
|
Convert the various formats of input identifier_data into
the proper json format expected by the ApiClient fetch method,
which is a list of dicts.
def get_identifier_input(self, identifier_data):
"""Convert the various formats of input identifier_data into
the proper json format expected by the ApiClient fetch method,
which is a list of dicts."""
identifier_input = []
if isinstance(identifier_data, list) and len(identifier_data) > 0:
# if list, convert each item in the list to json
for address in identifier_data:
identifier_input.append(self._convert_to_identifier_json(address))
else:
identifier_input.append(self._convert_to_identifier_json(identifier_data))
return identifier_input
|
Common method for handling parameters before passing to api_client
def fetch_identifier_component(self, endpoint_name, identifier_data, query_params=None):
"""Common method for handling parameters before passing to api_client"""
if query_params is None:
query_params = {}
identifier_input = self.get_identifier_input(identifier_data)
return self._api_client.fetch(endpoint_name, identifier_input, query_params)
|
Convert input address data into json format
def _convert_to_identifier_json(self, address_data):
"""Convert input address data into json format"""
if isinstance(address_data, str):
# allow just passing a slug string.
return {"slug": address_data}
if isinstance(address_data, tuple) and len(address_data) > 0:
address_json = {"address": address_data[0]}
if len(address_data) > 1:
address_json["zipcode"] = address_data[1]
if len(address_data) > 2:
address_json["meta"] = address_data[2]
return address_json
if isinstance(address_data, dict):
allowed_keys = ["address", "zipcode", "unit", "city", "state", "slug", "meta",
"client_value", "client_value_sqft"]
# ensure the dict does not contain any unallowed keys
for key in address_data:
if key not in allowed_keys:
msg = "Key in address input not allowed: " + key
raise housecanary.exceptions.InvalidInputException(msg)
# ensure it contains an "address" key
if "address" in address_data or "slug" in address_data:
return address_data
# if we made it here, the input was not valid.
msg = ("Input is invalid. Must be a list of (address, zipcode) tuples, or a dict or list"
" of dicts with each item containing at least an 'address' or 'slug' key.")
raise housecanary.exceptions.InvalidInputException((msg))
|
Call the value_report component
Value Report only supports a single address.
Args:
- address
- zipcode
Kwargs:
- report_type - "full" or "summary". Default is "full".
- format_type - "json", "pdf", "xlsx" or "all". Default is "json".
def value_report(self, address, zipcode, report_type="full", format_type="json"):
"""Call the value_report component
Value Report only supports a single address.
Args:
- address
- zipcode
Kwargs:
- report_type - "full" or "summary". Default is "full".
- format_type - "json", "pdf", "xlsx" or "all". Default is "json".
"""
query_params = {
"report_type": report_type,
"format": format_type,
"address": address,
"zipcode": zipcode
}
return self._api_client.fetch_synchronous("property/value_report", query_params)
|
Call the rental_report component
Rental Report only supports a single address.
Args:
- address
- zipcode
Kwargs:
- format_type - "json", "xlsx" or "all". Default is "json".
def rental_report(self, address, zipcode, format_type="json"):
"""Call the rental_report component
Rental Report only supports a single address.
Args:
- address
- zipcode
Kwargs:
- format_type - "json", "xlsx" or "all". Default is "json".
"""
# only json is supported by rental report.
query_params = {
"format": format_type,
"address": address,
"zipcode": zipcode
}
return self._api_client.fetch_synchronous("property/rental_report", query_params)
|
Call the zip component_mget endpoint
Args:
- zip_data - As described in the class docstring.
- components - A list of strings for each component to include in the request.
Example: ["zip/details", "zip/volatility"]
def component_mget(self, zip_data, components):
"""Call the zip component_mget endpoint
Args:
- zip_data - As described in the class docstring.
- components - A list of strings for each component to include in the request.
Example: ["zip/details", "zip/volatility"]
"""
if not isinstance(components, list):
print("Components param must be a list")
return
query_params = {"components": ",".join(components)}
return self.fetch_identifier_component(
"zip/component_mget", zip_data, query_params)
|
Returns the contents of version.json or a 404.
def version(request):
"""
Returns the contents of version.json or a 404.
"""
version_json = import_string(version_callback)(settings.BASE_DIR)
if version_json is None:
return HttpResponseNotFound('version.json not found')
else:
return JsonResponse(version_json)
|
Runs all the Django checks and returns a JsonResponse with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
def heartbeat(request):
"""
Runs all the Django checks and returns a JsonResponse with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response.
"""
all_checks = checks.registry.registry.get_checks(
include_deployment_checks=not settings.DEBUG,
)
details = {}
statuses = {}
level = 0
for check in all_checks:
detail = heartbeat_check_detail(check)
statuses[check.__name__] = detail['status']
level = max(level, detail['level'])
if detail['level'] > 0:
details[check.__name__] = detail
if level < checks.messages.WARNING:
status_code = 200
heartbeat_passed.send(sender=heartbeat, level=level)
else:
status_code = 500
heartbeat_failed.send(sender=heartbeat, level=level)
payload = {
'status': level_to_text(level),
'checks': statuses,
'details': details,
}
return JsonResponse(payload, status=status_code)
|
Returns a list of ComponentResult from the json_data
def _create_component_results(json_data, result_key):
""" Returns a list of ComponentResult from the json_data"""
component_results = []
for key, value in list(json_data.items()):
if key not in [result_key, "meta"]:
component_result = ComponentResult(
key,
value["result"],
value["api_code"],
value["api_code_description"]
)
component_results.append(component_result)
return component_results
|
Returns whether there was a business logic error when fetching data
for any components for this property.
Returns:
boolean
def has_error(self):
"""Returns whether there was a business logic error when fetching data
for any components for this property.
Returns:
boolean
"""
return next(
(True for cr in self.component_results
if cr.has_error()),
False
)
|
If there were any business errors fetching data for this property,
returns the error messages.
Returns:
string - the error message, or None if there was no error.
def get_errors(self):
"""If there were any business errors fetching data for this property,
returns the error messages.
Returns:
string - the error message, or None if there was no error.
"""
return [{cr.component_name: cr.get_error()}
for cr in self.component_results if cr.has_error()]
|
Deserialize property json data into a Property object
Args:
json_data (dict): The json data for this property
Returns:
Property object
def create_from_json(cls, json_data):
"""Deserialize property json data into a Property object
Args:
json_data (dict): The json data for this property
Returns:
Property object
"""
prop = Property()
address_info = json_data["address_info"]
prop.address = address_info["address"]
prop.block_id = address_info["block_id"]
prop.zipcode = address_info["zipcode"]
prop.zipcode_plus4 = address_info["zipcode_plus4"]
prop.address_full = address_info["address_full"]
prop.city = address_info["city"]
prop.county_fips = address_info["county_fips"]
prop.geo_precision = address_info["geo_precision"]
prop.lat = address_info["lat"]
prop.lng = address_info["lng"]
prop.slug = address_info["slug"]
prop.state = address_info["state"]
prop.unit = address_info["unit"]
prop.meta = None
if "meta" in json_data:
prop.meta = json_data["meta"]
prop.component_results = _create_component_results(json_data, "address_info")
return prop
|
Deserialize block json data into a Block object
Args:
json_data (dict): The json data for this block
Returns:
Block object
def create_from_json(cls, json_data):
"""Deserialize block json data into a Block object
Args:
json_data (dict): The json data for this block
Returns:
Block object
"""
block = Block()
block_info = json_data["block_info"]
block.block_id = block_info["block_id"]
block.num_bins = block_info["num_bins"] if "num_bins" in block_info else None
block.property_type = block_info["property_type"] if "property_type" in block_info else None
block.meta = json_data["meta"] if "meta" in json_data else None
block.component_results = _create_component_results(json_data, "block_info")
return block
|
Deserialize zipcode json data into a ZipCode object
Args:
json_data (dict): The json data for this zipcode
Returns:
Zip object
def create_from_json(cls, json_data):
"""Deserialize zipcode json data into a ZipCode object
Args:
json_data (dict): The json data for this zipcode
Returns:
Zip object
"""
zipcode = ZipCode()
zipcode.zipcode = json_data["zipcode_info"]["zipcode"]
zipcode.meta = json_data["meta"] if "meta" in json_data else None
zipcode.component_results = _create_component_results(json_data, "zipcode_info")
return zipcode
|
Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object
def create_from_json(cls, json_data):
"""Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object
"""
msa = Msa()
msa.msa = json_data["msa_info"]["msa"]
msa.meta = json_data["meta"] if "meta" in json_data else None
msa.component_results = _create_component_results(json_data, "msa_info")
return msa
|
Start yielding items when a condition arise.
Args:
iterable: the iterable to filter.
condition: if the callable returns True once, start yielding
items. If it's not a callable, it will be converted
to one as `lambda condition: condition == item`.
Example:
>>> list(starts_when(range(10), lambda x: x > 5))
[6, 7, 8, 9]
>>> list(starts_when(range(10), 7))
[7, 8, 9]
def starts_when(iterable, condition):
# type: (Iterable, Union[Callable, Any]) -> Iterable
"""Start yielding items when a condition arise.
Args:
iterable: the iterable to filter.
condition: if the callable returns True once, start yielding
items. If it's not a callable, it will be converted
to one as `lambda condition: condition == item`.
Example:
>>> list(starts_when(range(10), lambda x: x > 5))
[6, 7, 8, 9]
>>> list(starts_when(range(10), 7))
[7, 8, 9]
"""
if not callable(condition):
cond_value = condition
def condition(x):
return x == cond_value
return itertools.dropwhile(lambda x: not condition(x), iterable)
|
Stop yielding items when a condition arise.
Args:
iterable: the iterable to filter.
condition: if the callable returns True once, stop yielding
items. If it's not a callable, it will be converted
to one as `lambda condition: condition == item`.
Example:
>>> list(stops_when(range(10), lambda x: x > 5))
[0, 1, 2, 3, 4, 5]
>>> list(stops_when(range(10), 7))
[0, 1, 2, 3, 4, 5, 6]
def stops_when(iterable, condition):
# type: (Iterable, Union[Callable, Any]) -> Iterable
"""Stop yielding items when a condition arise.
Args:
iterable: the iterable to filter.
condition: if the callable returns True once, stop yielding
items. If it's not a callable, it will be converted
to one as `lambda condition: condition == item`.
Example:
>>> list(stops_when(range(10), lambda x: x > 5))
[0, 1, 2, 3, 4, 5]
>>> list(stops_when(range(10), 7))
[0, 1, 2, 3, 4, 5, 6]
"""
if not callable(condition):
cond_value = condition
def condition(x):
return x == cond_value
return itertools.takewhile(lambda x: not condition(x), iterable)
|
Returns a generator that will yield all objects from iterable, skipping
duplicates.
Duplicates are identified using the `key` function to calculate a
unique fingerprint. This does not use natural equality, but the
result use a set() to remove duplicates, so defining __eq__
on your objects would have no effect.
By default the fingerprint is the object itself,
which ensure the functions works as-is with an iterable of primitives
such as int, str or tuple.
:Example:
>>> list(skip_duplicates([1, 2, 3, 4, 4, 2, 1, 3 , 4]))
[1, 2, 3, 4]
The return value of `key` MUST be hashable, which means for
non hashable objects such as dict, set or list, you need to specify
a a function that returns a hashable fingerprint.
:Example:
>>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)),
... lambda x: tuple(x)))
[[], [1, 2]]
>>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)),
... lambda x: (type(x), tuple(x))))
[[], (), [1, 2], (1, 2)]
For more complex types, such as custom classes, the default behavior
is to remove nothing. You MUST provide a `key` function is you wish
to filter those.
:Example:
>>> class Test(object):
... def __init__(self, foo='bar'):
... self.foo = foo
... def __repr__(self):
... return "Test('%s')" % self.foo
...
>>> list(skip_duplicates([Test(), Test(), Test('other')]))
[Test('bar'), Test('bar'), Test('other')]
>>> list(skip_duplicates([Test(), Test(), Test('other')],\
lambda x: x.foo))
[Test('bar'), Test('other')]
def skip_duplicates(iterable, key=None, fingerprints=()):
# type: (Iterable, Callable, Any) -> Iterable
"""
Returns a generator that will yield all objects from iterable, skipping
duplicates.
Duplicates are identified using the `key` function to calculate a
unique fingerprint. This does not use natural equality, but the
result use a set() to remove duplicates, so defining __eq__
on your objects would have no effect.
By default the fingerprint is the object itself,
which ensure the functions works as-is with an iterable of primitives
such as int, str or tuple.
:Example:
>>> list(skip_duplicates([1, 2, 3, 4, 4, 2, 1, 3 , 4]))
[1, 2, 3, 4]
The return value of `key` MUST be hashable, which means for
non hashable objects such as dict, set or list, you need to specify
a a function that returns a hashable fingerprint.
:Example:
>>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)),
... lambda x: tuple(x)))
[[], [1, 2]]
>>> list(skip_duplicates(([], [], (), [1, 2], (1, 2)),
... lambda x: (type(x), tuple(x))))
[[], (), [1, 2], (1, 2)]
For more complex types, such as custom classes, the default behavior
is to remove nothing. You MUST provide a `key` function is you wish
to filter those.
:Example:
>>> class Test(object):
... def __init__(self, foo='bar'):
... self.foo = foo
... def __repr__(self):
... return "Test('%s')" % self.foo
...
>>> list(skip_duplicates([Test(), Test(), Test('other')]))
[Test('bar'), Test('bar'), Test('other')]
>>> list(skip_duplicates([Test(), Test(), Test('other')],\
lambda x: x.foo))
[Test('bar'), Test('other')]
"""
fingerprints = fingerprints or set()
fingerprint = None # needed on type errors unrelated to hashing
try:
# duplicate some code to gain perf in the most common case
if key is None:
for x in iterable:
if x not in fingerprints:
yield x
fingerprints.add(x)
else:
for x in iterable:
fingerprint = key(x)
if fingerprint not in fingerprints:
yield x
fingerprints.add(fingerprint)
except TypeError:
try:
hash(fingerprint)
except TypeError:
raise TypeError(
"The 'key' function returned a non hashable object of type "
"'%s' when receiving '%s'. Make sure this function always "
"returns a hashable object. Hint: immutable primitives like"
"int, str or tuple, are hashable while dict, set and list are "
"not." % (type(fingerprint), x))
else:
raise
|
Yields items from an iterator in iterable chunks.
def chunks(iterable, chunksize, cast=tuple):
# type: (Iterable, int, Callable) -> Iterable
"""
Yields items from an iterator in iterable chunks.
"""
it = iter(iterable)
while True:
yield cast(itertools.chain([next(it)],
itertools.islice(it, chunksize - 1)))
|
Yields iterms by bunch of a given size, but rolling only one item
in and out at a time when iterating.
>>> list(window([1, 2, 3]))
[(1, 2), (2, 3)]
By default, this will cast the window to a tuple before yielding it;
however, any function that will accept an iterable as its argument
is a valid target.
If you pass None as a cast value, the deque will be returned as-is,
which is more performant. However, since only one deque is used
for the entire iteration, you'll get the same reference everytime,
only the deque will contains different items. The result might not
be what you want :
>>> list(window([1, 2, 3], cast=None))
[deque([2, 3], maxlen=2), deque([2, 3], maxlen=2)]
def window(iterable, size=2, cast=tuple):
# type: (Iterable, int, Callable) -> Iterable
"""
Yields iterms by bunch of a given size, but rolling only one item
in and out at a time when iterating.
>>> list(window([1, 2, 3]))
[(1, 2), (2, 3)]
By default, this will cast the window to a tuple before yielding it;
however, any function that will accept an iterable as its argument
is a valid target.
If you pass None as a cast value, the deque will be returned as-is,
which is more performant. However, since only one deque is used
for the entire iteration, you'll get the same reference everytime,
only the deque will contains different items. The result might not
be what you want :
>>> list(window([1, 2, 3], cast=None))
[deque([2, 3], maxlen=2), deque([2, 3], maxlen=2)]
"""
iterable = iter(iterable)
d = deque(itertools.islice(iterable, size), size)
if cast:
yield cast(d)
for x in iterable:
d.append(x)
yield cast(d)
else:
yield d
for x in iterable:
d.append(x)
yield d
|
Return the item at the index of this iterable or raises IndexError.
WARNING: this will consume generators.
Negative indices are allowed but be aware they will cause n items to
be held in memory, where n = abs(index)
def at_index(iterable, index):
# type: (Iterable[T], int) -> T
"""" Return the item at the index of this iterable or raises IndexError.
WARNING: this will consume generators.
Negative indices are allowed but be aware they will cause n items to
be held in memory, where n = abs(index)
"""
try:
if index < 0:
return deque(iterable, maxlen=abs(index)).popleft()
return next(itertools.islice(iterable, index, index + 1))
except (StopIteration, IndexError) as e:
raise_from(IndexError('Index "%d" out of range' % index), e)
|
Return the first item of the iterable for which func(item) == True.
Or raises IndexError.
WARNING: this will consume generators.
def first_true(iterable, func):
# type: (Iterable[T], Callable) -> T
"""" Return the first item of the iterable for which func(item) == True.
Or raises IndexError.
WARNING: this will consume generators.
"""
try:
return next((x for x in iterable if func(x)))
except StopIteration as e:
# TODO: Find a better error message
raise_from(IndexError('No match for %s' % func), e)
|
Like itertools.islice, but accept int and callables.
If `start` is a callable, start the slice after the first time
start(item) == True.
If `stop` is a callable, stop the slice after the first time
stop(item) == True.
def iterslice(iterable, start=0, stop=None, step=1):
# type: (Iterable[T], int, int, int) -> Iterable[T]
""" Like itertools.islice, but accept int and callables.
If `start` is a callable, start the slice after the first time
start(item) == True.
If `stop` is a callable, stop the slice after the first time
stop(item) == True.
"""
if step < 0:
raise ValueError("The step can not be negative: '%s' given" % step)
if not isinstance(start, int):
# [Callable:Callable]
if not isinstance(stop, int) and stop:
return stops_when(starts_when(iterable, start), stop)
# [Callable:int]
return starts_when(itertools.islice(iterable, None, stop, step), start)
# [int:Callable]
if not isinstance(stop, int) and stop:
return stops_when(itertools.islice(iterable, start, None, step), stop)
# [int:int]
return itertools.islice(iterable, start, stop, step)
|
Lazily return the first x items from this iterable or default.
def firsts(iterable, items=1, default=None):
# type: (Iterable[T], int, T) -> Iterable[T]
""" Lazily return the first x items from this iterable or default. """
try:
items = int(items)
except (ValueError, TypeError):
raise ValueError("items should be usable as an int but is currently "
"'{}' of type '{}'".format(items, type(items)))
# TODO: replace this so that it returns lasts()
if items < 0:
raise ValueError(ww.f("items is {items} but should "
"be greater than 0. If you wish to get the last "
"items, use the lasts() function."))
i = 0
for i, item in zip(range(items), iterable):
yield item
for x in range(items - (i + 1)):
yield default
|
Lazily return the last x items from this iterable or default.
def lasts(iterable, items=1, default=None):
# type: (Iterable[T], int, T) -> Iterable[T]
""" Lazily return the last x items from this iterable or default. """
last_items = deque(iterable, maxlen=items)
for _ in range(items - len(last_items)):
yield default
for y in last_items:
yield y
|
Determine execution mode.
Legacy mode: <= v4.20181215
def is_legacy_server():
'''Determine execution mode.
Legacy mode: <= v4.20181215
'''
with Session() as session:
ret = session.Kernel.hello()
bai_version = ret['version']
legacy = True if bai_version <= 'v4.20181215' else False
return legacy
|
Terminates the session. It schedules the ``close()`` coroutine
of the underlying aiohttp session and then enqueues a sentinel
object to indicate termination. Then it waits until the worker
thread to self-terminate by joining.
def close(self):
'''
Terminates the session. It schedules the ``close()`` coroutine
of the underlying aiohttp session and then enqueues a sentinel
object to indicate termination. Then it waits until the worker
thread to self-terminate by joining.
'''
if self._closed:
return
self._closed = True
self._worker_thread.work_queue.put(self.aiohttp_session.close())
self._worker_thread.work_queue.put(self.worker_thread.sentinel)
self._worker_thread.join()
|
A proposed-but-not-implemented asyncio.run_forever() API based on
@vxgmichel's idea.
See discussions on https://github.com/python/asyncio/pull/465
def asyncio_run_forever(setup_coro, shutdown_coro, *,
stop_signals={signal.SIGINT}, debug=False):
'''
A proposed-but-not-implemented asyncio.run_forever() API based on
@vxgmichel's idea.
See discussions on https://github.com/python/asyncio/pull/465
'''
async def wait_for_stop():
loop = current_loop()
future = loop.create_future()
for stop_sig in stop_signals:
loop.add_signal_handler(stop_sig, future.set_result, stop_sig)
try:
recv_sig = await future
finally:
loop.remove_signal_handler(recv_sig)
loop = asyncio.new_event_loop()
try:
asyncio.set_event_loop(loop)
loop.set_debug(debug)
loop.run_until_complete(setup_coro)
loop.run_until_complete(wait_for_stop())
finally:
try:
loop.run_until_complete(shutdown_coro)
_cancel_all_tasks(loop)
if hasattr(loop, 'shutdown_asyncgens'): # Python 3.6+
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
asyncio.set_event_loop(None)
loop.close()
|
claar all the cache, and release memory
def clear(self):
'''
claar all the cache, and release memory
'''
for node in self.dli():
node.empty = True
node.key = None
node.value = None
self.head = _dlnode()
self.head.next = self.head
self.head.prev = self.head
self.listSize = 1
self.table.clear()
# status var
self.hit_cnt = 0
self.miss_cnt = 0
self.remove_cnt = 0
|
Delete the item
def pop(self, key, default = None):
"""Delete the item"""
node = self.get(key, None)
if node == None:
value = default
else:
value = node
try:
del self[key]
except:
return value
return value
|
Main function.
:return:
None.
def main():
"""
Main function.
:return:
None.
"""
try:
# Get the `src` directory's absolute path
src_path = os.path.dirname(
# `aoiklivereload` directory's absolute path
os.path.dirname(
# `demo` directory's absolute path
os.path.dirname(
# This file's absolute path
os.path.abspath(__file__)
)
)
)
# If the `src` directory path is not in `sys.path`
if src_path not in sys.path:
# Add to `sys.path`.
#
# This aims to save user setting PYTHONPATH when running this demo.
#
sys.path.append(src_path)
# Import reloader class
from aoiklivereload import LiveReloader
# Create reloader
reloader = LiveReloader()
# Start watcher thread
reloader.start_watcher_thread()
# Server host
server_host = '0.0.0.0'
# Server port
server_port = 8000
# Get message
msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format(
server_host, server_port
)
# Print message
print(msg)
# Create request handler
@bottle.get('/')
def hello_handler(): # pylint: disable=unused-variable
"""
Request handler.
:return:
Response body.
"""
# Return response body
return 'hello'
# Run server
bottle.run(host=server_host, port=server_port)
# If have `KeyboardInterrupt`
except KeyboardInterrupt:
# Not treat as error
pass
|
Get-or-creates a compute session.
If *client_token* is ``None``, it creates a new compute session as long as
the server has enough resources and your API key has remaining quota.
If *client_token* is a valid string and there is an existing compute session
with the same token and the same *lang*, then it returns the :class:`Kernel`
instance representing the existing session.
:param lang: The image name and tag for the compute session.
Example: ``python:3.6-ubuntu``.
Check out the full list of available images in your server using (TODO:
new API).
:param client_token: A client-side identifier to seamlessly reuse the compute
session already created.
:param mounts: The list of vfolder names that belongs to the currrent API
access key.
:param envs: The environment variables which always bypasses the jail policy.
:param resources: The resource specification. (TODO: details)
:param cluster_size: The number of containers in this compute session.
Must be at least 1.
:param tag: An optional string to annotate extra information.
:param owner: An optional access key that owns the created session. (Only
available to administrators)
:returns: The :class:`Kernel` instance.
async def get_or_create(cls, lang: str, *,
client_token: str = None,
mounts: Iterable[str] = None,
envs: Mapping[str, str] = None,
resources: Mapping[str, int] = None,
cluster_size: int = 1,
tag: str = None,
owner_access_key: str = None) -> 'Kernel':
'''
Get-or-creates a compute session.
If *client_token* is ``None``, it creates a new compute session as long as
the server has enough resources and your API key has remaining quota.
If *client_token* is a valid string and there is an existing compute session
with the same token and the same *lang*, then it returns the :class:`Kernel`
instance representing the existing session.
:param lang: The image name and tag for the compute session.
Example: ``python:3.6-ubuntu``.
Check out the full list of available images in your server using (TODO:
new API).
:param client_token: A client-side identifier to seamlessly reuse the compute
session already created.
:param mounts: The list of vfolder names that belongs to the currrent API
access key.
:param envs: The environment variables which always bypasses the jail policy.
:param resources: The resource specification. (TODO: details)
:param cluster_size: The number of containers in this compute session.
Must be at least 1.
:param tag: An optional string to annotate extra information.
:param owner: An optional access key that owns the created session. (Only
available to administrators)
:returns: The :class:`Kernel` instance.
'''
if client_token:
assert 4 <= len(client_token) <= 64, \
'Client session token should be 4 to 64 characters long.'
else:
client_token = uuid.uuid4().hex
if mounts is None:
mounts = []
if resources is None:
resources = {}
mounts.extend(cls.session.config.vfolder_mounts)
rqst = Request(cls.session, 'POST', '/kernel/create')
rqst.set_json({
'lang': lang,
'tag': tag,
'clientSessionToken': client_token,
'config': {
'mounts': mounts,
'environ': envs,
'clusterSize': cluster_size,
'resources': resources,
},
})
async with rqst.fetch() as resp:
data = await resp.json()
o = cls(data['kernelId'], owner_access_key) # type: ignore
o.created = data.get('created', True) # True is for legacy
o.service_ports = data.get('servicePorts', [])
return o
|
Destroys the compute session.
Since the server literally kills the container(s), all ongoing executions are
forcibly interrupted.
async def destroy(self):
'''
Destroys the compute session.
Since the server literally kills the container(s), all ongoing executions are
forcibly interrupted.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
rqst = Request(self.session,
'DELETE', '/kernel/{}'.format(self.kernel_id),
params=params)
async with rqst.fetch() as resp:
if resp.status == 200:
return await resp.json()
|
Restarts the compute session.
The server force-destroys the current running container(s), but keeps their
temporary scratch directories intact.
async def restart(self):
'''
Restarts the compute session.
The server force-destroys the current running container(s), but keeps their
temporary scratch directories intact.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
rqst = Request(self.session,
'PATCH', '/kernel/{}'.format(self.kernel_id),
params=params)
async with rqst.fetch():
pass
|
Gets the auto-completion candidates from the given code string,
as if a user has pressed the tab key just after the code in
IDEs.
Depending on the language of the compute session, this feature
may not be supported. Unsupported sessions returns an empty list.
:param code: An (incomplete) code text.
:param opts: Additional information about the current cursor position,
such as row, col, line and the remainder text.
:returns: An ordered list of strings.
async def complete(self, code: str, opts: dict = None) -> Iterable[str]:
'''
Gets the auto-completion candidates from the given code string,
as if a user has pressed the tab key just after the code in
IDEs.
Depending on the language of the compute session, this feature
may not be supported. Unsupported sessions returns an empty list.
:param code: An (incomplete) code text.
:param opts: Additional information about the current cursor position,
such as row, col, line and the remainder text.
:returns: An ordered list of strings.
'''
opts = {} if opts is None else opts
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
rqst = Request(self.session,
'POST', '/kernel/{}/complete'.format(self.kernel_id),
params=params)
rqst.set_json({
'code': code,
'options': {
'row': int(opts.get('row', 0)),
'col': int(opts.get('col', 0)),
'line': opts.get('line', ''),
'post': opts.get('post', ''),
},
})
async with rqst.fetch() as resp:
return await resp.json()
|
Retrieves a brief information about the compute session.
async def get_info(self):
'''
Retrieves a brief information about the compute session.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
rqst = Request(self.session,
'GET', '/kernel/{}'.format(self.kernel_id),
params=params)
async with rqst.fetch() as resp:
return await resp.json()
|
Executes a code snippet directly in the compute session or sends a set of
build/clean/execute commands to the compute session.
For more details about using this API, please refer :doc:`the official API
documentation <user-api/intro>`.
:param run_id: A unique identifier for a particular run loop. In the
first call, it may be ``None`` so that the server auto-assigns one.
Subsequent calls must use the returned ``runId`` value to request
continuation or to send user inputs.
:param code: A code snippet as string. In the continuation requests, it
must be an empty string. When sending user inputs, this is where the
user input string is stored.
:param mode: A constant string which is one of ``"query"``, ``"batch"``,
``"continue"``, and ``"user-input"``.
:param opts: A dict for specifying additional options. Mainly used in the
batch mode to specify build/clean/execution commands.
See :ref:`the API object reference <batch-execution-query-object>`
for details.
:returns: :ref:`An execution result object <execution-result-object>`
async def execute(self, run_id: str = None,
code: str = None,
mode: str = 'query',
opts: dict = None):
'''
Executes a code snippet directly in the compute session or sends a set of
build/clean/execute commands to the compute session.
For more details about using this API, please refer :doc:`the official API
documentation <user-api/intro>`.
:param run_id: A unique identifier for a particular run loop. In the
first call, it may be ``None`` so that the server auto-assigns one.
Subsequent calls must use the returned ``runId`` value to request
continuation or to send user inputs.
:param code: A code snippet as string. In the continuation requests, it
must be an empty string. When sending user inputs, this is where the
user input string is stored.
:param mode: A constant string which is one of ``"query"``, ``"batch"``,
``"continue"``, and ``"user-input"``.
:param opts: A dict for specifying additional options. Mainly used in the
batch mode to specify build/clean/execution commands.
See :ref:`the API object reference <batch-execution-query-object>`
for details.
:returns: :ref:`An execution result object <execution-result-object>`
'''
opts = opts if opts is not None else {}
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
if mode in {'query', 'continue', 'input'}:
assert code is not None, \
'The code argument must be a valid string even when empty.'
rqst = Request(self.session,
'POST', '/kernel/{}'.format(self.kernel_id),
params=params)
rqst.set_json({
'mode': mode,
'code': code,
'runId': run_id,
})
elif mode == 'batch':
rqst = Request(self.session,
'POST', '/kernel/{}'.format(self.kernel_id),
params=params)
rqst.set_json({
'mode': mode,
'code': code,
'runId': run_id,
'options': {
'clean': opts.get('clean', None),
'build': opts.get('build', None),
'buildLog': bool(opts.get('buildLog', False)),
'exec': opts.get('exec', None),
},
})
elif mode == 'complete':
rqst = Request(self.session,
'POST', '/kernel/{}/complete'.format(self.kernel_id),
params=params)
rqst.set_json({
'code': code,
'options': {
'row': int(opts.get('row', 0)),
'col': int(opts.get('col', 0)),
'line': opts.get('line', ''),
'post': opts.get('post', ''),
},
})
else:
raise BackendClientError('Invalid execution mode: {0}'.format(mode))
async with rqst.fetch() as resp:
return (await resp.json())['result']
|
Uploads the given list of files to the compute session.
You may refer them in the batch-mode execution or from the code
executed in the server afterwards.
:param files: The list of file paths in the client-side.
If the paths include directories, the location of them in the compute
session is calculated from the relative path to *basedir* and all
intermediate parent directories are automatically created if not exists.
For example, if a file path is ``/home/user/test/data.txt`` (or
``test/data.txt``) where *basedir* is ``/home/user`` (or the current
working directory is ``/home/user``), the uploaded file is located at
``/home/work/test/data.txt`` in the compute session container.
:param basedir: The directory prefix where the files reside.
The default value is the current working directory.
:param show_progress: Displays a progress bar during uploads.
async def upload(self, files: Sequence[Union[str, Path]],
basedir: Union[str, Path] = None,
show_progress: bool = False):
'''
Uploads the given list of files to the compute session.
You may refer them in the batch-mode execution or from the code
executed in the server afterwards.
:param files: The list of file paths in the client-side.
If the paths include directories, the location of them in the compute
session is calculated from the relative path to *basedir* and all
intermediate parent directories are automatically created if not exists.
For example, if a file path is ``/home/user/test/data.txt`` (or
``test/data.txt``) where *basedir* is ``/home/user`` (or the current
working directory is ``/home/user``), the uploaded file is located at
``/home/work/test/data.txt`` in the compute session container.
:param basedir: The directory prefix where the files reside.
The default value is the current working directory.
:param show_progress: Displays a progress bar during uploads.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
base_path = (Path.cwd() if basedir is None
else Path(basedir).resolve())
files = [Path(file).resolve() for file in files]
total_size = 0
for file_path in files:
total_size += file_path.stat().st_size
tqdm_obj = tqdm(desc='Uploading files',
unit='bytes', unit_scale=True,
total=total_size,
disable=not show_progress)
with tqdm_obj:
attachments = []
for file_path in files:
try:
attachments.append(AttachedFile(
str(file_path.relative_to(base_path)),
ProgressReportingReader(str(file_path),
tqdm_instance=tqdm_obj),
'application/octet-stream',
))
except ValueError:
msg = 'File "{0}" is outside of the base directory "{1}".' \
.format(file_path, base_path)
raise ValueError(msg) from None
rqst = Request(self.session,
'POST', '/kernel/{}/upload'.format(self.kernel_id),
params=params)
rqst.attach_files(attachments)
async with rqst.fetch() as resp:
return resp
|
Downloads the given list of files from the compute session.
:param files: The list of file paths in the compute session.
If they are relative paths, the path is calculated from
``/home/work`` in the compute session container.
:param dest: The destination directory in the client-side.
:param show_progress: Displays a progress bar during downloads.
async def download(self, files: Sequence[Union[str, Path]],
dest: Union[str, Path] = '.',
show_progress: bool = False):
'''
Downloads the given list of files from the compute session.
:param files: The list of file paths in the compute session.
If they are relative paths, the path is calculated from
``/home/work`` in the compute session container.
:param dest: The destination directory in the client-side.
:param show_progress: Displays a progress bar during downloads.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
rqst = Request(self.session,
'GET', '/kernel/{}/download'.format(self.kernel_id),
params=params)
rqst.set_json({
'files': [*map(str, files)],
})
async with rqst.fetch() as resp:
chunk_size = 1 * 1024
file_names = None
tqdm_obj = tqdm(desc='Downloading files',
unit='bytes', unit_scale=True,
total=resp.content.total_bytes,
disable=not show_progress)
with tqdm_obj as pbar:
fp = None
while True:
chunk = await resp.aread(chunk_size)
if not chunk:
break
pbar.update(len(chunk))
# TODO: more elegant parsing of multipart response?
for part in chunk.split(b'\r\n'):
if part.startswith(b'--'):
if fp:
fp.close()
with tarfile.open(fp.name) as tarf:
tarf.extractall(path=dest)
file_names = tarf.getnames()
os.unlink(fp.name)
fp = tempfile.NamedTemporaryFile(suffix='.tar',
delete=False)
elif part.startswith(b'Content-') or part == b'':
continue
else:
fp.write(part)
if fp:
fp.close()
os.unlink(fp.name)
result = {'file_names': file_names}
return result
|
Gets the list of files in the given path inside the compute session
container.
:param path: The directory path in the compute session.
async def list_files(self, path: Union[str, Path] = '.'):
'''
Gets the list of files in the given path inside the compute session
container.
:param path: The directory path in the compute session.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
rqst = Request(self.session,
'GET', '/kernel/{}/files'.format(self.kernel_id),
params=params)
rqst.set_json({
'path': path,
})
async with rqst.fetch() as resp:
return await resp.json()
|
Opens a pseudo-terminal of the kernel (if supported) streamed via
websockets.
:returns: a :class:`StreamPty` object.
def stream_pty(self) -> 'StreamPty':
'''
Opens a pseudo-terminal of the kernel (if supported) streamed via
websockets.
:returns: a :class:`StreamPty` object.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
request = Request(self.session,
'GET', '/stream/kernel/{}/pty'.format(self.kernel_id),
params=params)
return request.connect_websocket(response_cls=StreamPty)
|
Executes a code snippet in the streaming mode.
Since the returned websocket represents a run loop, there is no need to
specify *run_id* explicitly.
def stream_execute(self, code: str = '', *,
mode: str = 'query',
opts: dict = None) -> WebSocketResponse:
'''
Executes a code snippet in the streaming mode.
Since the returned websocket represents a run loop, there is no need to
specify *run_id* explicitly.
'''
params = {}
if self.owner_access_key:
params['owner_access_key'] = self.owner_access_key
opts = {} if opts is None else opts
if mode == 'query':
opts = {}
elif mode == 'batch':
opts = {
'clean': opts.get('clean', None),
'build': opts.get('build', None),
'buildLog': bool(opts.get('buildLog', False)),
'exec': opts.get('exec', None),
}
else:
msg = 'Invalid stream-execution mode: {0}'.format(mode)
raise BackendClientError(msg)
request = Request(self.session,
'GET', '/stream/kernel/{}/execute'.format(self.kernel_id),
params=params)
async def send_code(ws):
await ws.send_json({
'code': code,
'mode': mode,
'options': opts,
})
return request.connect_websocket(on_enter=send_code)
|
Grab the ~/.polyglot/.env file for variables
If you are running Polyglot v2 on this same machine
then it should already exist. If not create it.
def init_interface():
sys.stdout = LoggerWriter(LOGGER.debug)
sys.stderr = LoggerWriter(LOGGER.error)
"""
Grab the ~/.polyglot/.env file for variables
If you are running Polyglot v2 on this same machine
then it should already exist. If not create it.
"""
warnings.simplefilter('error', UserWarning)
try:
load_dotenv(join(expanduser("~") + '/.polyglot/.env'))
except (UserWarning) as err:
LOGGER.warning('File does not exist: {}.'.format(join(expanduser("~") + '/.polyglot/.env')), exc_info=True)
# sys.exit(1)
warnings.resetwarnings()
"""
If this NodeServer is co-resident with Polyglot it will receive a STDIN config on startup
that looks like:
{"token":"2cb40e507253fc8f4cbbe247089b28db79d859cbed700ec151",
"mqttHost":"localhost","mqttPort":"1883","profileNum":"10"}
"""
init = select.select([sys.stdin], [], [], 1)[0]
if init:
line = sys.stdin.readline()
try:
line = json.loads(line)
os.environ['PROFILE_NUM'] = line['profileNum']
os.environ['MQTT_HOST'] = line['mqttHost']
os.environ['MQTT_PORT'] = line['mqttPort']
os.environ['TOKEN'] = line['token']
LOGGER.info('Received Config from STDIN.')
except (Exception) as err:
# e = sys.exc_info()[0]
LOGGER.error('Invalid formatted input. Skipping. %s', err, exc_info=True)
|
The callback for when the client receives a CONNACK response from the server.
Subscribing in on_connect() means that if we lose the connection and
reconnect then subscriptions will be renewed.
:param mqttc: The client instance for this callback
:param userdata: The private userdata for the mqtt client. Not used in Polyglot
:param flags: The flags set on the connection.
:param rc: Result code of connection, 0 = Success, anything else is a failure
def _connect(self, mqttc, userdata, flags, rc):
"""
The callback for when the client receives a CONNACK response from the server.
Subscribing in on_connect() means that if we lose the connection and
reconnect then subscriptions will be renewed.
:param mqttc: The client instance for this callback
:param userdata: The private userdata for the mqtt client. Not used in Polyglot
:param flags: The flags set on the connection.
:param rc: Result code of connection, 0 = Success, anything else is a failure
"""
if rc == 0:
self.connected = True
results = []
LOGGER.info("MQTT Connected with result code " + str(rc) + " (Success)")
# result, mid = self._mqttc.subscribe(self.topicInput)
results.append((self.topicInput, tuple(self._mqttc.subscribe(self.topicInput))))
results.append((self.topicPolyglotConnection, tuple(self._mqttc.subscribe(self.topicPolyglotConnection))))
for (topic, (result, mid)) in results:
if result == 0:
LOGGER.info("MQTT Subscribing to topic: " + topic + " - " + " MID: " + str(mid) + " Result: " + str(result))
else:
LOGGER.info("MQTT Subscription to " + topic + " failed. This is unusual. MID: " + str(mid) + " Result: " + str(result))
# If subscription fails, try to reconnect.
self._mqttc.reconnect()
self._mqttc.publish(self.topicSelfConnection, json.dumps(
{
'connected': True,
'node': self.profileNum
}), retain=True)
LOGGER.info('Sent Connected message to Polyglot')
else:
LOGGER.error("MQTT Failed to connect. Result code: " + str(rc))
|
The callback for when a PUBLISH message is received from the server.
:param mqttc: The client instance for this callback
:param userdata: The private userdata for the mqtt client. Not used in Polyglot
:param flags: The flags set on the connection.
:param msg: Dictionary of MQTT received message. Uses: msg.topic, msg.qos, msg.payload
def _message(self, mqttc, userdata, msg):
"""
The callback for when a PUBLISH message is received from the server.
:param mqttc: The client instance for this callback
:param userdata: The private userdata for the mqtt client. Not used in Polyglot
:param flags: The flags set on the connection.
:param msg: Dictionary of MQTT received message. Uses: msg.topic, msg.qos, msg.payload
"""
try:
inputCmds = ['query', 'command', 'result', 'status', 'shortPoll', 'longPoll', 'delete']
parsed_msg = json.loads(msg.payload.decode('utf-8'))
if 'node' in parsed_msg:
if parsed_msg['node'] != 'polyglot':
return
del parsed_msg['node']
for key in parsed_msg:
# LOGGER.debug('MQTT Received Message: {}: {}'.format(msg.topic, parsed_msg))
if key == 'config':
self.inConfig(parsed_msg[key])
elif key == 'connected':
self.polyglotConnected = parsed_msg[key]
elif key == 'stop':
LOGGER.debug('Received stop from Polyglot... Shutting Down.')
self.stop()
elif key in inputCmds:
self.input(parsed_msg)
else:
LOGGER.error('Invalid command received in message from Polyglot: {}'.format(key))
except (ValueError) as err:
LOGGER.error('MQTT Received Payload Error: {}'.format(err), exc_info=True)
|
The callback for when a DISCONNECT occurs.
:param mqttc: The client instance for this callback
:param userdata: The private userdata for the mqtt client. Not used in Polyglot
:param rc: Result code of connection, 0 = Graceful, anything else is unclean
def _disconnect(self, mqttc, userdata, rc):
"""
The callback for when a DISCONNECT occurs.
:param mqttc: The client instance for this callback
:param userdata: The private userdata for the mqtt client. Not used in Polyglot
:param rc: Result code of connection, 0 = Graceful, anything else is unclean
"""
self.connected = False
if rc != 0:
LOGGER.info("MQTT Unexpected disconnection. Trying reconnect.")
try:
self._mqttc.reconnect()
except Exception as ex:
template = "An exception of type {0} occured. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
LOGGER.error("MQTT Connection error: " + message)
else:
LOGGER.info("MQTT Graceful disconnection.")
|
The client start method. Starts the thread for the MQTT Client
and publishes the connected message.
def _startMqtt(self):
"""
The client start method. Starts the thread for the MQTT Client
and publishes the connected message.
"""
LOGGER.info('Connecting to MQTT... {}:{}'.format(self._server, self._port))
try:
# self._mqttc.connect_async(str(self._server), int(self._port), 10)
self._mqttc.connect_async('{}'.format(self._server), int(self._port), 10)
self._mqttc.loop_forever()
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
LOGGER.error("MQTT Connection error: {}".format(message), exc_info=True)
|
The client stop method. If the client is currently connected
stop the thread and disconnect. Publish the disconnected
message if clean shutdown.
def stop(self):
"""
The client stop method. If the client is currently connected
stop the thread and disconnect. Publish the disconnected
message if clean shutdown.
"""
# self.loop.call_soon_threadsafe(self.loop.stop)
# self.loop.stop()
# self._longPoll.cancel()
# self._shortPoll.cancel()
if self.connected:
LOGGER.info('Disconnecting from MQTT... {}:{}'.format(self._server, self._port))
self._mqttc.publish(self.topicSelfConnection, json.dumps({'node': self.profileNum, 'connected': False}), retain=True)
self._mqttc.loop_stop()
self._mqttc.disconnect()
try:
for watcher in self.__stopObservers:
watcher()
except KeyError as e:
LOGGER.exception('KeyError in gotConfig: {}'.format(e), exc_info=True)
|
Formatted Message to send to Polyglot. Connection messages are sent automatically from this module
so this method is used to send commands to/from Polyglot and formats it for consumption
def send(self, message):
"""
Formatted Message to send to Polyglot. Connection messages are sent automatically from this module
so this method is used to send commands to/from Polyglot and formats it for consumption
"""
if not isinstance(message, dict) and self.connected:
warnings.warn('payload not a dictionary')
return False
try:
message['node'] = self.profileNum
self._mqttc.publish(self.topicInput, json.dumps(message), retain=False)
except TypeError as err:
LOGGER.error('MQTT Send Error: {}'.format(err), exc_info=True)
|
Add a node to the NodeServer
:param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
def addNode(self, node):
"""
Add a node to the NodeServer
:param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
"""
LOGGER.info('Adding node {}({})'.format(node.name, node.address))
message = {
'addnode': {
'nodes': [{
'address': node.address,
'name': node.name,
'node_def_id': node.id,
'primary': node.primary,
'drivers': node.drivers,
'hint': node.hint
}]
}
}
self.send(message)
|
Send custom dictionary to Polyglot to save and be retrieved on startup.
:param data: Dictionary of key value pairs to store in Polyglot database.
def saveCustomData(self, data):
"""
Send custom dictionary to Polyglot to save and be retrieved on startup.
:param data: Dictionary of key value pairs to store in Polyglot database.
"""
LOGGER.info('Sending customData to Polyglot.')
message = { 'customdata': data }
self.send(message)
|
Send custom dictionary to Polyglot to save and be retrieved on startup.
:param data: Dictionary of key value pairs to store in Polyglot database.
def saveCustomParams(self, data):
"""
Send custom dictionary to Polyglot to save and be retrieved on startup.
:param data: Dictionary of key value pairs to store in Polyglot database.
"""
LOGGER.info('Sending customParams to Polyglot.')
message = { 'customparams': data }
self.send(message)
|
Add custom notice to front-end for this NodeServers
:param data: String of characters to add as a notification in the front-end.
def addNotice(self, data):
"""
Add custom notice to front-end for this NodeServers
:param data: String of characters to add as a notification in the front-end.
"""
LOGGER.info('Sending addnotice to Polyglot: {}'.format(data))
message = { 'addnotice': data }
self.send(message)
|
Add custom notice to front-end for this NodeServers
:param data: Index of notices list to remove.
def removeNotice(self, data):
"""
Add custom notice to front-end for this NodeServers
:param data: Index of notices list to remove.
"""
LOGGER.info('Sending removenotice to Polyglot for index {}'.format(data))
message = { 'removenotice': data }
self.send(message)
|
Delete a node from the NodeServer
:param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
def delNode(self, address):
"""
Delete a node from the NodeServer
:param node: Dictionary of node settings. Keys: address, name, node_def_id, primary, and drivers are required.
"""
LOGGER.info('Removing node {}'.format(address))
message = {
'removenode': {
'address': address
}
}
self.send(message)
|
Get Node by Address of existing nodes.
def getNode(self, address):
"""
Get Node by Address of existing nodes.
"""
try:
for node in self.config['nodes']:
if node['address'] == address:
return node
return False
except KeyError:
LOGGER.error('Usually means we have not received the config yet.', exc_info=True)
return False
|
Save incoming config received from Polyglot to Interface.config and then do any functions
that are waiting on the config to be received.
def inConfig(self, config):
"""
Save incoming config received from Polyglot to Interface.config and then do any functions
that are waiting on the config to be received.
"""
self.config = config
self.isyVersion = config['isyVersion']
try:
for watcher in self.__configObservers:
watcher(config)
self.send_custom_config_docs()
except KeyError as e:
LOGGER.error('KeyError in gotConfig: {}'.format(e), exc_info=True)
|
Send custom parameters descriptions to Polyglot to be used
in front end UI configuration screen
Accepts list of objects with the followin properties
name - used as a key when data is sent from UI
title - displayed in UI
defaultValue - optionanl
type - optional, can be 'NUMBER', 'STRING' or 'BOOLEAN'.
Defaults to 'STRING'
desc - optional, shown in tooltip in UI
isRequired - optional, True/False, when set, will not validate UI
input if it's empty
isList - optional, True/False, if set this will be treated as list
of values or objects by UI
params - optional, can contain a list of objects. If present, then
this (parent) is treated as object / list of objects by UI,
otherwise, it's treated as a single / list of single values
def save_typed_params(self, data):
"""
Send custom parameters descriptions to Polyglot to be used
in front end UI configuration screen
Accepts list of objects with the followin properties
name - used as a key when data is sent from UI
title - displayed in UI
defaultValue - optionanl
type - optional, can be 'NUMBER', 'STRING' or 'BOOLEAN'.
Defaults to 'STRING'
desc - optional, shown in tooltip in UI
isRequired - optional, True/False, when set, will not validate UI
input if it's empty
isList - optional, True/False, if set this will be treated as list
of values or objects by UI
params - optional, can contain a list of objects. If present, then
this (parent) is treated as object / list of objects by UI,
otherwise, it's treated as a single / list of single values
"""
LOGGER.info('Sending typed parameters to Polyglot.')
if type(data) is not list:
data = [ data ]
message = { 'typedparams': data }
self.send(message)
|
Just send it along if requested, should be able to delete the node even if it isn't
in our config anywhere. Usually used for normalization.
def delNode(self, address):
"""
Just send it along if requested, should be able to delete the node even if it isn't
in our config anywhere. Usually used for normalization.
"""
if address in self.nodes:
del self.nodes[address]
self.poly.delNode(address)
|
Sends the GraphQL query and returns the response.
:param query: The GraphQL query string.
:param variables: An optional key-value dictionary
to fill the interpolated template variables
in the query.
:returns: The object parsed from the response JSON string.
async def query(cls, query: str,
variables: Optional[Mapping[str, Any]] = None,
) -> Any:
'''
Sends the GraphQL query and returns the response.
:param query: The GraphQL query string.
:param variables: An optional key-value dictionary
to fill the interpolated template variables
in the query.
:returns: The object parsed from the response JSON string.
'''
gql_query = {
'query': query,
'variables': variables if variables else {},
}
rqst = Request(cls.session, 'POST', '/admin/graphql')
rqst.set_json(gql_query)
async with rqst.fetch() as resp:
return await resp.json()
|
Returns human readable string from number of seconds
def get_readable_time_string(seconds):
"""Returns human readable string from number of seconds"""
seconds = int(seconds)
minutes = seconds // 60
seconds = seconds % 60
hours = minutes // 60
minutes = minutes % 60
days = hours // 24
hours = hours % 24
result = ""
if days > 0:
result += "%d %s " % (days, "Day" if (days == 1) else "Days")
if hours > 0:
result += "%d %s " % (hours, "Hour" if (hours == 1) else "Hours")
if minutes > 0:
result += "%d %s " % (minutes, "Minute" if (minutes == 1) else "Minutes")
if seconds > 0:
result += "%d %s " % (seconds, "Second" if (seconds == 1) else "Seconds")
return result.strip()
|
Returns a list of rate limit information from a given response's headers.
def get_rate_limits(response):
"""Returns a list of rate limit information from a given response's headers."""
periods = response.headers['X-RateLimit-Period']
if not periods:
return []
rate_limits = []
periods = periods.split(',')
limits = response.headers['X-RateLimit-Limit'].split(',')
remaining = response.headers['X-RateLimit-Remaining'].split(',')
reset = response.headers['X-RateLimit-Reset'].split(',')
for idx, period in enumerate(periods):
rate_limit = {}
limit_period = get_readable_time_string(period)
rate_limit["period"] = limit_period
rate_limit["period_seconds"] = period
rate_limit["request_limit"] = limits[idx]
rate_limit["requests_remaining"] = remaining[idx]
reset_datetime = get_datetime_from_timestamp(reset[idx])
rate_limit["reset"] = reset_datetime
right_now = datetime.now()
if (reset_datetime is not None) and (right_now < reset_datetime):
# add 1 second because of rounding
seconds_remaining = (reset_datetime - right_now).seconds + 1
else:
seconds_remaining = 0
rate_limit["reset_in_seconds"] = seconds_remaining
rate_limit["time_to_reset"] = get_readable_time_string(seconds_remaining)
rate_limits.append(rate_limit)
return rate_limits
|
Return key, self[key] as generator for key in keys.
Raise KeyError if a key does not exist
Args:
keys: Iterable containing keys
Example:
>>> from ww import d
>>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3))
[(1, 1), (3, 3)]
def isubset(self, *keys):
# type: (*Hashable) -> ww.g
"""Return key, self[key] as generator for key in keys.
Raise KeyError if a key does not exist
Args:
keys: Iterable containing keys
Example:
>>> from ww import d
>>> list(d({1: 1, 2: 2, 3: 3}).isubset(1, 3))
[(1, 1), (3, 3)]
"""
return ww.g((key, self[key]) for key in keys)
|
Swap key and value
/!\ Be carreful, if there are duplicate values, only one will
survive /!\
Example:
>>> from ww import d
>>> d({1: 2, 2: 2, 3: 3}).swap()
{2: 2, 3: 3}
def swap(self):
# type: () -> DictWrapper
"""Swap key and value
/!\ Be carreful, if there are duplicate values, only one will
survive /!\
Example:
>>> from ww import d
>>> d({1: 2, 2: 2, 3: 3}).swap()
{2: 2, 3: 3}
"""
return self.__class__((v, k) for k, v in self.items())
|
Create a new d from
Args:
iterable: Iterable containing keys
value: value to associate with each key.
If callable, will be value[key]
Returns: new DictWrapper
Example:
>>> from ww import d
>>> sorted(d.fromkeys('123', value=4).items())
[('1', 4), ('2', 4), ('3', 4)]
>>> sorted(d.fromkeys(range(3), value=lambda e:e**2).items())
[(0, 0), (1, 1), (2, 4)]
def fromkeys(cls, iterable, value=None):
# TODO : type: (Iterable, Union[Any, Callable]) -> DictWrapper
# https://github.com/python/mypy/issues/2254
"""Create a new d from
Args:
iterable: Iterable containing keys
value: value to associate with each key.
If callable, will be value[key]
Returns: new DictWrapper
Example:
>>> from ww import d
>>> sorted(d.fromkeys('123', value=4).items())
[('1', 4), ('2', 4), ('3', 4)]
>>> sorted(d.fromkeys(range(3), value=lambda e:e**2).items())
[(0, 0), (1, 1), (2, 4)]
"""
if not callable(value):
return cls(dict.fromkeys(iterable, value))
return cls((key, value(key)) for key in iterable)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.