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, sec, log, nl = parse_args()
    if sec is None:
        sec = 'none'
    if not nl:
        brcdapi_log.open_log(log)
    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)
    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. Error message is:', True)
        brcdapi_log.log(brcdapi_auth.formatted_error_msg(session), True)
        return -1

    # Logout
    brcdapi_log.log('Login succeeded. Attempting logout', True)
    obj = brcdapi_rest.logout(session)
    if brcdapi_auth.is_error(obj):
        brcdapi_log.log('Logout failed. Error message is:', True)
        brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True)
        return -1
    brcdapi_log.log('Logout succeeded.', True)
    return 1
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
Example #3
0
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()
Example #4
0
def pseudo_main():
    """Basically the main().

    :return: Exit code
    :rtype: int
    """
    ec = 0

    # Get and condition the command line input
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ip, user_id, pw, sec, fid, echo, vd, log, nl = parse_args()
    if vd:
        brcdapi_rest.verbose_debug = True
    if sec is None:
        sec = 'none'
        ml.append('Access:    HTTP')
    else:
        ml.append('Access:    HTTPS')
    if not nl:
        brcdapi_log.open_log(log)
    try:
        fid = int(fid)
        if fid < 1 or fid > 128:
            raise
    except ValueError:
        brcdapi_log.log('Invalid fid. FID must be an integer between 1-128', True)
        return -1
    ml.append('FID:       ' + str(fid))
    brcdapi_log.log(ml, True)
    echo = False if echo is None else echo

    # 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. API error message is:', brcdapi_auth.formatted_error_msg(session)], True)
        return -1
    brcdapi_log.log('Login succeeded.', True)

    # Delete the switch
    try:  # I always do a try in code development so that if there is a code bug, I still log out.
        buf = 'Deleting FID ' + str(fid) + '. This will take about 20 sec per switch + 25 sec per group of 32 ports.'
        brcdapi_log.log(buf, True)
        obj = brcdapi_switch.delete_switch(session, fid, echo)
        if brcdapi_auth.is_error(obj):
            ml = ['Error deleting FID ' + str(fid)]
            ml.append(brcdapi_auth.formatted_error_msg(obj))
            brcdapi_log.log(ml, True)
            ec = -1

    except:  # Bare because I don't care what went wrong. I just want to logout
        brcdapi_log.log('Encountered a programming error', True)
        ec = -1

    # Logout
    obj = brcdapi_rest.logout(session)
    if brcdapi_auth.is_error(obj):
        brcdapi_log.log(['Logout failed. API error message is:',  brcdapi_auth.formatted_error_msg(obj)], True)
    return ec
