code stringlengths 1 18.2k |
|---|
'list'> >>> assert 'ackStatus' in all_alarms[0] [{'OID': '1.3.6.1.4.1.11.2.14.11.15.2.75.5.3.1.6.7', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '1001', 'alarmCategoryDesc': 'Wireless Device Alarm', 'alarmDesc': 'The device(MAC Address: F4 ... |
'', 'id': '187616', 'originalType': '1', 'originalTypeDesc': 'Trap', 'paras': '*Attack MAC= F4 B7 E2 95 A0 CD;Attack Frame Type=Probe Request', 'parentId': '0', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25... |
event (hh3cPeriodicalTrap) of device ADP_Initial_Config(10.20.10.10) from 2016-07-25 12:56:01 to 2016-07-25 14:36:01.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187625', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469471... |
'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient device interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:07:06 t... |
Time=2016-07-25 14:07:06;Stop Time=2016-07-25 14:40:21;Times=100;*Repeat Event Name=Some ambient device interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {... |
baseline(2.87 Mbps).', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/187631', 'alarmLevel': '2', 'alarmLevelDesc': 'Major', 'deviceId': '67', 'deviceIp': '10.101.0.203', 'deviceName': 'HPEIMC72WIN2K12R2', 'faultTime': '1469472140', 'faultTimeDesc': '2016-07-25 14:42:20', 'holdInfo': '', 'id': '187631', 'or... |
'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.3.2.6.11', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime': '0', 'ackTimeDesc': '', 'ackUserName': '', 'alarmCategory': '9', 'alarmCategoryDesc': 'Traffic Analysis and Audit Alarm', 'alarmDesc': 'The out ... |
'holdInfo': '', 'id': '187632', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': '*UNBA Server Name=NMS;*UNBA Server IP=127.0.0.1;*Alarm Object Name=The out direction of interface GigabitEthernet1/0/2 on device 192.168.1.221;Alarm Occur Time=2016-07-25 14:32:00;Current Flow Speed=48.79 Mbps;Alarm Severity=2;Thr... |
'', 'alarmCategory': '15', 'alarmCategoryDesc': 'Other Alarms from NMS', 'alarmDesc': 'iMC alarm system has received 100 alarms about the event (Some ambient AP interferes) of device HP830_WSC(10.10.10.5) from 2016-07-25 14:14:00 to 2016-07-25 14:47:55.', 'alarmDetail': 'http://10.101.0.203:8080/imcrs/fault/alarm/18763... |
AP interferes;*Device IP=10.10.10.5;Device Name=HP830_WSC', 'parentId': '173953', 'recStatus': '0', 'recStatusDesc': 'Unrecovered', 'recTime': '0', 'recTimeDesc': '', 'recUserName': '', 'remark': '', 'somState': '0'}, {'OID': '1.3.6.1.4.1.25506.4.2.2.2.6.1', 'ackStatus': '0', 'ackStatusDesc': 'Unacknowledged', 'ackTime... |
'http://10.101.0.203:8080/imcrs/fault/alarm/187654', 'alarmLevel': '4', 'alarmLevelDesc': 'Warning', 'deviceId': '0', 'deviceIp': '127.0.0.1', 'deviceName': 'NMS', 'faultTime': '1469474150', 'faultTimeDesc': '2016-07-25 15:15:50', 'id': '187654', 'originalType': '3', 'originalTypeDesc': 'iMC', 'paras': 'Start Time=2016... |
r = requests.get(f_url, auth=auth, headers=headers) # r.status_code try: if r.status_code == 200: alarm_list = (json.loads(r.text)) return alarm_list['alarm'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + ' get_alarms: An Error has occured' |
def get_dev_alarms(auth, url, devid=None, devip=None): """ function takes the devId of a specific device and issues a RESTFUL call to get the current alarms for the target device. :param devid: int or str value of the target device :param devip: str of ipv4 address of the target device :param auth: requests auth object... |
RS interface #usually auth.url from pyhpeimc.auth.authclass :return:list of dictionaries containing the alarms for this device :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> dev_alarms = get_dev_alarms(auth.... |
= get_dev_details(devip, auth, url)['id'] f_url = url + "/imcrs/fault/alarm?operatorName=admin&deviceId=" + \ str(devid) + "&desc=false" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: dev_alarm = (json.loads(response.text)) if 'alarm' in dev_alarm: return dev_alarm['alar... |
def get_realtime_alarm(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.cred... |
where each element of the list represents a single alarm as pulled from the the current list of realtime alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> real_time_alarm = get_re... |
url + "/imcrs/fault/faultRealTime?operatorName=" + username response = requests.get(f_url, auth=auth, headers=HEADERS) try: realtime_alarm_list = (json.loads(response.text)) return realtime_alarm_list['faultRealTime']['faultRealTimeList'] except requests.exceptions.RequestException as error: return "Error:\n" + str(err... |
def get_alarms(username, auth, url): """Takes in no param as input to fetch RealTime Alarms from HP IMC RESTFUL API :param username OpeatorName, String type. Required. Default Value "admin". Checks the operator has the privileges to view the Real-Time Alarms. :param auth: requests auth object #usually auth.creds from a... |
where each element of the list represents a single alarm as pulled from the the current list of browse alarms in the HPE IMC Platform :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.alarms import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> all_alarms = get_alarms('a... |
url + "/imcrs/fault/alarm?operatorName=" + username + \ "&recStatus=0&ackStatus=0&timeRange=0&size=50&desc=true" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: alarm_list = (json.loads(response.text)) return alarm_list['alarm'] except requests.exceptions.RequestException... |
def get_alarm_details(alarm_id, auth, url): """ function to take str input of alarm_id, issues a REST call to the IMC REST interface and returns a dictionary object which contains the details of a specific alarm. :param alarm_id: str number which represents the internal ID of a specific alarm :param auth: :param url: :... |
headers=HEADERS) try: alarm_details = json.loads(response.text) return alarm_details except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarm_details: An Error has occured' |
def acknowledge_alarm(alarm_id, auth, url): """ Function tasks input of str of alarm ID and sends to REST API. Function will acknowledge designated alarm in the IMC alarm database. :param alarm_id: str of alarm ID param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of... |
f_url = url + "/imcrs/fault/alarm/acknowledge/"+str(alarm_id) response = requests.put(f_url, auth=auth, headers=HEADERS) try: return response.status_code except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + ' get_alarms: An Error has occured' |
def create_operator(operator, auth, url,headers=HEADERS): """ Function takes input of dictionary operator with the following keys operator = { "fullName" : "" , "sessionTimeout" : "", "password" : "", "operatorGroupId" : "", "name" : "", "desc" : "", "defaultAcl" : "", "authType" : ""} converts to json and issues a HTT... |
auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :param operator: dictionary with the required operator key-value pairs as defined above. :param headers: json formated string. default values set in module :return: :rtype: >>> import json >>... |
'''{ "fullName" : "test administrator", "sessionTimeout" : "30","password" : "password","operatorGroupId" : "1","name" : "testadmin","desc" : "test admin account","defaultAcl" : "","authType" : "0"}''' >>> operator = json.loads(operator) >>> delete_if_exists = delete_plat_operator('testadmin', auth.creds, auth.url) >>>... |
""" create_operator_url = '/imcrs/plat/operator' f_url = url + create_operator_url payload = json.dumps(operator, indent=4) # creates the URL using the payload variable as the contents r = requests.post(f_url, data=payload, auth=auth, headers=headers) try: if r.status_code == 409: #print("Operator Already Exists") retu... |
def list(): '''List virtual folders that belongs to the current user.''' fields = [ ('Name', 'name'), ('ID', 'id'), ('Owner', 'is_owner'), ('Permission', 'permission'), ] with Session() as session: try: resp = session.VFolder.list() if not resp: print('There is no virtual folders created yet.') return rows = (tuple(vf[... |
except Exception as e: print_error(e) sys.exit(1) |
def list_hosts(): '''List the hosts of virtual folders that is accessible to the current user.''' with Session() as session: try: resp = session.VFolder.list_hosts() print(f"Default vfolder host: {resp['default']}") print(f"Usable hosts: {', '.join(resp['allowed'])}") except Exception as e: print_error(e) sys.exit(1) |
def create(name, host): '''Create a new virtual folder. \b NAME: Name of a virtual folder. HOST: Name of a virtual folder host in which the virtual folder will be created. ''' with Session() as session: try: result = session.VFolder.create(name, host) print('Virtual folder "{0}" is created.'.format(result['name'])) exc... |
def delete(name): '''Delete the given virtual folder. This operation is irreversible! NAME: Name of a virtual folder. ''' with Session() as session: try: session.VFolder(name).delete() print_done('Deleted.') except Exception as e: print_error(e) sys.exit(1) |
def rename(old_name, new_name): '''Rename the given virtual folder. This operation is irreversible! You cannot change the vfolders that are shared by other users, and the new name must be unique among all your accessible vfolders including the shared ones. OLD_NAME: The current name of a virtual folder. NEW_NAME: The n... |
Exception as e: print_error(e) sys.exit(1) |
def info(name): '''Show the information of the given virtual folder. NAME: Name of a virtual folder. ''' with Session() as session: try: result = session.VFolder(name).info() print('Virtual folder "{0}" (ID: {1})' .format(result['name'], result['id'])) print('- Owner:', result['is_owner']) print('- Permission:', result... |
def download(name, filenames): ''' Download a file from the virtual folder to the current working directory. The files with the same names will be overwirtten. \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to be uploaded. ''' with Session() as session: try: session.VFolder(name).download(filenames, s... |
def mkdir(name, path): '''Create an empty directory in the virtual folder. \b NAME: Name of a virtual folder. PATH: The name or path of directory. Parent directories are created automatically if they do not exist. ''' with Session() as session: try: session.VFolder(name).mkdir(path) print_done('Done.') except Exception... |
def rm(name, filenames, recursive): ''' Delete files in a virtual folder. If one of the given paths is a directory and the recursive option is enabled, all its content and the directory itself are recursively deleted. This operation is irreversible! \b NAME: Name of a virtual folder. FILENAMES: Paths of the files to de... |
sure? (y/n): ").lower().strip()[:1] == 'y': session.VFolder(name).delete_files( filenames, recursive=recursive) print_done('Done.') except Exception as e: print_error(e) sys.exit(1) |
def ls(name, path): """ List files in a path of a virtual folder. \b NAME: Name of a virtual folder. PATH: Path inside vfolder. """ with Session() as session: try: print_wait('Retrieving list of files in "{}"...'.format(path)) result = session.VFolder(name).list_files(path) if 'error_msg' in result and result['error_ms... |
mdt = datetime.fromtimestamp(file['mtime']) mtime = mdt.strftime('%b %d %Y %H:%M:%S') row = [file['filename'], file['size'], mtime, file['mode']] table.append(row) print_done('Retrived.') print(tabulate(table, headers=headers)) except Exception as e: print_error(e) |
def invite(name, emails, perm): """Invite other users to access the virtual folder. \b NAME: Name of a virtual folder. EMAIL: Emails to invite. """ with Session() as session: try: assert perm in ['rw', 'ro'], \ 'Invalid permission: {}'.format(perm) result = session.VFolder(name).invite(perm, emails) invited_ids = resul... |
found. Invitation was not sent.') except Exception as e: print_error(e) sys.exit(1) |
def invitations(): """List and manage received invitations. """ with Session() as session: try: result = session.VFolder.invitations() invitations = result.get('invitations', []) if len(invitations) < 1: print('No invitations.') return print('List of invitations (inviter, vfolder id, permission):') for cnt, inv in enum... |
inv['vfolder_id'], perm)) selection = input('Choose invitation number to manage: ') if selection.isdigit(): selection = int(selection) - 1 else: return if 0 <= selection < len(invitations): while True: action = input('Choose action. (a)ccept, (r)eject, (c)ancel: ') if action.lower() == 'a': # TODO: Let user can select ... |
config.access_key) print(result['msg']) break elif action.lower() == 'r': result = session.VFolder.delete_invitation( invitations[selection]['id']) print(result['msg']) break elif action.lower() == 'c': break except Exception as e: print_error(e) sys.exit(1) |
def init_check(self, check, obj): """ Adds a given check callback with the provided object to the list of checks. Useful for built-ins but also advanced custom checks. """ self.logger.info('Adding extension check %s' % check.__name__) check = functools.wraps(check)(functools.partial(check, obj)) self.check(func=check) |
def init_app(self, app): """ Initializes the extension with the given app, registers the built-in views with an own blueprint and hooks up our signal callbacks. """ # If no version path was provided in the init of the Dockerflow # class we'll use the parent directory of the app root path. if self.version_path is None: ... |
self._version_view), ('/__heartbeat__', 'heartbeat', self._heartbeat_view), ('/__lbheartbeat__', 'lbheartbeat', self._lbheartbeat_view), ): self._blueprint.add_url_rule(*view) self._blueprint.before_app_request(self._before_request) self._blueprint.after_app_request(self._after_request) self._blueprint.app_errorhandler... |
def _before_request(self): """ The before_request callback. """ g._request_id = str(uuid.uuid4()) g._start_timestamp = time.time() |
def _after_request(self, response): """ The signal handler for the request_finished signal. """ if not getattr(g, '_has_exception', False): extra = self.summary_extra() self.summary_logger.info('', extra=extra) return response |
def _got_request_exception(self, sender, exception, **extra): """ The signal handler for the got_request_exception signal. """ extra = self.summary_extra() extra['errno'] = 500 self.summary_logger.error(str(exception), extra=extra) g._has_exception = True |
def user_id(self): """ Return the ID of the current request's user """ # This needs flask-login to be installed if not has_flask_login: return # and the actual login manager installed if not hasattr(current_app, 'login_manager'): return # fail if no current_user was attached to the request context try: is_authenticated... |
is_authenticated = is_authenticated() # and fail if the user isn't authenticated if not is_authenticated: return # finally return the user id return current_user.get_id() |
def summary_extra(self): """ Build the extra data for the summary logger. """ out = { 'errno': 0, 'agent': request.headers.get('User-Agent', ''), 'lang': request.headers.get('Accept-Language', ''), 'method': request.method, 'path': request.path, } # set the uid value to the current user ID user_id = self.user_id() if u... |
if request_id is not None: out['rid'] = request_id # and the t value to the time it took to render start_timestamp = g.get('_start_timestamp', None) if start_timestamp is not None: # Duration of request, in milliseconds. out['t'] = int(1000 * (time.time() - start_timestamp)) return out |
def _version_view(self): """ View that returns the contents of version.json or a 404. """ version_json = self._version_callback(self.version_path) if version_json is None: return 'version.json not found', 404 else: return jsonify(version_json) |
def _heartbeat_view(self): """ Runs all the registered checks and returns a JSON response 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. """ details = {} statuses = {} level = 0 for name, check in se... |
detail['status'] level = max(level, detail['level']) if detail['level'] > 0: details[name] = detail payload = { 'status': checks.level_to_text(level), 'checks': statuses, 'details': details, } def render(status_code): return make_response(jsonify(payload), status_code) if level < checks.WARNING: status_code = 200 heart... |
def check(self, func=None, name=None): """ A decorator to register a new Dockerflow check to be run when the /__heartbeat__ endpoint is called., e.g.:: from dockerflow.flask import checks @dockerflow.check def storage_reachable(): try: acme.storage.ping() except SlowConnectionException as exc: return [checks.Warning(ex... |
if name is None: name = func.__name__ self.logger.info('Registered Dockerflow check %s', name) @functools.wraps(func) def decorated_function(*args, **kwargs): self.logger.info('Called Dockerflow check %s', name) return func(*args, **kwargs) self.checks[name] = decorated_function return decorated_function |
def drange(start: Decimal, stop: Decimal, num: int): ''' A simplified version of numpy.linspace with default options ''' delta = stop - start step = delta / (num - 1) yield from (start + step * Decimal(tick) for tick in range(0, num)) |
def range_expr(arg): ''' Accepts a range expression which generates a range of values for a variable. Linear space range: "linspace:1,2,10" (start, stop, num) as in numpy.linspace Pythonic range: "range:1,10,2" (start, stop[, step]) as in Python's range Case range: "case:a,b,c" (comma-separated strings) ''' key, value ... |
value.startswith('linspace:'): start, stop, num = value[9:].split(',') return key, tuple(drange(Decimal(start), Decimal(stop), int(num))) elif value.startswith('range:'): range_args = map(int, value[6:].split(',')) return key, tuple(range(*range_args)) else: raise ArgumentTypeError('Unrecognized range expression type')... |
async def exec_loop(stdout, stderr, kernel, mode, code, *, opts=None, vprint_done=print_done, is_multi=False): ''' Fully streamed asynchronous version of the execute loop. ''' async with kernel.stream_execute(code, mode=mode, opts=opts) as stream: async for result in stream: if result.type == aiohttp.WSMsgType.TEXT: re... |
else: print('----- output record (type: {0}) -----'.format(rec[0]), file=stdout) print(rec[1], file=stdout) print('----- end of record -----', file=stdout) stdout.flush() files = result.get('files', []) if files: print('--- generated files ---', file=stdout) for item in files: print('{0}: {1}'.format(item['name'], item... |
result['status'] == 'build-finished': exitCode = result.get('exitCode') msg = 'Build finished. (exit code = {0})'.format(exitCode) if is_multi: print(msg, file=stderr) vprint_done(msg) elif result['status'] == 'finished': exitCode = result.get('exitCode') msg = 'Execution finished. (exit code = {0})'.format(exitCode) i... |
def exec_loop_sync(stdout, stderr, kernel, mode, code, *, opts=None, vprint_done=print_done): ''' Old synchronous polling version of the execute loop. ''' opts = opts if opts else {} run_id = None # use server-assigned run ID while True: result = kernel.execute(run_id, code, mode=mode, opts=opts) run_id = result['runId... |
'stderr': print(rec[1], end='', file=stderr) else: print('----- output record (type: {0}) -----'.format(rec[0]), file=stdout) print(rec[1], file=stdout) print('----- end of record -----', file=stdout) stdout.flush() files = result.get('files', []) if files: print('--- generated files ---', file=stdout) for item in file... |
code = '' elif result['status'] == 'build-finished': exitCode = result.get('exitCode') vprint_done('Build finished. (exit code = {0})'.format(exitCode), file=stdout) mode = 'continue' code = '' elif result['status'] == 'finished': exitCode = result.get('exitCode') vprint_done('Execution finished. (exit code = {0})'.for... |
'' |
def run(lang, files, session_id, cluster_size, code, clean, build, exec, terminal, basedir, rm, env, env_range, build_range, exec_range, max_parallel, mount, stats, tag, resources, quiet): ''' Run the given code snippet or files in a session. Depending on the session ID you give (default is random), it may reuse an exi... |
colon) of session runtime or programming language.') FILES: The code file(s). Can be added multiple times. ''' if quiet: vprint_info = vprint_wait = vprint_done = _noop else: vprint_info = print_info vprint_wait = print_wait vprint_done = print_done if files and code: print('You can run only either source files or comm... |
command-line code snippet using ' '"-c" option if run without files.', file=sys.stderr) sys.exit(1) envs = _prepare_env_arg(env) resources = _prepare_resource_arg(resources) mount = _prepare_mount_arg(mount) if not (1 <= cluster_size < 4): print('Invalid cluster size.', file=sys.stderr) sys.exit(1) if env_range is None... |
r for v, r in env_range} build_ranges = {v: r for v, r in build_range} exec_ranges = {v: r for v, r in exec_range} env_var_maps = [dict(zip(env_ranges.keys(), values)) for values in itertools.product(*env_ranges.values())] build_var_maps = [dict(zip(build_ranges.keys(), values)) for values in itertools.product(*build_r... |
{k: string.Template(v) for k, v in envs.items()} for env_vmap, build_vmap, exec_vmap in vmaps_product: interpolated_envs = tuple((k, vt.substitute(env_vmap)) for k, vt in env_templates.items()) if build: interpolated_build = build_template.substitute(build_vmap) else: interpolated_build = '*' if exec: interpolated_exec... |
'a positive integer.', file=sys.stderr) sys.exit(1) if terminal: print('You cannot run multiple cases with terminal.', file=sys.stderr) sys.exit(1) if not quiet: vprint_info('Running multiple sessions for the following combinations:') for case in case_set.keys(): pretty_env = ' '.join('{}={}'.format(item[0], item[1]) f... |
client_token=session_id, cluster_size=cluster_size, mounts=mount, envs=envs, resources=resources, tag=tag) except Exception as e: print_error(e) sys.exit(1) if kernel.created: vprint_done('[{0}] Session {0} is ready.'.format(idx, kernel.kernel_id)) else: vprint_done('[{0}] Reusing session {0}...'.format(idx, kernel.ker... |
failed!'.format(idx)) print('{0}: {1}\n{2}'.format( ret.status, ret.reason, ret.text())) return vprint_done('[{0}] Uploading done.'.format(idx)) opts = { 'clean': clean_cmd, 'build': build_cmd, 'exec': exec_cmd, } if not terminal: exec_loop_sync(sys.stdout, sys.stderr, kernel, 'batch', '', opts=opts, vprint_done=vprint... |
vprint_wait('[{0}] Cleaning up the session...'.format(idx)) ret = kernel.destroy() vprint_done('[{0}] Cleaned up the session.'.format(idx)) if stats: _stats = ret.get('stats', None) if ret else None if _stats: _stats.pop('precpu_used', None) _stats.pop('precpu_system_used', None) _stats.pop('cpu_system_used', None) pri... |
BackendError as e: print_fail('[{0}] {1}'.format(idx, e)) return if kernel.created: vprint_done('[{0}] Session {1} is ready.'.format(idx, kernel.kernel_id)) else: vprint_done('[{0}] Reusing session {1}...'.format(idx, kernel.kernel_id)) if not is_multi: stdout = sys.stdout stderr = sys.stderr else: log_dir = Path.home(... |
files: if not is_multi: vprint_wait('[{0}] Uploading source files...'.format(idx)) ret = await kernel.upload(files, basedir=basedir, show_progress=not is_multi) if ret.status // 100 != 2: print_fail('[{0}] Uploading source files failed!'.format(idx)) print('{0}: {1}\n{2}'.format( ret.status, ret.reason, ret.text()), fi... |
vprint_done=indexed_vprint_done, is_multi=is_multi) if terminal: await exec_terminal(kernel) return if code: await exec_loop(stdout, stderr, kernel, 'query', code, vprint_done=indexed_vprint_done, is_multi=is_multi) except BackendError as e: print_fail('[{0}] {1}'.format(idx, e)) raise RuntimeError(e) except Exception ... |
ret else None if _stats: _stats.pop('precpu_used', None) _stats.pop('precpu_system_used', None) _stats.pop('cpu_system_used', None) stats_str = _format_stats(_stats) print(format_info('[{0}] Statistics:'.format(idx)) + '\n{0}'.format(stats_str)) if is_multi: print('Statistics:\n{0}'.format(stats_str), file=stderr) else... |
as session: for idx, case in enumerate(case_set.keys()): if is_multi: _session_id = '{0}-{1}'.format(session_id_prefix, idx) else: _session_id = session_id_prefix envs = dict(case[0]) clean_cmd = clean if clean else '*' build_cmd = case[1] exec_cmd = case[2] _run_legacy(session, idx, _session_id, envs, clean_cmd, build... |
out the stdout/stderr logs stored in ' '~/.cache/backend.ai/client-logs directory.') async with AsyncSession() as session: tasks = [] # TODO: limit max-parallelism using aiojobs for idx, case in enumerate(case_set.keys()): if is_multi: _session_id = '{0}-{1}'.format(session_id_prefix, idx) else: _session_id = session_i... |
is_multi=is_multi)) tasks.append(t) results = await asyncio.gather(*tasks, return_exceptions=True) if any(map(lambda r: isinstance(r, Exception), results)): if is_multi: print_fail('There were failed cases!') sys.exit(1) if is_legacy_server(): _run_cases_legacy() else: loop = asyncio.get_event_loop() try: loop.run_unti... |
def start(lang, session_id, owner, env, mount, tag, resources, cluster_size): ''' Prepare and start a single compute session without executing codes. You may use the created session to execute codes using the "run" command or connect to an application service provided by the session using the "app" command. \b LANG: Th... |
''' if session_id is None: session_id = token_hex(5) else: session_id = session_id ###### envs = _prepare_env_arg(env) resources = _prepare_resource_arg(resources) mount = _prepare_mount_arg(mount) with Session() as session: try: kernel = session.Kernel.get_or_create( lang, client_token=session_id, cluster_size=cluster... |
.format(session_id)) if kernel.service_ports: print_info('This session provides the following app services: ' + ', '.join(sport['name'] for sport in kernel.service_ports)) |
def terminate(sess_id_or_alias, owner, stats): ''' Terminate the given session. SESSID: session ID or its alias given when creating the session. ''' print_wait('Terminating the session(s)...') with Session() as session: has_failure = False for sess in sess_id_or_alias: try: kernel = session.Kernel(sess, owner) ret = ke... |
'to terminate other user\'s session.') has_failure = True except Exception as e: print_error(e) has_failure = True if has_failure: sys.exit(1) else: print_done('Done.') if stats: stats = ret.get('stats', None) if ret else None if stats: print(_format_stats(stats)) else: print('Statistics is not available.') |
def get_custom_view_details(name, auth, url): """ function requires no input and returns a list of dictionaries of custom views from an HPE IMC. Optional name argument will return only the specified view. :param name: str containing the name of the desired custom view :param auth: requests auth object #usually auth.cre... |
:param name: (optional) str of name of specific custom view :return: list of dictionaties containing attributes of the custom views :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> view_details = get_custom_vi... |
get_custom_view_details_url = '/imcrs/plat/res/view/custom/' + str(view_id) f_url = url + get_custom_view_details_url r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 200: current_devices = (json.loads(r.text)) if 'device' in curre... |
def add_devs_custom_views(custom_view_name, dev_list, auth, url): """ function takes a list of devIDs from devices discovered in the HPE IMC platform and and issues a RESTFUL call to add the list of devices to a specific custom views from HPE IMC. :param dev_list: list containing the devID of all devices to be containe... |
auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: str of creation results ( "view " + name + "created successfully" :rtype: str >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.groups import * >>> auth = IMCAuth("http://", "10.101.0.203", "80... |
f_url = url + add_devs_custom_views_url r = requests.put(f_url, data = payload, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents try: if r.status_code == 204: print ('View ' + custom_view_name +' : Devices Successfully Added') return r.status_code except requests.exceptions.Reque... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.