sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
|---|---|---|
def virtualenv_setup(
ctx,
python,
inputs=None,
outputs=None,
touch=None,
check_import=False,
pip_setup_file=None,
pip_setup_touch=None,
cache_key=None,
always=False,
):
"""
Create task that sets up `virtualenv` package.
:param ctx: BuildContext object.
:param python: Python program path.
:param inputs: Input items list to add to created task.
See :paramref:`create_cmd_task.inputs` for allowed item types.
:param outputs: Output items list to add to created task.
See :paramref:`create_cmd_task.outputs` for allowed item types.
:param touch: Touch file path for dirty checking.
:param check_import: Whether import module for dirty checking.
:param pip_setup_file: `get-pip.py` file path for `pip_setup` task.
:param pip_setup_touch: Touch file path for `pip_setup` task.
:param cache_key: Task cache key.
:param always: Whether always run.
:return: Created task.
"""
# Ensure given context object is BuildContext object
_ensure_build_context(ctx)
# If `get-pip.py` file path is not given
if pip_setup_file is None:
# Not create task that sets up `pip`
pip_setup_task = None
# If `get-pip.py` file path is given
else:
# Create task that sets up `pip`
pip_setup_task = pip_setup(
# Context
ctx=ctx,
# Python program path
python=python,
# `get-pip.py` file path
setup_file=pip_setup_file,
# Touch file path
touch=pip_setup_touch,
# Whether import module for dirty checking
check_import=check_import,
# Whether always run
always=always,
)
# If touch file path is not given
if touch is None:
# Not update touch file
touch_node = None
else:
# Update touch file
touch_node, always = update_touch_file(
# Context
ctx=ctx,
# Touch file path
path=touch,
# Whether import module for dirty checking
check_import=check_import,
# Module name to import for dirty checking
check_import_module='virtualenv',
# Python program path for dirty checking
check_import_python=python,
# Whether always run
always=always,
)
# Create task that sets up `virtualenv` package
task = create_cmd_task(
# Context
ctx=ctx,
# Command parts
parts=[
# Python program path
python,
# Run module
'-m',
# Module name
'pip',
# Install package
'install',
# Package name
'virtualenv',
],
# Input items list
inputs=[
# Run after the task that sets up `pip`
pip_setup_task,
# Given input items list
inputs,
],
# Output items list
outputs=[
# Use the touch node as output target for dirty checking
touch_node,
# Given output items list
outputs,
],
# Whether always run
always=always,
# Task cache key
cache_key=cache_key or (python, 'virtualenv'),
)
# Return the created task
return task
|
Create task that sets up `virtualenv` package.
:param ctx: BuildContext object.
:param python: Python program path.
:param inputs: Input items list to add to created task.
See :paramref:`create_cmd_task.inputs` for allowed item types.
:param outputs: Output items list to add to created task.
See :paramref:`create_cmd_task.outputs` for allowed item types.
:param touch: Touch file path for dirty checking.
:param check_import: Whether import module for dirty checking.
:param pip_setup_file: `get-pip.py` file path for `pip_setup` task.
:param pip_setup_touch: Touch file path for `pip_setup` task.
:param cache_key: Task cache key.
:param always: Whether always run.
:return: Created task.
|
entailment
|
def create_venv(
ctx,
python,
venv_path,
inputs=None,
outputs=None,
pip_setup_file=None,
pip_setup_touch=None,
virtualenv_setup_touch=None,
task_name=None,
cache_key=None,
always=False,
):
"""
Create task that sets up virtual environment.
:param ctx: BuildContext object.
:param python: Python program path.
:param venv_path: Virtual environment directory relative path relative to
top directory.
:param inputs: Input items list to add to created task.
See :paramref:`create_cmd_task.inputs` for allowed item types.
:param outputs: Output items list to add to created task.
See :paramref:`create_cmd_task.outputs` for allowed item types.
:param pip_setup_file: `get-pip.py` file path for `pip_setup` task.
:param pip_setup_touch: Touch file path for `pip_setup` task.
:param virtualenv_setup_touch: Touch file path for `virtualenv_setup` task.
:param task_name: Task name for display purpose.
:param cache_key: Task cache key.
:param always: Whether always run.
:return: Created task.
"""
# Ensure given context object is BuildContext object
_ensure_build_context(ctx)
# Create task that sets up `virtualenv` package
virtualenv_setup_task = virtualenv_setup(
# Context
ctx=ctx,
# Python program path
python=python,
# Touch file path
touch=virtualenv_setup_touch,
# `get-pip.py` file path for `pip_setup` task.
pip_setup_file=pip_setup_file,
# Touch file path for `pip_setup` task.
pip_setup_touch=pip_setup_touch,
)
# Get virtual environment directory path node
venv_path_node, _ = _normalize_items(
ctx=ctx,
items=[venv_path],
# Convert path string to node
str_to_node=True
)[0]
# Create task that sets up virtual environment.
task = create_cmd_task(
# Context
ctx=ctx,
# Command parts
parts=[
# Python program path
python,
# Run module
'-m',
# Module name
'virtualenv',
# Virtual environment directory absolute path
venv_path_node.abspath(),
],
# Input items list
inputs=[
# Run after the task that sets up `virtualenv` package
virtualenv_setup_task,
# Given input items list
inputs,
],
# Output items list
outputs=[
# Add the virtual environment's `python` program path as output
# target for dirty checking
get_python_path(venv_path),
# Add the virtual environment's `pip` program path as output target
# for dirty checking
get_pip_path(venv_path),
# Given output items list
outputs,
],
# Whether always run
always=always,
# Task name
task_name=task_name,
# Task cache key
cache_key=cache_key or (python, venv_path),
)
# Return the created task
return task
|
Create task that sets up virtual environment.
:param ctx: BuildContext object.
:param python: Python program path.
:param venv_path: Virtual environment directory relative path relative to
top directory.
:param inputs: Input items list to add to created task.
See :paramref:`create_cmd_task.inputs` for allowed item types.
:param outputs: Output items list to add to created task.
See :paramref:`create_cmd_task.outputs` for allowed item types.
:param pip_setup_file: `get-pip.py` file path for `pip_setup` task.
:param pip_setup_touch: Touch file path for `pip_setup` task.
:param virtualenv_setup_touch: Touch file path for `virtualenv_setup` task.
:param task_name: Task name for display purpose.
:param cache_key: Task cache key.
:param always: Whether always run.
:return: Created task.
|
entailment
|
def pip_ins_req(
ctx,
python,
req_path,
venv_path=None,
inputs=None,
outputs=None,
touch=None,
check_import=False,
check_import_module=None,
pip_setup_file=None,
pip_setup_touch=None,
virtualenv_setup_touch=None,
always=False,
):
"""
Create task that uses given virtual environment's `pip` to sets up \
packages listed in given requirements file.
:param ctx: BuildContext object.
:param python: Python program path used to set up `pip` and `virtualenv`.
:param req_path: Requirements file relative path relative to top directory.
:param venv_path: Virtual environment directory relative path relative to
top directory.
If given, will create the virtual environment and set up packages
listed in given requirements file in the virtual environment.
If not given, will set up packages listed in given requirements file in
given Python program's environment.
:param inputs: Input items list to add to created task.
See :paramref:`create_cmd_task.inputs` for allowed item types.
:param outputs: Output items list to add to created task.
See :paramref:`create_cmd_task.outputs` for allowed item types.
:param touch: Touch file path for dirty checking.
:param check_import: Whether import module for dirty checking.
:param check_import_module: Module name to import for dirty checking.
:param pip_setup_file: `get-pip.py` file path for `pip_setup` task.
:param pip_setup_touch: Touch file path for `pip_setup` task.
:param virtualenv_setup_touch: Touch file path for `virtualenv_setup` task.
:param always: Whether always run.
:return: Created task.
"""
# Ensure given context object is BuildContext object
_ensure_build_context(ctx)
# If virtual environment directory path is not given
if venv_path is None:
# Use given Python program path
venv_python = python
# If virtual environment directory path is given
else:
# Get Python program path in the virtual environment
venv_python = get_python_path(venv_path)
# Mark the path as input target
venv_python = mark_input(venv_python)
# If virtual environment directory path is not given,
# it means not create virtual environment.
if venv_path is None:
# Create task that sets up `pip`
pip_setup_task = pip_setup(
# Context
ctx=ctx,
# Python program path
python=python,
# `get-pip.py` file path
setup_file=pip_setup_file,
# Touch file path
touch=pip_setup_touch,
# Whether import module for dirty checking
always=always,
)
# Not create virtual environment
venv_task = None
# If virtual environment directory path is given
else:
# Not create task that sets up `pip` here because `create_venv`
# function below will do
pip_setup_task = None
# Create task that sets up virtual environment
venv_task = create_venv(
# Context
ctx=ctx,
# Python program path
python=python,
# Virtual environment directory path
venv_path=venv_path,
# Output items list
outputs=[
# Add the virtual environment's `python` program path as output
# target for dirty checking
get_python_path(venv_path),
# Add the virtual environment's `pip` program path as output
# target for dirty checking
get_pip_path(venv_path),
],
# Whether always run
always=always,
# Task name
task_name='Create venv `{}`'.format(venv_path),
# `get-pip.py` file path for `pip_setup` task
pip_setup_file=pip_setup_file,
# Touch file path for `pip_setup` task
pip_setup_touch=pip_setup_touch,
# Touch file path for `virtualenv_setup` task
virtualenv_setup_touch=virtualenv_setup_touch,
)
# If touch file path is not given
if not touch:
# Not update touch file
touch_node = None
# If touch file path is given
else:
# Update touch file
touch_node, always = update_touch_file(
# Context
ctx=ctx,
# Touch file path
path=touch,
# Whether import module for dirty checking
check_import=check_import,
# Module name to import for dirty checking
check_import_module=check_import_module,
# Python program path for dirty checking
check_import_python=venv_python,
# Whether always run
always=always,
)
# Create task that sets up packages
task = create_cmd_task(
# Context
ctx=ctx,
# Command parts
parts=[
# Python program path
venv_python,
# Run module
'-m',
# Module name
'pip',
# Install package
'install',
# Read package names from requirements file
'-r',
# Requirements file path. Mark as input target.
mark_input(req_path),
],
# Input items list
inputs=inputs,
# Output items list
outputs=[
# Use the touch node as output target for dirty checking
touch_node,
# Given output items list
outputs,
],
# Whether always run
always=always,
)
# Chain these tasks to run one after another
chain_tasks([
pip_setup_task,
venv_task,
task,
])
# Return the created task
return task
|
Create task that uses given virtual environment's `pip` to sets up \
packages listed in given requirements file.
:param ctx: BuildContext object.
:param python: Python program path used to set up `pip` and `virtualenv`.
:param req_path: Requirements file relative path relative to top directory.
:param venv_path: Virtual environment directory relative path relative to
top directory.
If given, will create the virtual environment and set up packages
listed in given requirements file in the virtual environment.
If not given, will set up packages listed in given requirements file in
given Python program's environment.
:param inputs: Input items list to add to created task.
See :paramref:`create_cmd_task.inputs` for allowed item types.
:param outputs: Output items list to add to created task.
See :paramref:`create_cmd_task.outputs` for allowed item types.
:param touch: Touch file path for dirty checking.
:param check_import: Whether import module for dirty checking.
:param check_import_module: Module name to import for dirty checking.
:param pip_setup_file: `get-pip.py` file path for `pip_setup` task.
:param pip_setup_touch: Touch file path for `pip_setup` task.
:param virtualenv_setup_touch: Touch file path for `virtualenv_setup` task.
:param always: Whether always run.
:return: Created task.
|
entailment
|
def git_clean(ctx):
"""
Delete all files untracked by git.
:param ctx: Context object.
:return: None.
"""
# Get command parts
cmd_part_s = [
# Program path
'git',
# Clean untracked files
'clean',
# Remove all untracked files
'-x',
# Remove untracked directories too
'-d',
# Force to remove
'-f',
# Give two `-f` flags to remove sub-repositories too
'-f',
]
# Print title
print_title('git_clean')
# Print the command in multi-line format
print_text(_format_multi_line_command(cmd_part_s))
# Create subprocess to run the command in top directory
proc = subprocess.Popen(cmd_part_s, cwd=ctx.top_dir)
# Wait the subprocess to finish
proc.wait()
# Print end title
print_title('git_clean', is_end=True)
|
Delete all files untracked by git.
:param ctx: Context object.
:return: None.
|
entailment
|
def run(self):
"""
Run command.
:return: Command exit code.
"""
# Print task title
print_title(self._task_name_title)
# Get context object
ctx = self._ctx
# Get command parts
cmd_part_s = self._parts
# Print title
print_title('Find program')
# Get program path from command parts
program_path = cmd_part_s[0]
# If the program path ends with one of the file extensions below
if program_path.endswith(('.exe', '.com', '.bat', '.cmd')):
# Remove the file extension.
# This is because `Waf`'s `find_binary` function adds each of the
# file extensions when finding the program.
program_path = program_path[:-4]
# Print info
print_text('Find program: {0}'.format(program_path))
#
try:
# Find program
found_program_path_s = ctx.find_program(program_path, quiet=True)
# If program paths are not found
except ConfigurationError:
# Get error message
msg = 'Error (2D7VS): Program is not found: {0}'.format(
program_path
)
# Raise error
raise ValueError(msg)
# If program paths are found.
# If program paths are found.
# Use the first program path found.
# If program paths are not found. (Should not happen.)
# Use given program path.
found_program_path = found_program_path_s[0] \
if found_program_path_s else program_path
# Use the program path found as the first command part
cmd_part_s[0] = found_program_path
# Print info
print_text('Use program: {0}'.format(found_program_path))
# Print end title
print_title('Find program', is_end=True)
# Print title
print_title('PATH')
# Print environment variable PATH's value, one part per line
print_text('\n'.join(os.environ.get('PATH', '').split(os.pathsep)))
# Print end title
print_title('PATH', is_end=True)
# Print title
print_title('PYTHONPATH')
# Print environment variable PYTHONPATH's value, one part per line
print_text(
'\n'.join(os.environ.get('PYTHONPATH', '').split(os.pathsep))
)
# Print end title
print_title('PYTHONPATH', is_end=True)
# Print title
print_title('DIR')
# Print working directory
print_text(self._cwd)
# Print end title
print_title('DIR', is_end=True)
# Print title
print_title('CMD')
# Print the command in multi-line format
print_text(_format_multi_line_command(cmd_part_s))
# Print end title
print_title('CMD', is_end=True)
# Print title
print_title('RUN')
# Run the command in the working directory
exit_code = self.exec_command(cmd_part_s, cwd=self._cwd)
# Print the command's exit code
print_text('Exit code: {0}'.format(exit_code))
# Print end title
print_title('RUN', is_end=True)
# Print task end title
print_title(self._task_name_title, True)
# Return the exit code
return exit_code
|
Run command.
:return: Command exit code.
|
entailment
|
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)
>>> assert type(ac_info_all) is list
>>> assert len(ac_info_all[0]) == 12
>>> assert 'hardwareVersion' in ac_info_all[0]
>>> assert 'ipAddress' in ac_info_all[0]
>>> assert 'label' in ac_info_all[0]
>>> assert 'macAddress' in ac_info_all[0]
>>> assert 'onlineApCount' in ac_info_all[0]
>>> assert 'onlineClientCount' in ac_info_all[0]
>>> assert 'pingStatus' in ac_info_all[0]
>>> assert 'serialId' in ac_info_all[0]
>>> assert 'softwareVersion' in ac_info_all[0]
>>> assert 'status' in ac_info_all[0]
>>> assert 'sysName' in ac_info_all[0]
>>> assert 'type' in ac_info_all[0]
"""
get_ac_info_all_url = "/imcrs/wlan/acInfo/queryAcBasicInfo"
f_url = url + get_ac_info_all_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)['acBasicInfo']
except requests.exceptions.RequestException as e:
return "Error:\n" + str(e) + " get_ac_info_all: 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)
>>> assert type(ac_info_all) is list
>>> assert len(ac_info_all[0]) == 12
>>> assert 'hardwareVersion' in ac_info_all[0]
>>> assert 'ipAddress' in ac_info_all[0]
>>> assert 'label' in ac_info_all[0]
>>> assert 'macAddress' in ac_info_all[0]
>>> assert 'onlineApCount' in ac_info_all[0]
>>> assert 'onlineClientCount' in ac_info_all[0]
>>> assert 'pingStatus' in ac_info_all[0]
>>> assert 'serialId' in ac_info_all[0]
>>> assert 'softwareVersion' in ac_info_all[0]
>>> assert 'status' in ac_info_all[0]
>>> assert 'sysName' in ac_info_all[0]
>>> assert 'type' in ac_info_all[0]
|
entailment
|
def addvlan(self, vlanid, vlan_name):
"""
Function operates on the IMCDev object. Takes input of vlanid (1-4094), str of vlan_name,
auth and url to execute the create_dev_vlan method on the IMCDev object. Device must be
supported in the HPE IMC Platform VLAN Manager module.
:param vlanid: str of VLANId ( valid 1-4094 )
:param vlan_name: str of vlan_name
:return:
"""
create_dev_vlan( vlanid, vlan_name, self.auth, self.url, devid = self.devid)
|
Function operates on the IMCDev object. Takes input of vlanid (1-4094), str of vlan_name,
auth and url to execute the create_dev_vlan method on the IMCDev object. Device must be
supported in the HPE IMC Platform VLAN Manager module.
:param vlanid: str of VLANId ( valid 1-4094 )
:param vlan_name: str of vlan_name
:return:
|
entailment
|
def delvlan(self, vlanid):
"""
Function operates on the IMCDev object. Takes input of vlanid (1-4094),
auth and url to execute the delete_dev_vlans method on the IMCDev object. Device must be
supported in the HPE IMC Platform VLAN Manager module.
:param vlanid: str of VLANId ( valid 1-4094 )
:return:
"""
delete_dev_vlans( vlanid, self.auth, self.url, devid = self.devid)
|
Function operates on the IMCDev object. Takes input of vlanid (1-4094),
auth and url to execute the delete_dev_vlans method on the IMCDev object. Device must be
supported in the HPE IMC Platform VLAN Manager module.
:param vlanid: str of VLANId ( valid 1-4094 )
:return:
|
entailment
|
def getipmacarp(self):
"""
Function operates on the IMCDev object and updates the ipmacarp attribute
:return:
"""
self.ipmacarp = get_ip_mac_arp_list(self.auth, self.url, devid = self.devid)
|
Function operates on the IMCDev object and updates the ipmacarp attribute
:return:
|
entailment
|
def down(self):
"""
Function operates on the IMCInterface object and configures the interface into an
administratively down state and refreshes contents of self.adminstatus
:return:
"""
set_interface_down(self.ifIndex, self.auth, self.url, devip=self.ip)
self.adminstatus = get_interface_details(self.ifIndex, self.auth, self.url, devip=self.ip)[
'adminStatusDesc']
|
Function operates on the IMCInterface object and configures the interface into an
administratively down state and refreshes contents of self.adminstatus
:return:
|
entailment
|
def up(self):
"""
Function operates on the IMCInterface object and configures the interface into an
administratively up state and refreshes contents of self.adminstatus
:return:
"""
set_interface_up(self.ifIndex, self.auth, self.url, devip=self.ip)
self.adminstatus = get_interface_details(self.ifIndex, self.auth, self.url, devip=self.ip)[
'adminStatusDesc']
|
Function operates on the IMCInterface object and configures the interface into an
administratively up state and refreshes contents of self.adminstatus
:return:
|
entailment
|
def allocate_ip(self, hostipaddress, name, description):
"""
Object method takes in input of hostipaddress, name and description and adds them to the
parent ip scope.
:param hostipaddress: str of ipv4 address of the target host ip record
:param name: str of the name of the owner of the target host ip record
:param description: str of a description of the target host ip record
:return:
"""
add_scope_ip(hostipaddress, name, description, self.auth, self.url, scopeid=self.id)
|
Object method takes in input of hostipaddress, name and description and adds them to the
parent ip scope.
:param hostipaddress: str of ipv4 address of the target host ip record
:param name: str of the name of the owner of the target host ip record
:param description: str of a description of the target host ip record
:return:
|
entailment
|
def deallocate_ip(self, hostipaddress):
"""
Object method takes in input of hostip address,removes them from the parent ip scope.
:param hostid: str of the hostid of the target host ip record
:return:
"""
delete_host_from_segment(hostipaddress, self.netaddr, self.auth, self.url)
|
Object method takes in input of hostip address,removes them from the parent ip scope.
:param hostid: str of the hostid of the target host ip record
:return:
|
entailment
|
def gethosts(self):
"""
Method gets all hosts currently allocated to the target scope and refreashes the self.hosts
attributes of the object
:return:
"""
self.hosts = get_ip_scope_hosts(self.auth, self.url, self.id)
|
Method gets all hosts currently allocated to the target scope and refreashes the self.hosts
attributes of the object
:return:
|
entailment
|
def nextfreeip(self):
"""
Method searches for the next free ip address in the scope object and returns it as a str
value.
:return:
"""
allocated_ips = [ipaddress.ip_address(host['ip']) for host in self.hosts]
for ip in self.netaddr:
if str(ip).split('.')[-1] == '0':
continue
if ip not in allocated_ips:
return ip
|
Method searches for the next free ip address in the scope object and returns it as a str
value.
:return:
|
entailment
|
def addchild(self, startip, endip, name, description):
"""
Method takes inpur of str startip, str endip, name, and description and adds a child scope.
The startip and endip MUST be in the IP address range of the parent scope.
:param startip: str of ipv4 address of the first address in the child scope
:param endip: str of ipv4 address of the last address in the child scope
:param name: of the owner of the child scope
:param description: description of the child scope
:return:
"""
add_child_ip_scope(self.auth, self.url, startip, endip, name, description, self.id)
|
Method takes inpur of str startip, str endip, name, and description and adds a child scope.
The startip and endip MUST be in the IP address range of the parent scope.
:param startip: str of ipv4 address of the first address in the child scope
:param endip: str of ipv4 address of the last address in the child scope
:param name: of the owner of the child scope
:param description: description of the child scope
:return:
|
entailment
|
def get_telnet_template(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
telnet template
:rtype list
"""
f_url = url + "/imcrs/plat/res/telnet?start=0&size=10000&desc=false&total=false"
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
telnet_templates = (json.loads(response.text))
template = None
if type(telnet_templates['telnetParamTemplate']) is dict:
my_templates = [telnet_templates['telnetParamTemplate']]
telnet_templates['telnetParamTemplate'] = my_templates
if template_name is None:
return telnet_templates['telnetParamTemplate']
elif template_name is not None:
for telnet_template in telnet_templates['telnetParamTemplate']:
if telnet_template['name'] == template_name:
template = [telnet_template]
print (type(template))
if template == None:
return 404
else:
return template
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_telnet_templates: 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
telnet template
:rtype list
|
entailment
|
def modify_telnet_template(auth, url, telnet_template, template_name= None, template_id = None):
"""
Function takes input of a dictionry containing the required key/value pair for the modification
of a telnet template.
:param auth:
:param url:
:param telnet_template: Human readable label which is the name of the specific telnet template
:param template_id Internal IMC number which designates the specific telnet 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.
telnet_template = {"type": "0",
"name": "User_with_Enable",
"authType": "4",
"userName": "newadmin",
"userPassword": "newpassword",
"superPassword": "newpassword",
"authTypeStr": "Username + Password + Super/Manager Password",
"timeout": "4",
"retries": "1",
"port": "23",
"version": "1",
"creator": "admin",
"accessType": "1",
"operatorGroupStr": ""}
"""
if template_name is None:
template_name = telnet_template['name']
if template_id is None:
telnet_templates = get_telnet_template(auth, url)
template_id = None
for template in telnet_templates:
if template['name'] == template_name:
template_id = template['id']
f_url = url + "/imcrs/plat/res/telnet/"+str(template_id)+"/update"
response = requests.put(f_url, data = json.dumps(telnet_template), auth=auth, headers=HEADERS)
try:
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " modify_telnet_template: An Error has occured"
|
Function takes input of a dictionry containing the required key/value pair for the modification
of a telnet template.
:param auth:
:param url:
:param telnet_template: Human readable label which is the name of the specific telnet template
:param template_id Internal IMC number which designates the specific telnet 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.
telnet_template = {"type": "0",
"name": "User_with_Enable",
"authType": "4",
"userName": "newadmin",
"userPassword": "newpassword",
"superPassword": "newpassword",
"authTypeStr": "Username + Password + Super/Manager Password",
"timeout": "4",
"retries": "1",
"port": "23",
"version": "1",
"creator": "admin",
"accessType": "1",
"operatorGroupStr": ""}
|
entailment
|
def delete_telnet_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
telnet 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:
telnet_templates = get_telnet_template(auth, url)
if template_name is None:
template_name = telnet_template['name']
template_id = None
for template in telnet_templates:
if template['name'] == template_name:
template_id = template['id']
f_url = url + "/imcrs/plat/res/telnet/%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_telnet_template: An Error has occured"
|
Takes template_name as input to issue RESTUL call to HP IMC which will delete the specific
telnet 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
|
entailment
|
def create_ssh_template(auth, url, ssh_template ):
"""
Function takes input of a dictionry containing the required key/value pair for the creation
of a ssh template.
:param auth:
:param url:
:param ssh: dictionary of valid JSON which complains to API schema
: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.
ssh_template = {
"type": "0",
"name": "ssh_admin_template",
"authType": "3",
"authTypeStr": "Password + Super Password",
"userName": "admin",
"password": "password",
"superPassword": "password",
"port": "22",
"timeout": "10",
"retries": "3",
"keyFileName": "",
"keyPhrase": ""
}
"""
f_url = url + "/imcrs/plat/res/ssh/add"
response = requests.post(f_url, data = json.dumps(ssh_template), auth=auth, headers=HEADERS)
try:
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " create_ssh_template: An Error has occured"
|
Function takes input of a dictionry containing the required key/value pair for the creation
of a ssh template.
:param auth:
:param url:
:param ssh: dictionary of valid JSON which complains to API schema
: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.
ssh_template = {
"type": "0",
"name": "ssh_admin_template",
"authType": "3",
"authTypeStr": "Password + Super Password",
"userName": "admin",
"password": "password",
"superPassword": "password",
"port": "22",
"timeout": "10",
"retries": "3",
"keyFileName": "",
"keyPhrase": ""
}
|
entailment
|
def get_ssh_template(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
ssh template
:rtype list
"""
f_url = url + "/imcrs/plat/res/ssh?start=0&size=10000&desc=false&total=false"
response = requests.get(f_url, auth=auth, headers=HEADERS)
try:
if response.status_code == 200:
ssh_templates = (json.loads(response.text))
template = None
if type(ssh_templates['sshParamTemplate']) is dict:
my_templates = [ssh_templates['sshParamTemplate']]
ssh_templates['sshParamTemplate'] = my_templates
if template_name is None:
return ssh_templates['sshParamTemplate']
elif template_name is not None:
for ssh_template in ssh_templates['sshParamTemplate']:
if ssh_template['name'] == template_name:
template = [ssh_template]
print (type(template))
if template == None:
return 404
else:
return template
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " get_ssh_templates: 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
ssh template
:rtype list
|
entailment
|
def modify_ssh_template(auth, url, ssh_template, template_name= None, template_id = None):
"""
Function takes input of a dictionry containing the required key/value pair for the modification
of a ssh 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.
ssh_template = {
"type": "0",
"name": "ssh_admin_template",
"authType": "3",
"authTypeStr": "Password + Super Password",
"userName": "newadmin",
"password": "password",
"superPassword": "password",
"port": "22",
"timeout": "10",
"retries": "3",
"keyFileName": "",
"keyPhrase": ""
}
"""
if template_name is None:
template_name = ssh_template['name']
if template_id is None:
ssh_templates = get_ssh_template(auth, url)
template_id = None
for template in ssh_templates:
if template['name'] == template_name:
template_id = template['id']
f_url = url + "/imcrs/plat/res/ssh/"+str(template_id)+"/update"
response = requests.put(f_url, data = json.dumps(ssh_template), auth=auth, headers=HEADERS)
try:
return response.status_code
except requests.exceptions.RequestException as error:
return "Error:\n" + str(error) + " modify_ssh_template: An Error has occured"
|
Function takes input of a dictionry containing the required key/value pair for the modification
of a ssh 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.
ssh_template = {
"type": "0",
"name": "ssh_admin_template",
"authType": "3",
"authTypeStr": "Password + Super Password",
"userName": "newadmin",
"password": "password",
"superPassword": "password",
"port": "22",
"timeout": "10",
"retries": "3",
"keyFileName": "",
"keyPhrase": ""
}
|
entailment
|
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 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
|
entailment
|
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"
|
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
|
entailment
|
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"
|
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": ""
}
|
entailment
|
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 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
|
entailment
|
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 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]
|
entailment
|
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'
|
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]
|
entailment
|
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)
|
Run a non-encrypted non-authorized API proxy server.
Use this only for development and testing!
|
entailment
|
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\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]
|
entailment
|
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"
|
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
|
entailment
|
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 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]
|
entailment
|
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 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]
|
entailment
|
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 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
|
entailment
|
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 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]
|
entailment
|
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 " 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')
|
entailment
|
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"
|
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
|
entailment
|
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
|
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
|
entailment
|
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.
|
entailment
|
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']
|
Creates a new keypair with the given options.
You need an admin privilege for this operation.
|
entailment
|
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']
|
Deletes an existing keypair with given ACCESSKEY.
|
entailment
|
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']
|
Lists the keypairs.
You need an admin privilege for this operation.
|
entailment
|
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']
|
Returns the keypair's information such as resource limits.
:param fields: Additional per-agent query fields to fetch.
.. versionadded:: 18.12
|
entailment
|
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']
|
Activates this keypair.
You need an admin privilege for this operation.
|
entailment
|
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']
|
Deactivates this keypair.
Deactivated keypairs cannot make any API requests
unless activated again by an administrator.
You need an admin privilege for this operation.
|
entailment
|
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"
}'''
|
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:
|
entailment
|
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()
|
Lists all resource presets in the current scaling group with additiona
information.
|
entailment
|
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 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)
|
entailment
|
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 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
|
entailment
|
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 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
|
entailment
|
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"
|
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)
|
entailment
|
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")
|
This function prompts user for IMC server information and credentuials and stores
values in url and auth global variables
|
entailment
|
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)
|
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
|
entailment
|
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()
|
This method requests an authentication object from the HPE IMC NMS and returns an HTTPDigest Auth Object
:return:
|
entailment
|
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
|
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
|
entailment
|
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 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.
|
entailment
|
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)
|
Calls this instance's request_client's get method with the
specified component endpoint
|
entailment
|
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
|
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.
|
entailment
|
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)
|
Common method for handling parameters before passing to api_client
|
entailment
|
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))
|
Convert input address data into json format
|
entailment
|
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 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".
|
entailment
|
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 rental_report component
Rental Report only supports a single address.
Args:
- address
- zipcode
Kwargs:
- format_type - "json", "xlsx" or "all". Default is "json".
|
entailment
|
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)
|
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"]
|
entailment
|
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)
|
Returns the contents of version.json or a 404.
|
entailment
|
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)
|
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.
|
entailment
|
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 a list of ComponentResult from the json_data
|
entailment
|
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
)
|
Returns whether there was a business logic error when fetching data
for any components for this property.
Returns:
boolean
|
entailment
|
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()]
|
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.
|
entailment
|
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 property json data into a Property object
Args:
json_data (dict): The json data for this property
Returns:
Property object
|
entailment
|
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 block json data into a Block object
Args:
json_data (dict): The json data for this block
Returns:
Block object
|
entailment
|
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 zipcode json data into a ZipCode object
Args:
json_data (dict): The json data for this zipcode
Returns:
Zip object
|
entailment
|
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
|
Deserialize msa json data into a Msa object
Args:
json_data (dict): The json data for this msa
Returns:
Msa object
|
entailment
|
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)
|
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]
|
entailment
|
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)
|
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]
|
entailment
|
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
|
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')]
|
entailment
|
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 items from an iterator in iterable chunks.
|
entailment
|
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
|
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)]
|
entailment
|
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 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)
|
entailment
|
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)
|
Return the first item of the iterable for which func(item) == True.
Or raises IndexError.
WARNING: this will consume generators.
|
entailment
|
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)
|
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.
|
entailment
|
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 first x items from this iterable or default.
|
entailment
|
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
|
Lazily return the last x items from this iterable or default.
|
entailment
|
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
|
Determine execution mode.
Legacy mode: <= v4.20181215
|
entailment
|
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()
|
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.
|
entailment
|
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()
|
A proposed-but-not-implemented asyncio.run_forever() API based on
@vxgmichel's idea.
See discussions on https://github.com/python/asyncio/pull/465
|
entailment
|
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
|
claar all the cache, and release memory
|
entailment
|
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
|
Delete the item
|
entailment
|
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
|
Main function.
:return:
None.
|
entailment
|
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
|
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.
|
entailment
|
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()
|
Destroys the compute session.
Since the server literally kills the container(s), all ongoing executions are
forcibly interrupted.
|
entailment
|
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
|
Restarts the compute session.
The server force-destroys the current running container(s), but keeps their
temporary scratch directories intact.
|
entailment
|
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()
|
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.
|
entailment
|
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()
|
Retrieves a brief information about the compute session.
|
entailment
|
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']
|
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>`
|
entailment
|
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
|
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.
|
entailment
|
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
|
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.
|
entailment
|
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()
|
Gets the list of files in the given path inside the compute session
container.
:param path: The directory path in the compute session.
|
entailment
|
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)
|
Opens a pseudo-terminal of the kernel (if supported) streamed via
websockets.
:returns: a :class:`StreamPty` object.
|
entailment
|
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)
|
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.
|
entailment
|
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)
|
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.
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.