Example #5
0
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 exit codes in brcddb.brcddb_common
    :rtype: int
    """
    global __version__
    global _DEBUG_id, _DEBUG_pw, _DEBUG_ip

    ec, ip, user_id, pw, sec, scan_flag, fid, cfile, wwn, a_flag, scan_flag, addl_parms = _get_input(
    )

    if ec != brcddb_common.EXIT_STATUS_OK:
        return ec

    # Read the project file
    proj_obj = brcddb_project.read_from(
        brcdapi_file.full_file_name(cfile, '.json'))
    if proj_obj is None:
        return brcddb_common.EXIT_STATUS_ERROR
    fab_obj = None
    if not scan_flag:
        fab_obj = proj_obj.r_fabric_obj(wwn)
        if fab_obj is None:
            brcdapi_log.log(
                wwn + ' does not exist in ' + cfile +
                '. Try using the -scan option', True)
            return brcddb_common.EXIT_STATUS_INPUT_ERROR

    if scan_flag:
        return _scan_fabrics(proj_obj)

    # Login
    session = api_int.login(user_id, pw, ip, sec, proj_obj)
    if fos_auth.is_error(session):
        brcdapi_log.log(fos_auth.formatted_error_msg(session), True)
        return brcddb_common.EXIT_STATUS_ERROR

    # Make the zoning change
    try:
        brcdapi_log.log('Sending zone updates to FID ' + str(fid), True)
        obj = api_zone.replace_zoning(session, fab_obj, fid)
        if fos_auth.is_error(obj):
            brcdapi_log.log(fos_auth.formatted_error_msg(obj), True)
        else:
            brcdapi_log.log('Zone restore completed successfully.', True)

    except BaseException as e:
        brcdapi_log.log(['', 'Software error.', 'Exception: ' + str(e)], True)

    # Logout
    obj = brcdapi_rest.logout(session)
    if fos_auth.is_error(obj):
        brcdapi_log.log(fos_auth.formatted_error_msg(obj), True)

    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 pseudo_main():
    """Basically the main(). Did it this way so it can easily be modified to be called from another script.

    :return: Exit code. See exit codes in brcddb.brcddb_common
    :rtype: int
    """
    # Get the command line input
    ip_addr, user_id, pw, sec = _get_input()

    # Login
    brcdapi_log.log('Attempting login', True)
    session = brcdapi_rest.login(user_id, pw, ip_addr, sec)
    if fos_auth.is_error(session):
        brcdapi_log.log('Login failed. Error message is:', True)
        brcdapi_log.log(fos_auth.formatted_error_msg(session), True)
        return -1
    brcdapi_log.log([
        'Login succeeded', 'Getting certificates. This will take about 30 sec.'
    ], True)

    try:  # This try is to ensure the logout code gets executed regardless of what happened.
        # Get the certificates from the API
        cert_obj = brcdapi_rest.get_request(
            session, 'running/brocade-security/security-certificate')
    except BaseException as e:
        brcdapi_log.exception(
            'Unexpected error encountered. Exception is: ' + str(e), True)

    # Logout
    brcdapi_log.log('Attempting logout', True)
    obj = brcdapi_rest.logout(session)
    if fos_auth.is_error(obj):
        brcdapi_log.log('Logout failed. Error message is:', True)
        brcdapi_log.log(fos_auth.formatted_error_msg(obj), True)
        return -1
    brcdapi_log.log('Logout succeeded.', True)

    # Display the certificates
    if fos_auth.is_error(cert_obj):
        brcdapi_log.exception(
            'Failed to capture certificates.' +
            fos_auth.formatted_error_msg(cert_obj), True)
        return -1
    _cert_detail_report(cert_obj)
    _cert_summary_report(cert_obj)

    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
Example #9
0
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 pseudo_main():
    """Basically the main(). Did it this way to use with IDE
    :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 sec is None:
        sec = 'none'
    if not nl:
        brcdapi_log.open_log(log)
    fl = [int(f) for f in fids.split(',')]
    ml.append('FIDs: ' + fids)
    brcdapi_log.log(ml, True)

    # Login
    session = brcdapi_rest.login(user_id, pw, ip, sec)
    if brcdapi_auth.is_error(session):
        brcdapi_log.log(
            'Login failed:\n' + brcdapi_auth.formatted_error_msg(session),
            True)
        return -1

    # Get the Chassis data
    brcdapi_log.log('Chassis Data\n------------', True)
    for uri in _chassis_rest_data:
        brcdapi_log.log('URI: ' + uri, True)
        try:
            obj = brcdapi_rest.get_request(session, uri)
            if brcdapi_auth.is_error(
                    obj):  # Set breakpoint here to inspect response
                brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True)
        except BaseException as e:
            brcdapi_log.exception(
                ['Error requesting ' + uri, 'Exception: ' + str(e)], True)

    # Get the Switch data
    for vf_id in fl:
        brcdapi_log.log(
            'Switch data. FID: ' + str(vf_id) + '\n---------------------',
            True)
        for buf in fid_rest_data:
            brcdapi_log.log('URI: ' + buf, True)
            try:
                obj = brcdapi_rest.get_request(session, buf, vf_id)
                if brcdapi_auth.is_error(
                        obj):  # Set breakpoint here to inspect response
                    brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj),
                                    True)
            except BaseException as e:
                brcdapi_log.exception(
                    ['Error requesting ' + buf, 'Exception: ' + str(e)], True)

    # Logout
    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 -1

    return 0
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
    """
    ec = brcddb_common.EXIT_STATUS_OK

    # Get the user input
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ip, user_id, pw, sec, s_flag, fid, vd, log, nl = parse_args()
    if not nl:
        brcdapi_log.open_log(log)
    if vd:
        brcdapi_rest.verbose_debug = True
    if s_flag:
        brcdapi_log.set_suppress_all()
    if sec is None:
        sec = 'none'
    fid_list = None if fid is None else [int(i) for i in fid.split(',')]
    ml.extend([
        'IP address: ' + ip, 'User ID:    ' + user_id, 'Security:   ' + sec,
        'Surpress:   ' + str(s_flag),
        'FID:        ' + 'Automatic' if fid is None else fid
    ])
    brcdapi_log.log(ml, True)

    # Create the project
    proj_obj = brcddb_project.new(
        'Captured_data',
        datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))
    proj_obj.s_python_version(sys.version)
    proj_obj.s_description('Unused ports to disable')

    # Login
    session = api_int.login(user_id, pw, ip, sec, proj_obj)
    if fos_auth.is_error(session):
        brcdapi_log.log(fos_auth.formatted_error_msg(session), True)
        return brcddb_common.EXIT_STATUS_ERROR

    # Capture data - stats are cleared on a per port basis so this is needed to determine what the ports are.
    try:  # I always put all code after login in a try/except so that if I have a code bug, I still logout
        brcdapi_log.log('Capturing data', True)
        api_int.get_batch(session, proj_obj, chassis_uris, list(),
                          fid_list)  # Captured data is put in proj_obj
        chassis_obj = proj_obj.r_chassis_obj(session.get('chassis_wwn'))

        # Clear stats on each switch
        for switch_obj in chassis_obj.r_switch_objects():
            fid = brcddb_switch.switch_fid(switch_obj)
            if fid_list is None or fid in fid_list:
                temp_ec = clear_stats(session, switch_obj)
                ec = temp_ec if ec != brcddb_common.EXIT_STATUS_OK else ec
    except:  # Bare because I don't care what happened. I just want to logout.
        brcdapi_log.exception('Programming error encountered', True)
        ec = brcddb_common.EXIT_STATUS_ERROR

    # Logout
    obj = brcdapi_rest.logout(session)
    if fos_auth.is_error(obj):
        brcdapi_log.log(fos_auth.formatted_error_msg(obj), True)
        return brcddb_common.EXIT_STATUS_ERROR

    return ec
def pseudo_main():
    """Basically the main().

    :return: Exit code
    :rtype: int
    """
    global _DEBUG

    # Get and validate command line input
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ip, user_id, pw, sec, fid_str, vd, log, nl = parse_args()
    if not nl:
        brcdapi_log.open_log(log)
    if vd:
        brcdapi_rest.verbose_debug = True
    if fid_str.isdigit():
        fid = int(fid_str)
    else:
        brcdapi_log.log('Invalid FID: ' + fid_str, True)
        return -1
    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)

    ec = 0
    try:  # I always do a try in code development so that if there is a code bug, I still log out.

        # Get FC port list for this FID by reading the configurations
        kpi = 'running/brocade-interface/fibrechannel'
        obj = brcdapi_rest.get_request(session, kpi, fid)
        if brcdapi_auth.is_error(obj):
            brcdapi_log.log('Failed to read ' + kpi + ' for fid ' + str(fid),
                            True)
            ec = -1

        else:
            # Get the port lists
            fc_plist = [port.get('name') for port in obj.get('fibrechannel')]

            # Disable all ports and set to the default configuration.
            brcdapi_log.log(
                'Disabling all ports of fid: ' + str(fid) +
                ' and setting to default configuration', True)
            obj = brcdapi_port.default_port_config(session, fid, fc_plist)
            if brcdapi_auth.is_error(obj):
                brcdapi_log.log(
                    'Set ports to default for FID ' + str(fid) + ' failed',
                    True)
                brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True)
                ec = -1
            else:
                brcdapi_log.log(
                    'Successfully set all ports for FID ' + str(fid) +
                    ' to the default configuration', True)

    except:
        brcdapi_log.log('Encountered a programming error', True)
        ec = -1

    # Logout
    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 _patch_zone_db(proj_obj, eff_cfg):
    """Replaces the zoning in the fabric(s).

    :param proj_obj: Project object
    :type proj_obj: brcddb.classes.project.ProjectObj
    :param eff_cfg: Name of zone configuration to activate. None if no zone configuration to activate.
    :type eff_cfg: str, None
    :return: List of error messages. Empty list if no errors found
    :rtype: list()
    """
    rl = list()  # List of error messages to return
    base_fab_obj = proj_obj.r_get('zone_merge/base_fab_obj')
    if base_fab_obj is None:
        rl.append(
            'base_fab_obj is None')  # There is a code bug if this happens
        return rl

    update_count = 0
    for fab_obj in proj_obj.r_fabric_objects():

        # Get the login credentials
        ip_addr = fab_obj.r_get('zone_merge/ip')
        id = fab_obj.r_get('zone_merge/id')
        pw = fab_obj.r_get('zone_merge/pw')
        sec = fab_obj.r_get('zone_merge/sec')
        fid = fab_obj.r_get('zone_merge/fid')
        update = fab_obj.r_get('zone_merge/update')
        if ip_addr is None or id is None or pw is None or sec is None or fid is None or update is None or not update:
            continue

        # Login
        session = api_int.login(id, pw, ip_addr, sec, proj_obj)
        if fos_auth.is_error(session):
            rl.append(fos_auth.formatted_error_msg(session))
            return rl

        # Send the changes to the switch
        brcdapi_log.log(
            'Sending zone updates to ' +
            brcddb_fabric.best_fab_name(fab_obj, wwn=True), True)
        try:
            obj = api_zone.replace_zoning(session, base_fab_obj, fid)
            if fos_auth.is_error(obj):
                rl.append(fos_auth.formatted_error_msg(obj))
            else:
                update_count += 1
                if isinstance(eff_cfg, str):
                    obj = api_zone.enable_zonecfg(session, None, fid, eff_cfg)
                    if fos_auth.is_error(obj):
                        rl.append(fos_auth.formatted_error_msg(obj))
        except:
            rl.append('Software fault in api_zone.replace_zoning()')

        # Logout
        obj = brcdapi_rest.logout(session)
        if fos_auth.is_error(obj):
            rl.append(fos_auth.formatted_error_msg(obj))

        brcdapi_log.log(str(update_count) + ' switch(es) updated.', True)

    return rl
def pseudo_main():
    """Basically the main(). Did it this way to use with IDE

    :return: Exit code
    :rtype: int
    """
    global _DEBUG_IP, _DEBUG_ID, _DEBUG_PW, _DEBUG_SEC, _DEBUG_SUP, _DEBUG_LOG, _DEBUG_NL, _DEBUG_VERBOSE, __version__
    global _DEBUG_API, _DEBUG_MODE, _DEBUG_FOLDER

    ec = 0  # Return error code

    # Set up the log file
    _setup_log(_DEBUG_LOG, _DEBUG_NL)

    if _DEBUG_VERBOSE:
        brcdapi_rest.verbose_debug = True  # A proper Python method would set this via a method in brcdapi_rest

    if _DEBUG_API:
        brcdapi_rest.set_debug(_DEBUG_API, _DEBUG_MODE, _DEBUG_FOLDER)

    # Login
    sec = 'none' if _DEBUG_SEC is None else _DEBUG_SEC
    brcdapi_log.log('Attempting login')
    session = brcdapi_rest.login(_DEBUG_ID, _DEBUG_PW, _DEBUG_IP, sec)
    if brcdapi_auth.is_error(session):
        brcdapi_log.log(
            ['Login failed:',
             brcdapi_auth.formatted_error_msg(session)],
            echo=True)
        return -1
    else:
        brcdapi_log.log('Login Succeeded', echo=True)
    """ I always put code after the login and before the logout in between try & except. It is especially useful during
    code development because if there is a bug in your code, you still logout. If you are new to Python, try says
    try to execute this code and if an error is encountered, execute what comes after "except:". Its common in
    Python scripting to just "let it rip" and handle errors in an exception but the intent in that case is that you
    know what the potential errors will be. Each exception has it's own type. For example, if you attempt to read a
    file that doesn't exist, the exception code is FileNotFoundError so the code would look something like:
    
    try:
        f = open(file, 'rb')
    except FileNotFoundError:
        brcdapi_log('File ' + file + ' not found', True
          
    So the idea is that you have some idea about what you are tyring to do. Its a bit of a fau pax in Python to have
    just "except:". This is referred to as a "bare except". Since this is for code development, I don't care what the
    exception is. I just want to fall through to ensure I logout. Otherwise, if my script crashed I have to use the CLI
    to determine what my login session ID is and then use another CLI command to terminate the session. So the bare
    except below is frowned upon by the purest but, IMO, it's a reasonable in this case."""

    try:
        # Before anything can be done with switches, you need to know what the switches are. Since the order of other
        # chassis data doesn't matter, we may as well capture all the chassis data at once.
        fid_list = _get_chassis_data(session)
        if len(fid_list) == 0:
            # If the switch is not VF enabled, fid_list is empty. I'm appending None here so that the loop below that
            # gets switch data is executed. Note that None type is used in the driver for non-VF enabled switches.
            fid_list.append(None)

        # Now get the switch data, fabric, and port data.
        for fid in fid_list:
            _get_switch_data(session, fid)

    except BaseException as e:
        brcdapi_log.log(
            ['Encountered a programming error.', 'Exception is: ' + str(e)],
            True)
        ec = -1

    # Logout
    obj = brcdapi_rest.logout(session)
    if brcdapi_auth.is_error(obj):
        brcdapi_log.log(
            ['Logout failed:',
             brcdapi_auth.formatted_error_msg(obj)], True)
        ec = -1

    return ec
Example #15
0
def pseudo_main():
    """Basically the main().

    :return: Exit code
    :rtype: int
    """
    global _DEBUG, _sfp_monitoring_system

    # Get and validate the command line input
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ip, user_id, pw, sec, fid, new_policy, file, mp, enable_flag, s_flag, vd, log, nl = parse_args(
    )
    if vd:
        brcdapi_rest.verbose_debug = True
    if not nl:
        brcdapi_log.open_log(log)
    if s_flag:
        brcdapi_log.set_suppress_all()
    fid = int(fid)
    if sec is None:
        sec = 'none'
    ml.extend([
        'FID:                 ' + str(fid),
        'New policy:          ' + new_policy,
        'SFP rules file:      ' + str(file),
        'Policy to clone:     ' + 'Active' if mp is None else mp,
        'Activate new policy: ' + 'Yes' if enable_flag else 'No',
        'The \'User Warning: Data Validation ...\' can be ignored.',
    ])
    brcdapi_log.log(ml, True)

    # Login
    session = api_int.login(user_id, pw, ip, sec)
    if brcdapi_auth.is_error(
            session):  # api_int.login() logs detailed error message
        return brcddb_common.EXIT_STATUS_API_ERROR

    # try/except used during development to ensure logout due to programming errors.
    ec = brcddb_common.EXIT_STATUS_ERROR  # Return code normally gets overwritten
    try:
        if file is None:
            sfp_rules = list()
        else:
            file = brcdapi_file.full_file_name(file, '.xlsx')
            brcdapi_log.log(
                'Adding rules can take up to a minute. Please be patient.',
                True)
            _sfp_monitoring_system = [
                'CURRENT', 'RXP', 'SFP_TEMP', 'TXP', 'VOLTAGE'
            ]
            sfp_rules = report_utils.parse_sfp_file_for_rules(
                file, _get_groups(session, fid))
        if sfp_rules is None:
            brcdapi_log.log('Error opening or reading ' + file, True)
        else:
            ec = _modify_maps(session, fid, sfp_rules, new_policy, mp,
                              enable_flag)
    except BaseException as e:
        brcdapi_log.log(
            'Programming error encountered. Exception is: ' + str(e), True)

    obj = brcdapi_rest.logout(session)
    if brcdapi_auth.is_error(obj):
        brcdapi_log.log(
            'Logout failed. API response:\n' +
            brcdapi_auth.formatted_error_msg(obj), True)
        ec = brcddb_common.EXIT_STATUS_API_ERROR

    return ec
Example #16
0
def pseudo_main():
    """Basically the main().

    :return: Exit code
    :rtype: int
    """
    ec = 0

    # Get and condition the command line input
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ip, user_id, pw, sec, fid, name, did, idid, xisl, base, ficon, i_ports, i_ge_ports, es, ep, echo, vd = parse_args(
    )
    if vd:
        brcdapi_rest.verbose_debug = True
    if sec is None:
        sec = 'none'
        ml.append('Access:        HTTP')
    else:
        ml.append('Access:        HTTPS')
    try:
        fid = int(fid)
        if fid < 1 or fid > 128:
            raise
    except:
        brcdapi_log.log('Invalid fid. FID must be an integer between 1-128',
                        True)
        return -1
    if did is not None:
        try:
            did = int(did)
            if did < 1 or did > 239:
                raise
        except:
            brcdapi_log.log(
                'Invalid DID. DID must be an integer between 1-239', True)
            return -1
    ml.append('FID:           ' + str(fid))
    ml.append('Name:          ' + str(name))
    ml.append('DID:           ' + str(did))
    ml.append('Insistent:     ' + str(idid))
    ml.append('xisl:          ' + str(xisl))
    ml.append('base:          ' + str(base))
    ml.append('ficon:         ' + str(ficon))
    ml.append('ports:         ' + str(i_ports))
    ml.append('ge_ports:      ' + str(i_ge_ports))
    ml.append('Enable switch: ' + str(es))
    ml.append('Enable ports:  ' + str(ep))
    brcdapi_log.log(ml, True)
    base = False if base is None else base
    ficon = False if ficon is None else ficon
    es = False if es is None else es
    ep = False if ep is None else ep
    echo = False if echo is None else echo

    # Login
    brcdapi_log.log('Attempting login', True)
    session = brcdapi_rest.login(user_id, pw, ip, sec)
    if pyfos_auth.is_error(session):
        brcdapi_log.log([
            'Login failed. API error message is:',
            pyfos_auth.formatted_error_msg(session)
        ], True)
        return -1
    brcdapi_log.log('Login succeeded.', True)

    try:  # I always do a try in code development so that if there is a code bug, I still log out.

        # Get a list of ports to move to the new switch
        port_d, ge_port_d = _parse_ports(session, fid, i_ports, i_ge_ports,
                                         echo)

        # We're done with conditioning the user input. Now create the logical switch.
        ec = create_ls(session, fid, name, did, idid, xisl, base, ficon,
                       port_d, ge_port_d, es, ep, echo)

    except:
        brcdapi_log.log('Encountered a programming error', True)
        ec = -1

    # Logout
    obj = brcdapi_rest.logout(session)
    if pyfos_auth.is_error(obj):
        brcdapi_log.log([
            'Logout failed. API error message is:',
            pyfos_auth.formatted_error_msg(obj)
        ], True)
    return ec
def pseudo_main():
    """Basically the main().

    :return: Exit code
    :rtype: int
    """
    global _DEBUG

    # Get and validate command line input
    ec, ip, user_id, pw, sec, input_d = _get_input()
    if ec != 0:
        return ec

    # Login
    brcdapi_log.log('Attempting login', True)
    session = brcdapi_rest.login(user_id, pw, ip, sec)
    if fos_auth.is_error(session):
        brcdapi_log.log(fos_auth.formatted_error_msg(session), True)
        return -1
    brcdapi_log.log('Login succeeded', True)

    ec = 0
    uri = 'running/brocade-chassis/management-interface-configuration'

    try:  # try/except so that no matter what happens, the logout code gets executed.

        # Display initial read (GET) of parameters
        brcdapi_log.log(['', 'Before Changes:'], True)
        obj = brcdapi_rest.get_request(session, uri)
        if fos_auth.is_error(obj):
            brcdapi_log.log(fos_auth.formatted_error_msg(obj), True)
            ec = -1
        else:
            brcdapi_log.log(pprint.pformat(obj), True)

        if ec == 0:

            # Make the changes
            content_d = dict()
            for k, v in input_d.items():
                if v is not None:
                    content_d.update({k: v})
            if len(content_d) == 0:
                brcdapi_log.log('No changes to make.', True)
            else:
                obj = brcdapi_rest.send_request(
                    session, uri, 'PATCH',
                    {'management-interface-configuration': content_d})
                if fos_auth.is_error(obj):
                    brcdapi_log.log(fos_auth.formatted_error_msg(obj), True)
                    ec = -1
                else:

                    # Display read (GET) after changing parameters
                    brcdapi_log.log(['', 'After Changes:'], True)
                    obj = brcdapi_rest.get_request(session, uri)
                    if fos_auth.is_error(obj):
                        brcdapi_log.log(fos_auth.formatted_error_msg(obj),
                                        True)
                        ec = -1
                    else:
                        brcdapi_log.log(pprint.pformat(obj), True)

    except BaseException as e:
        brcdapi_log.exception(
            'Programming error encountered. Exception is: ' + str(e), True)
        ec = -1

    # Logout
    obj = brcdapi_rest.logout(session)
    if fos_auth.is_error(obj):
        brcdapi_log.log('Logout failed', True)
        ec = -1
    else:
        brcdapi_log.log('Logout succeeded', True)

    return ec
def pseudo_main():
    """Basically the main(). Did it this way to use with IDE
    :return: Exit code
    :rtype: int
    """
    global _DEBUG

    # Get the command line input
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ip, user_id, pw, sec, fid_str, vd, log, nl = parse_args()
    if vd:
        brcdapi_rest.verbose_debug = True
    if sec is None:
        sec = 'none'
    if not nl:
        brcdapi_log.open_log(log)
    ml.append('FID: ' + fid_str)
    try:
        fid = int(fid_str)
    except ValueError:
        brcdapi_log.log(
            'Invalid FID, -f. FID must be an integer between 1-128')
    brcdapi_log.log(ml, True)

    # Login
    session = brcdapi_rest.login(user_id, pw, ip, sec)
    if brcdapi_auth.is_error(session):
        brcdapi_log.log(
            'Login failed:\n' + brcdapi_auth.formatted_error_msg(session),
            True)
        return -1

    ec = 0  # Error code. 0: No errors. -1: error encountered
    port_info_d = dict()  # Will use this to store basic port information
    port_stats_d = dict()  # Will use this to store port statistics in

    # You may want to put better error checking in your code as well as use a more efficient code. A verbose coding
    # style was used here for readability.
    try:
        # Get the switch WWN
        brcdapi_log.log('Capturing chassis Data', True)
        uri = 'running/brocade-fibrechannel-logical-switch/fibrechannel-logical-switch'
        obj = brcdapi_rest.get_request(session, uri)
        if brcdapi_auth.is_error(obj):
            brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True)
            ec = -1
        else:
            # Find the switch with the matching FID
            switch_wwn = None
            for switch_obj in obj['fibrechannel-logical-switch']:
                if switch_obj['fabric-id'] == fid:
                    switch_wwn = switch_obj['switch-wwn']
                    break
            if switch_wwn is None:
                brcdapi_log.log(
                    'Logical switch for FID ' + str(fid) + 'not found', True)
                ec = -1

        # Get some basic port information
        if ec == 0:  # Make sure we didn't encountered any errors above
            # It's common to keep track of other port information, such as the user friendly name and FC address. Below
            # captures this basic port information.
            brcdapi_log.log('Capturing basic port information.', True)
            uri = 'running/brocade-interface/fibrechannel'
            port_info = brcdapi_rest.get_request(session, uri, fid)
            if brcdapi_auth.is_error(port_info):
                brcdapi_log.log(brcdapi_auth.formatted_error_msg(port_info),
                                True)
                ec = -1
            else:
                # To make it easier to match the port information with the port statistics, we're going to create a
                # a dictionary using the port name (port number) as the key
                for port_obj in port_info['fibrechannel']:
                    port_info_d.update({port_obj['name']: port_obj})

        # Capture the port statistics
        if ec == 0:  # Make sure we didn't encountered any errors above
            brcdapi_log.log('Capturing port statistics', True)
            uri = 'running/brocade-interface/fibrechannel-statistics'
            port_stats = brcdapi_rest.get_request(session, uri, fid)
            if brcdapi_auth.is_error(port_stats):
                brcdapi_log.log(brcdapi_auth.formatted_error_msg(port_stats),
                                True)
                ec = -1
            else:
                # We could just add each port to the database here but since it's common to capture additional
                # information, such as determining the login alias(es), we'll add it to a dictionary as was done with
                # the basic port information
                for port_obj in port_stats['fibrechannel-statistics']:
                    port_stats_d.update({port_obj['name']: port_obj})

        # Add all the ports to the database
        if ec == 0:  # Make sure we didn't encountered any errors above
            brcdapi_log.log('Adding key value pairs to the database.', True)
            for port_num, port_obj in port_info_d.items():
                sub_key = 'fcid-hex'  # Just using the FC address for this example
                _db_add(switch_wwn, port_num, sub_key, port_obj[sub_key])
                for k, v in port_stats_d[port_num].items():
                    _db_add(switch_wwn, port_num, k, v)

    except:  # Bare because I don't care what went wrong. I just want to logout
        # The brcdapi_log.exception() method precedes the passed message parameter with a stack trace
        brcdapi_log.exception(
            'Unknown programming error occured while processing: ' + uri, True)

    # Logout
    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 -1

    return 0
