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
Beispiel #2
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
Beispiel #3
0
def login(user_id, pw, ip_addr, https='none', proj_obj=None):
    """Log in and capture a list of supported modules.

    :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 https: If 'CA' or 'self', uses https to login. Otherwise, http.
    :type https: None, str
    :param proj_obj: Project object
    :type proj_obj: brcddb.classes.project.ProjectObj, None
    :return: session
    :rtype: dict
    """
    # Attempt to log in
    tip = brcdapi_util.mask_ip_addr(ip_addr, True)
    session = brcdapi_rest.login(user_id, pw, ip_addr, https)
    if pyfos_auth.is_error(session):
        brcdapi_log.log(tip + ' Login failed', True)
        _process_errors(session, '/rest/login', session, proj_obj)
        return session
    else:
        brcdapi_log.log(tip + ' Login succeeded', True)

    # Figure out what modules this FOS version supports
    # Step 1: Read all the module information from FOS
    uri = 'brocade-module-version'
    obj = brcdapi_rest.get_request(session, uri)
    if pyfos_auth.is_error(obj):
        brcdapi_log.log(tip + ' ERROR: ' + uri + '\n' + pyfos_auth.formatted_error_msg(obj), True)
        return session

    # Step 2: Parse the module information and add it to the session object
    kpi_list = list()
    for mod_obj in obj.get(uri).get('module'):
        name = mod_obj.get('name')
        if name is None:
            brcdapi_log.exception("'name' mising in brocade-module-version", True)
            continue
        kpi_list.append(name)
        try:  # I think 'object' will always be there, just empty when there are no objects. Try/Except just in case.
            for mod_object in mod_obj.get('objects').get('object'):
                kpi_list.append(name + '/' + mod_object)
        except:
            pass
    session.update(dict(supported_uris=kpi_list))

    return session
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
Beispiel #5
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().

    :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 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
