def pseudo_main(): """Basically the main(). Did it this way so it can easily be used as a standalone module or called from another. :return: Exit code. See exist codes in brcddb.brcddb_common :rtype: int """ ip, user_id, pw, outf, sec, s_flag, vd, c_file, fid, log, nl = parse_args() if vd: brcdapi_rest.verbose_debug = True if s_flag: brcdapi_log.set_suppress_all() if not nl: brcdapi_log.open_log(log) if sec is None: sec = 'none' fid_l = None if fid is None else fid.split(',') ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list() ml.append('IP: ' + brcdapi_util.mask_ip_addr(ip, True)) ml.append('ID: ' + user_id) ml.append('security: ' + sec) ml.append('Output file: ' + outf) ml.append('KPI file: ' + str(c_file)) ml.append('FID List: ' + str(fid)) brcdapi_log.log(ml, True) outf = brcdapi_file.full_file_name(outf, '.json') # Create project proj_obj = brcddb_project.new( "Captured_data", datetime.datetime.now().strftime('%d %b %Y %H:%M:%S')) proj_obj.s_python_version(sys.version) proj_obj.s_description("This is a test") # Login session = api_int.login(user_id, pw, ip, sec, proj_obj) if brcdapi_auth.is_error(session): return brcddb_common.EXIT_STATUS_API_ERROR # Collect the data try: api_int.get_batch(session, proj_obj, _kpi_list(session, c_file), fid_l) except BaseException as e: brcdapi_log.exception( 'Programming error encountered. Exception is: ' + str(e), True) # Logout obj = brcdapi_rest.logout(session) if brcdapi_auth.is_error(obj): brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True) # Dump the database to a file if _WRITE: brcdapi_log.log('Saving project to: ' + outf, True) plain_copy = dict() brcddb_copy.brcddb_to_plain_copy(proj_obj, plain_copy) brcdapi_file.write_dump(plain_copy, outf) brcdapi_log.log('Save complete', True) return proj_obj.r_exit_code()
def _create_switch(session, chassis_obj, switch_d, echo): """Creates a logical switch :param session: Session object, or list of session objects, returned from brcdapi.fos_auth.login() :type session: dict :param chassis_obj: Chassis object :type chassis_obj: brcddb.classes.chassis.ChassisObj :param switch_d: Switch object as returned from report_utils.parse_switch_file() :type switch_d: dict :param echo: If True, echo switch configuration details to STD_OUT :type echo: bool """ global _basic_capture_kpi_l fid = switch_d['fid'] buf = 'Creating FID ' + str( fid ) + '. This will take about 20 sec per switch + 25 sec per group of 32 ports.' brcdapi_log.log(buf, True) base = True if switch_d['switch_type'] == 'base' else False ficon = True if switch_d['switch_type'] == 'ficon' else False obj = brcdapi_switch.create_switch(session, fid, base, ficon, echo) if fos_auth.is_error(obj): switch_d['err_msgs'].append('Error creating FID ' + str(fid)) brcdapi_log.log([ switch_d['err_msgs'][len(switch_d['err_msgs']) - 1], fos_auth.formatted_error_msg(obj) ], True) return brcddb_common.EXIT_STATUS_ERROR # re-read the chassis and logical switch data to pick up the switch we just created. session.pop('chassis_wwn', None) api_int.get_batch(session, chassis_obj.r_project_obj(), _basic_capture_kpi_l, None) return chassis_obj.r_switch_obj_for_fid(fid)
def _wrap_up(exit_code): """Write out the collected data in JSON to a plain text file. :param exit_code: Initial exit code :type exit_code: int """ global _proj_obj, _session, _out_f, _switch_obj, _base_switch_obj ec = exit_code if _session is not None: try: obj = brcdapi_rest.logout(_session) if fos_auth.is_error(obj): brcdapi_log.log(fos_auth.formatted_error_msg(obj), True) except BaseException as e: brcdapi_log.log( ['Logout failure. ' + _EXCEPTION_MSG, 'Exception: ' + str(e)], True) _session = None try: _proj_obj.s_new_key('base_switch_wwn', _base_switch_obj.r_obj_key()) _proj_obj.s_new_key('switch_list', [obj.r_obj_key() for obj in _switch_obj]) plain_copy = dict() brcddb_copy.brcddb_to_plain_copy(_proj_obj, plain_copy) brcdapi_file.write_dump(plain_copy, _out_f) except BaseException as e: brcdapi_log.log('Unknown exception: ' + str(e), True) return ec
def clear_stats(session, switch_obj): """Clear all statistical counters associated with a switch :param session: Session object returned from brcdapi.fos_auth.login() :type session: dict :param switch_obj: Switch object :type switch_obj: brcddb.classes.SwitchObj :return: Ending status code :rtype: int """ ec = brcddb_common.EXIT_STATUS_OK stats_list = [ dict(ports=switch_obj.r_port_keys(), content='fibrechannel-statistics'), dict(ports=switch_obj.r_ge_port_keys(), content='gigabitethernet-statistics') ] for stats in stats_list: if len(stats.get('ports')) > 0: pl = list() fid = brcddb_switch.switch_fid(switch_obj) content = {stats.get('content'): pl} for p in stats.get('ports'): d = dict() d.update({'name': p}) d.update({'reset-statistics': 1}) pl.append(d) obj = brcdapi_rest.send_request( session, 'running/brocade-interface/fibrechannel-statistics', 'PATCH', content, fid) if fos_auth.is_error(obj): brcdapi_log.log(fos_auth.obj_error_detail(obj), True) ec = brcddb_common.EXIT_STATUS_ERROR return ec
def _logout(session): """Logout and post message if the logout failed :param session: Session object returned from brcdapi.brcdapi_auth.login() :type session: dict """ obj = brcdapi_rest.logout(session) if brcdapi_auth.is_error(obj): brcdapi_log.log( 'Logout failed:\n' + brcdapi_auth.formatted_error_msg(obj), True)
def _clear_dashboard(session, fid): """Clears the MAPS dashboard :return fid: Fabric ID :rtype fid: int """ content = {'clear-data': True} obj = brcdapi_rest.send_request(session, 'running/brocade-maps/dashboard-misc', 'PUT', content, fid) if brcdapi_auth.is_error(obj): brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True) return -1 return 0
def _capture_data(proj_obj, kpi_l, fid_l, user_id, pw, ip_addr, sec): """Captures data from switch and adds it to the project object :param proj_obj: The project object :type proj_obj: brcddb.classes.project.ProjectObj :param kpi_l: List of KPIs to GET :type kpi_l: list, tuple :param fid_l: FID, or list of FIDs for logical switch level requests. If None, execute requests for all FIDs. :type fid_l: int, list, tuple, None :param user_id: User ID :type user_id: str :param pw: Password :type pw: str :param ip_addr: IP address :type ip_addr: str :param sec: If 'CA' or 'self', uses https to login. Otherwise, http. :type sec: None, str :return: Status code :type: int """ # Login session = api_int.login(user_id, pw, ip_addr, sec, proj_obj) if fos_auth.is_error(session): return brcddb_common.EXIT_STATUS_API_ERROR # api_int.login() prints the error message detail. ec = brcddb_common.EXIT_STATUS_OK # Capture the data api_int.get_batch(session, proj_obj, kpi_l, fid_l) if proj_obj.r_is_any_error(): brcdapi_log.log('Errors encountered. Search the log for "ERROR:".', True) # Logout obj = brcdapi_rest.logout(session) if fos_auth.is_error(obj): brcdapi_log.log(fos_auth.formatted_error_msg(obj), True) ec = brcddb_common.EXIT_STATUS_API_ERROR return ec
def pseudo_main(): """Basically the main(). :return: Exit code :rtype: int """ ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list() ip, user_id, pw, sec, fids, vd, log, nl = parse_args() if vd: brcdapi_rest.verbose_debug = True if not nl: brcdapi_log.open_log(log) fid = int(fids) ml.append('FID: ' + fids) if sec is None: sec = 'none' brcdapi_log.log(ml, True) # Login brcdapi_log.log('Attempting login', True) session = brcdapi_rest.login(user_id, pw, ip, sec) if brcdapi_auth.is_error(session): brcdapi_log.log('Login failed', True) brcdapi_log.log(brcdapi_auth.formatted_error_msg(session), True) return -1 brcdapi_log.log('Login succeeded', True) try: ec = _clear_dashboard(session, fid) except: # Base except because I don't care what went wrong, I just want to make sure we logout. brcdapi_log.exception('Encountered a programming error', True) ec = -1 obj = brcdapi_rest.logout(session) if brcdapi_auth.is_error(obj): brcdapi_log.log('Logout failed:\n' + brcdapi_auth.formatted_error_msg(obj), True) return ec
def _is_error(session, fid, obj): """Tests to see if the API returned an error and aborts the zoning transaction if it did :param session: Session object returned from brcdapi.brcdapi_auth.login() :type session: dict :param fid: Logical FID number to be created. Valid FISs are 1-128. Will return an error if the FID already exists :type fid: int :return: True if an error was returned :rtype: bool """ if brcdapi_auth.is_error(obj): # Commented out code below is redundant because brcdapi.zone methods already print formatted error messages to # the log. Should you need to format error objects into human readable text: # brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True) brcdapi_zone.abort(session, fid, True) return True else: return False
def _enable_switch(session, fid, echo): """Enable switch :param session: Session object returned from brcdapi.fos_auth.login() :type session: dict :param fid: Fabric ID :type fid: int :param echo: If True, echo switch configuration details to STD_OUT :type echo: bool """ obj = brcdapi_switch.fibrechannel_switch(session, fid, {'is-enabled-state': True}, None, echo) if fos_auth.is_error(obj): brcdapi_log.log([ 'Failed to enable FID ' + str(fid), fos_auth.formatted_error_msg(obj) ], True) return brcddb_common.EXIT_STATUS_API_ERROR return brcddb_common.EXIT_STATUS_OK
def _enable_ports(session, fid, port_l, echo): """Enable ports :param session: Session object returned from brcdapi.fos_auth.login() :type session: dict :param fid: Fabric ID :type fid: int :param port_l: Ports in s/p notation to enable :type port_l: list :param echo: If True, echo switch configuration details to STD_OUT :type echo: bool """ if len(port_l) > 0: obj = brcdapi_port.enable_port(session, fid, port_l, echo) if fos_auth.is_error(obj): brcdapi_log.log([ 'Failed to enable ports on FID ' + str(fid), fos_auth.formatted_error_msg(obj) ], True) return brcddb_common.EXIT_STATUS_API_ERROR return brcddb_common.EXIT_STATUS_OK
def pseudo_main(): """Basically the main(). :return: Exit code :rtype: int """ global _DEBUG # Get and validate command line input. ec = brcddb_common.EXIT_STATUS_OK ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list() ip, user_id, pw, sec, file, force, s_flag, echo, vd, log, nl = parse_args() if vd: brcdapi_rest.verbose_debug = True if s_flag: brcdapi_log.set_suppress_all() if not nl: brcdapi_log.open_log(log) if sec is None: sec = 'none' file = brcdapi_file.full_file_name(file, '.xlsx') if ip is not None: if user_id is None: ml.append('Missing user ID, -id') ec = brcddb_common.EXIT_STATUS_INPUT_ERROR if pw is None: ml.append('Missing password, -pw') ec = brcddb_common.EXIT_STATUS_INPUT_ERROR ml.append('File: ' + file) ml.append( 'IP address: ' + brcdapi_util.mask_ip_addr(ip) if isinstance(ip, str) else str(ip)) ml.append('ID: ' + str(user_id)) ml.append('sec: ' + sec) if len(ml) > 0: brcdapi_log.log(ml, True) if ec != brcddb_common.EXIT_STATUS_OK: return ec echo = False if echo is None else echo # Read in the Workbook, generate the portaddress --bind commands, and configure the switch(es) switch_d_list = [ switch_d for switch_d in report_utils.parse_switch_file(file).values() ] session = proj_obj = None try: for switch_d in switch_d_list: switch_d.update(err_msgs=list()) # Create the bind commands if switch_d['bind']: _bind_commands(switch_d) cli_l = switch_d['bind_commands'].copy() i = 0 while i < len(cli_l): cli_l.insert(i, '') i += 16 cli_l.insert( 0, '\n# Bind commands for FID ' + str(switch_d['fid'])) cli_l.append('\n# End bind commands for FID ' + str(switch_d['fid'])) brcdapi_log.log(cli_l, True) # Create the logical switch if ip is not None and switch_d['switch_flag']: if session is None: # Login session = api_int.login(user_id, pw, ip, sec, proj_obj) if fos_auth.is_error(session): return brcddb_common.EXIT_STATUS_API_ERROR if proj_obj is None: # Create a project object proj_obj = brcddb_project.new( 'Create_LS', datetime.datetime.now().strftime('%d %b %Y %H:%M:%S')) proj_obj.s_python_version(sys.version) proj_obj.s_description('Creating logical switches from ' + os.path.basename(__file__)) api_int.get_batch(session, proj_obj, _basic_capture_kpi_l, None) if proj_obj.r_is_any_error(): switch_d['err_msgs'].append( 'Error reading logical switch information from chassis' ) brcdapi_log.log( switch_d['err_msgs'][len(switch_d['err_msgs']) - 1], True) else: ec = _configure_switch(user_id, pw, session, proj_obj, switch_d, force, echo) except BaseException as e: switch_d['err_msgs'].append( 'Programming error encountered. Exception: ' + str(e)) brcdapi_log.log(switch_d['err_msgs'][len(switch_d['err_msgs']) - 1], True) ec = brcddb_common.EXIT_STATUS_ERROR # Logout and create and print a summary report if session is not None: obj = brcdapi_rest.logout(session) if fos_auth.is_error(obj): brcdapi_log.log(fos_auth.formatted_error_msg(obj), True) ec = brcddb_common.EXIT_STATUS_API_ERROR if ip is not None: _print_summary(switch_d_list) return ec
def _add_remove_ports(session, switch_obj, switch_d, force, echo): """Add and remove ports from a logical switch :param session: Session object, or list of session objects, returned from brcdapi.fos_auth.login() :type session: dict :param switch_obj: Chassis object :type switch_obj: brcddb.classes.switch.SwitchObj :param switch_d: Switch object as returned from report_utils.parse_switch_file() :type switch_d: dict :param force: Move the port whether it's online or not. :type force: bool :param echo: If True, echo switch configuration details to STD_OUT :type echo: bool """ # Load common use stuff into local variables ec = brcddb_common.EXIT_STATUS_OK chassis_obj = switch_obj.r_chassis_obj() fid = switch_d['fid'] # Figure out what ports to add or remove _ports_to_move(switch_obj, switch_d, force) # Report any ports that could not be moved. ml = list() for d in [ dict(port_l=switch_d['not_found_ports'], m='were not found:'), dict(port_l=switch_d['online_ports'], m='are online:') ]: if len(d['port_l']) > 0: ml.append('The following ports were not moved because they ' + d['m']) for port in brcddb_util.sp_port_sort(d['port_l']): port_obj = chassis_obj.r_port_obj(port) if port_obj is not None: ml.append( brcddb_port.best_port_name(port_obj, True) + ', ' + brcddb_port.port_best_desc(port_obj)) else: ml.append(port) ec = brcddb_common.EXIT_STATUS_ERROR if len(ml) > 0: brcdapi_log.log(ml, True) default_fid = chassis_obj.r_default_switch_fid() # $ToDo brcdapi_switch.add_ports doesn't remove GE ports # Remove ports obj = brcdapi_switch.add_ports(session, default_fid, fid, switch_d['remove_ports'], None, echo) if fos_auth.is_error(obj): ml = [ 'Error moving ports from FID ' + str('fid') + ' to ' + str(default_fid), fos_auth.formatted_error_msg(obj) ] brcdapi_log.log(ml, True) ec = brcddb_common.EXIT_STATUS_ERROR # Add ports for from_fid, port_d in switch_d['add_ports'].items(): obj = brcdapi_switch.add_ports(session, fid, from_fid, port_d['ports'], port_d['ge_ports'], echo) if fos_auth.is_error(obj): ml = [ 'Error moving ports from FID ' + from_fid + ' to ' + str(fid), fos_auth.formatted_error_msg(obj) ] brcdapi_log.log(ml, True) ec = brcddb_common.EXIT_STATUS_ERROR return ec