def pseudo_main():
    """Basically the main().

    :return: Exit code
    :rtype: int
    """
    global _DEBUG

    # Get and validate command line input
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ip, user_id, pw, sec, fid_str, vd, log, nl = parse_args()
    if not nl:
        brcdapi_log.open_log(log)
    if vd:
        brcdapi_rest.verbose_debug = True
    if fid_str.isdigit():
        fid = int(fid_str)
    else:
        brcdapi_log.log('Invalid FID: ' + fid_str, True)
        return -1
    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)

    ec = 0
    try:  # I always do a try in code development so that if there is a code bug, I still log out.

        # Get FC port list for this FID by reading the configurations
        kpi = 'running/brocade-interface/fibrechannel'
        obj = brcdapi_rest.get_request(session, kpi, fid)
        if brcdapi_auth.is_error(obj):
            brcdapi_log.log('Failed to read ' + kpi + ' for fid ' + str(fid),
                            True)
            ec = -1

        else:
            fc_plist = [port.get('name') for port in obj.get('fibrechannel')]
            pl = list()
            content = {'fibrechannel': pl}
            for p in fc_plist:
                d = {
                    'name': p,
                    'user-friendly-name':
                    'port_' + p.replace('/', '_'),  # Name port "port_s_p"
                    'los-tov-mode-enabled': 2  # Enable LOS_TOV
                }
                # For other port configuration parameters, search the Rest API Guide or Yang models for
                # brocade-interface/fibrechannel
                pl.append(d)
            # PATCH only changes specified leaves in the content for this URI. It does not replace all resources
            obj = brcdapi_rest.send_request(
                session, 'running/brocade-interface/fibrechannel', 'PATCH',
                content, fid)
            if brcdapi_auth.is_error(obj):
                brcdapi_log.log('Error configuring ports for FID ' + str(fid),
                                True)
                brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True)
                ec = -1
            else:
                brcdapi_log.log(
                    'Successfully configured ports for FID ' + str(fid), True)

    except:  # Bare because I don't care what went wrong at this point. I just want to log out no matter what happens.
        brcdapi_log.log('Encountered a programming error', True)
        ec = -1

    # Logout
    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
Example #20
0
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