Beispiel #8
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
    """
    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 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(user_id, pw, ip, sec, vd, log, nl):
    """Basically the main().

    :param user_id: User ID
    :type user_id: str
    :param pw: Password
    :type pw: str
    :param ip: IP address
    :type ip: str
    :param sec: Security. 'none' for HTTP, 'self' for self signed certificate, 'CA' for signed certificate
    :type sec: str
    :param vd: When True, enables debug logging
    :type vd: bool
    :return: Exit code
    :rtype: int
    """
    fid = _DEBUG_FID
    save_flag = False

    if vd:
        brcdapi_rest.verbose_debug = True
    if not nl:
        brcdapi_log.open_log(log)

    # 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)

    # A check sum is needed to save any updates
    checksum, obj = brcdapi_zone.checksum(session, fid, True)
    if checksum is None:
        _logout(session)
        return -1

    # try/except was so that during development a bug would not cause an abort and skip the logout
    try:
        # Create aliases
        if _DEBUG_CREATE_ALIASES:
            save_flag = True
            brcdapi_log.log('Creating aliases for fid: ' + str(fid), True)
            if _is_error(
                    session, fid,
                    brcdapi_zone.create_aliases(session, fid,
                                                _DEBUG_ALIAS_LIST, True)):
                _logout(session)
                return -1

        # Create zones
        if _DEBUG_CREATE_ZONES:
            save_flag = True
            brcdapi_log.log('Creating zones for fid: ' + str(fid), True)
            if _is_error(
                    session, fid,
                    brcdapi_zone.create_zones(session, fid, _DEBUG_ZONE_LIST,
                                              True)):
                _logout(session)
                return -1

        # Create zone configurations
        if _DEBUG_CREATE_ZONECFGS:
            save_flag = True
            brcdapi_log.log(
                'Creating zone configurations for fid: ' + str(fid), True)
            for k, v in _DEBUG_ZONECFG_LIST.items():
                if _is_error(
                        session, fid,
                        brcdapi_zone.create_zonecfg(session, fid, k, v, True)):
                    _logout(session)
                    return -1

        # Delete zone configurations. If you are also deleting zones and a zone is in a defined configuration, the
        # delete will fail. This is why the zone configuration delete is first.
        if _DEBUG_DELETE_ZONECFGS:
            save_flag = True
            brcdapi_log.log(
                'Deleting zone configurations for fid: ' + str(fid), True)
            for k in _DEBUG_ZONECFG_DEL_LIST:
                if _is_error(session, fid,
                             brcdapi_zone.del_zonecfg(session, fid, k, True)):
                    _logout(session)
                    return -1

        # Delete zones. If you are also deleting aliases and an alias is in a defined zone, the delete will fail. This
        # is why the zone delete is before the alias delete.
        if _DEBUG_DELETE_ZONES:
            save_flag = True
            brcdapi_log.log('Deleting zones for fid: ' + str(fid), True)
            if _is_error(
                    session, fid,
                    brcdapi_zone.del_zones(session, fid, _DEBUG_ZONE_DEL_LIST,
                                           True)):
                _logout(session)
                return -1

        # Delete aliases
        if _DEBUG_DELETE_ALIASES:
            save_flag = True
            brcdapi_log.log('Deleting aliases for fid: ' + str(fid), True)
            if _is_error(
                    session, fid,
                    brcdapi_zone.del_aliases(session, fid,
                                             _DEBUG_ALIAS_DEL_LIST, True)):
                _logout(session)
                return -1

        if _DEBUG_MODIFY_ZONE:
            save_flag = True
            brcdapi_log.log(
                'Modifying ZONE ' + _DEBUG_ZONE_MODIFY + ' in fid: ' +
                str(fid), True)
            if _is_error(
                    session, fid,
                    brcdapi_zone.modify_zone(session, fid, _DEBUG_ZONE_MODIFY,
                                             _DEBUG_ZONE_ADD_MEMS,
                                             _DEBUG_ZONE_DEL_MEMS,
                                             _DEBUG_ZONE_ADD_PMEMS,
                                             _DEBUG_ZONE_DEL_PMEMS, True)):
                _logout(session)
                return -1

        if _DEBUG_MODIFY_ZONECFG:
            save_flag = True
            brcdapi_log.log(
                'Modifying zone configuration ' + _DEBUG_ZONECFG_MODIFY +
                ' in fid: ' + str(fid), True)
            if len(_DEBUG_ZONECFG_ADD_MEMS) > 0:
                if _is_error(
                        session, fid,
                        brcdapi_zone.zonecfg_add(session, fid,
                                                 _DEBUG_ZONECFG_MODIFY,
                                                 _DEBUG_ZONECFG_ADD_MEMS,
                                                 True)):
                    _logout(session)
                    return -1
            if len(_DEBUG_ZONECFG_DEL_MEMS) > 0:
                if _is_error(
                        session, fid,
                        brcdapi_zone.zonecfg_remove(session, fid,
                                                    _DEBUG_ZONECFG_MODIFY,
                                                    _DEBUG_ZONECFG_DEL_MEMS,
                                                    True)):
                    _logout(session)
                    return -1

        if _DEBUG_DISABLE_ZONECFG:
            brcdapi_log.log(
                'Disabling zone configuration ' + _DEBUG_ZONECFG + ', fid: ' +
                str(fid), True)
            if _is_error(
                    session, fid,
                    brcdapi_zone.disable_zonecfg(session, checksum, fid,
                                                 _DEBUG_ZONECFG, True)):
                _logout(session)
                return -1
            save_flag = False  # Enabling a zone configuration does a configuration save

        if _DEBUG_ENABLE_ZONECFG:
            brcdapi_log.log(
                'Enabling zone configuration ' + _DEBUG_ZONECFG + ', fid: ' +
                str(fid), True)
            if _is_error(
                    session, fid,
                    brcdapi_zone.enable_zonecfg(session, checksum, fid,
                                                _DEBUG_ZONECFG, True)):
                _logout(session)
                return -1
            save_flag = False  # Enabling a zone configuration does a configuration save

        if save_flag:
            if _is_error(session, fid,
                         brcdapi_zone.save(session, fid, checksum, True)):
                _logout(session)
                return -1

    except:
        brcdapi_log.log('Logging out', True)
        _logout(session)
        brcdapi_log.exception('Exception', True)
        return -1

    brcdapi_log.log('Logging out', True)
    _logout(session)
    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