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
Ejemplo n.º 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
Ejemplo n.º 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 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 _get_chassis_data(session):
    """Capture chassis data as would be returned from (not all chassis data is being captured):

    :param session: The session object returned from brcdapi.fos_auth.login()
    :type session: dict
    :return: FID list
    :rtype: list
    """
    global _chassis_rest_data

    # Get all the chassis data
    # Note that in Gen 6 and above, the license ID, brocade-chassis/chassis/license-id, may not be the chassis WWN
    for kpi in _chassis_rest_data:  # See comments with _chassis_rest_data above
        ml = ['', kpi
              ]  # The first member as '' inserts a blank line before the KPI
        obj = brcdapi_rest.get_request(session, kpi)
        if brcdapi_auth.is_error(obj):
            ml.append(brcdapi_auth.formatted_error_msg(obj))
        else:
            ml.append(pprint.pformat(obj))
        brcdapi_log.log(ml, True)
    """This is essentially a hybrid of lscfg --show and switchshow. This is where all the logical switches and ports
    associated with those logical switches are reported. I broke this out from _chassis_rest_data because we need to
    pick out the fabric IDs of all the logical switches."""

    kpi = 'running/brocade-fibrechannel-logical-switch/fibrechannel-logical-switch'
    ml = ['', kpi]
    obj = brcdapi_rest.get_request(session, kpi)
    if brcdapi_auth.is_error(obj):
        ml.append(brcdapi_auth.formatted_error_msg(obj))
        brcdapi_log.log(ml, True)
        return list(
        )  # A return in the middle of a method is common in Python after an error is encountered.

    ml.append(pprint.pformat(obj))
    """Normally, I would build a dictionary of the ports so I could treat them as objects and add port
    configuration, port statistics, and anything else port specific to the object.
    
    I don't recall how a non-VF enabled switch responds but I don't think 'fabric-id' is present in the response.

    If you are new to Python, there is a construct referred to as a list comprehension which allows you to build a
    list in a single line of code. The code that follows this comment is equivalent to:
    
    fid_list = list()
    for ls in obj['fibrechannel-logical-switch']:
        if ls.get('fabric-id') is not None:
            fid_list.append(ls.get('fabric-id'))
    return fid_list"""

    return [
        ls.get('fabric-id') for ls in obj['fibrechannel-logical-switch']
        if ls.get('fabric-id') is not None
    ]
Ejemplo n.º 5
0
def _create_new_policy(session, fid, policy, rule_list, enable_flag=False):
    """Create a new MAPS policy.

    :param session: Session object returned from brcdapi.brcdapi_auth.login()
    :type session: dict
    :param fid: Fabric ID of the logical switch whose MAPS policy we want to modify. None if not VF enabled
    :type fid: None, str
    :param policy: Name of the MAPS policy to create
    :type policy: str
    :param rule_list: List of rule names for the MAPS policy
    :type rule_list: list
    :param enable_flag: If True, enables the policy
    :type enable_flag: bool
    :return: List of new rules
    :rtype: list
    """
    new_content = {
        'name': policy,
        'rule-list': {
            'rule': rule_list
        },
        'is-active-policy': enable_flag
    }

    # Now send the new MAPS policy to the switch
    obj = brcdapi_rest.send_request(session, 'runningbrocade-maps/maps-policy',
                                    'POST', {'maps-policy': new_content}, fid)
    if brcdapi_auth.is_error(obj):
        brcdapi_log.log(
            'Failed to set MAPS policy. API response:\n' +
            brcdapi_auth.formatted_error_msg(obj), True)
        brcdapi_log.log(
            'This typically occurs when the policy already exists.', True)
        return brcddb_common.EXIT_STATUS_API_ERROR
    return brcddb_common.EXIT_STATUS_OK
Ejemplo n.º 6
0
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 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
Ejemplo n.º 9
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()
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)
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
def _create_new_rules(session, fid, new_sfp_rules):
    """Create all new SFP rules

    :param session: Session object returned from brcdapi.brcdapi_auth.login()
    :type session: dict
    :param fid: Fabric ID of the logical switch whose MAPS policy we want to modify. None if not VF enabled
    :type fid: None, str
    :param new_sfp_rules: List of dictionaries of rules returned from report_utils.parse_sfp_file_for_rules()
    :type new_sfp_rules: list
    :return: List of new rules created.
    """
    # Build the new rules content for the API POST request
    sum_new_rules = list()
    num_rules = len(new_sfp_rules)
    # After writing the code, I was getting HTTP connection timeouts so I had to batch the number of rules to add.
    i = 0
    while i < num_rules:
        x = i + _MAX_RULE_BATCH if i + _MAX_RULE_BATCH <= num_rules else num_rules
        new_rules = new_sfp_rules[i:x]
        obj = brcdapi_rest.send_request(session, 'running/brocade-maps/rule',
                                        'POST', dict(rule=new_rules), fid)
        if brcdapi_auth.is_error(obj):
            # If the rule already exists, you cannot use POST or PATCH to write over it and PUT is not supported. I'm
            # assuming you could DELETE then POST and I could also check to see if the rule is changing but this simple
            # example on how to modify a MAPS policy is already getting to complicated so I just post warnings.
            er_l = list()
            er_obj = dict(errors=dict(error=er_l))
            if 'errors' in obj and isinstance(obj['errors'].get('error'),
                                              list):
                for d in obj['errors']['error']:
                    buf = d.get('error-message')
                    if buf is not None and buf == 'Rule name is present.' and isinstance(
                            d.get('error-path'), str):
                        brcdapi_log.log(
                            'Rule ' + d['error-path'].replace(
                                '/rule/name/', '').replace('/', '') +
                            ' already exists. Not changed.', True)
                    else:
                        er_l.append(d)
            if len(er_l) > 0:
                brcdapi_log.log(
                    'Failed to create rules. API response:' +
                    brcdapi_auth.formatted_error_msg(er_obj), True)
                return sum_new_rules  # If we get here, something is really wrong so just bail out
        # rule.get('name') should never be None in the line below. I'm just extra cautious
        sum_new_rules.extend([
            rule.get('name') for rule in new_rules
            if rule.get('name') is not None
        ])
        i = x
    return sum_new_rules
Ejemplo n.º 13
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 _get_switch_data(session, fid):
    """Capture switch, fabric, and port data as would be returned from (not all data is being captured):

    :param session: The session object returned from brcdapi.fos_auth.login()
    :type session: dict
    :param fid: Fabric ID to execute the switch level commands against. Use None for non-VF enabled switches
    :type fid: int, None
    """
    global _switch_rest_data

    for kpi in _switch_rest_data:  # See comments with _switch_rest_data above
        ml = ['', kpi
              ]  # The first member as '' inserts a blank line before the KPI
        obj = brcdapi_rest.get_request(session, kpi, fid)
        if brcdapi_auth.is_error(obj):
            ml.append(brcdapi_auth.formatted_error_msg(obj))
        else:
            ml.append(pprint.pformat(obj))
        brcdapi_log.log(ml, True)
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
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 _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 get_ge_port_list(session, fid):
    """Returns the list of GE ports in a logical switch

    :param session: Session object returned from brcdapi.brcdapi_auth.login()
    :type session: dict
    :param fid: Logical switch FID number
    :type fid: int
    :return: List of GE ports
    :rtype: list
    """
    obj = brcdapi_rest.get_request(
        session,
        'running/brocade-fibrechannel-logical-switch/fibrechannel-logical-switch/fabric-id/'
        + str(fid))
    if brcdapi_auth.is_error(obj):
        brcdapi_log.log(brcdapi_auth.formatted_error_msg(obj), True)
        return list()
    if 'fibrechannel-logical-switch' in obj and 'ge-port-member-list' in obj[
            'fibrechannel-logical-switch']:
        pl = obj['fibrechannel-logical-switch']['ge-port-member-list'].get(
            'port-member')
        return list() if pl is None else pl
    return list()
Ejemplo n.º 19
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
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:
            # 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

    # 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(). 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
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
    """
    global _DEBUG, _DEFAULT_POLL_INTERVAL, _DEFAULT_MAX_SAMPLE, _proj_obj, _session, _out_f, _switch_obj
    global _base_switch_obj, __version__, _uris, _uris_2

    signal.signal(signal.SIGINT, _signal_handler)

    # Get user input
    ip, user_id, pw, sec, fid, pct, max_p, _out_f = _get_input()
    default_text = ' (default)'
    ml = ['WARNING!!! Debug is enabled'] if _DEBUG else list()
    ml.append(os.path.basename(__file__) + ' version: ' + __version__)
    ml.append('IP Address:    ' + brcdapi_util.mask_ip_addr(ip))
    ml.append('User ID:       ' + user_id)
    ml.append('FID:           ' + str(fid))
    if max_p is None:
        max_p = _DEFAULT_MAX_SAMPLE
        ml.append('Samples:       ' + str(max_p) + default_text)
    else:
        ml.append('Samples:       ' + str(max_p))
    if pct is None:
        pct = _DEFAULT_POLL_INTERVAL
        ml.append('Poll Interval: ' + str(pct) + default_text)
    else:
        ml.append('Poll Interval: ' + str(pct) + ' (defaulting to ' +
                  str(_MIN_POLL) + ')' if pct < _MIN_POLL else '')
    ml.append('Output File:   ' + _out_f)
    brcdapi_log.log(ml, True)

    # Create project
    _proj_obj = brcddb_project.new(
        'Port_Stats',
        datetime.datetime.now().strftime('%d %b %Y %H:%M:%S'))
    _proj_obj.s_python_version(sys.version)
    _proj_obj.s_description('Port statistics')

    # Login
    _session = brcddb_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

    try:  # I always put all code after login in a try/except in case of a code bug or network error, I still logout
        # Capture the initial switch and port information along with the first set of statistics.
        brcdapi_log.log('Capturing initial data', True)
        brcddb_int.get_batch(_session, _proj_obj, _uris,
                             fid)  # Captured data is put in _proj_obj
        chassis_obj = _proj_obj.r_chassis_obj(_session.get('chassis_wwn'))
        if chassis_obj.r_is_vf_enabled():
            if fid is None:
                fid = 128
            _base_switch_obj = chassis_obj.r_switch_obj_for_fid(fid)
        else:
            _base_switch_obj = chassis_obj.r_switch_objects()[0]
        if _base_switch_obj is None:
            brcdapi_log.log('Switch for FID ' + str(fid) + ' not found. ',
                            True)
            return _wrap_up(brcddb_common.EXIT_STATUS_ERROR)
        base_switch_wwn = _base_switch_obj.r_obj_key()
        if _base_switch_obj.r_fabric_key() is None:
            _base_switch_obj.s_fabric_key(
                base_switch_wwn
            )  # Fake out a fabric principal if we don't have one
            _proj_obj.s_add_fabric(base_switch_wwn)
        brcddb_int.get_batch(_session, _proj_obj, _uris_2,
                             fid)  # Captured data is put in _proj_obj
        time.sleep(
            5
        )  # Somewhat arbitrary time. Don't want a throttling delay if the poll interval is very short

        # Get the first sample
        stats_buf = 'brocade-interface/fibrechannel-statistics'
        last_time = time.time()
        last_stats = brcddb_int.get_rest(_session, stats_buf, _base_switch_obj,
                                         fid)
        for p in last_stats.get('fibrechannel-statistics'):
            _base_switch_obj.r_port_obj(p.get('name')).s_new_key(
                'fibrechannel-statistics', p)

        # Now start collecting the port and interface statistics
        for i in range(0, max_p):
            x = pct - (time.time() - last_time)
            time.sleep(_MIN_POLL if x < _MIN_POLL else x)
            switch_obj = _proj_obj.s_add_switch(base_switch_wwn + '-' + str(i))
            last_time = time.time()
            obj = brcddb_int.get_rest(_session,
                                      'brocade-interface/fibrechannel',
                                      switch_obj, fid)
            if not fos_auth.is_error(obj):
                for p in obj.get('fibrechannel'):
                    switch_obj.s_add_port(p.get('name')).s_new_key(
                        'fibrechannel', p)
                obj = brcddb_int.get_rest(_session, stats_buf, switch_obj, fid)
            if fos_auth.is_error(
                    obj
            ):  # We typically get here when the login times out or network fails.
                brcdapi_log.log(
                    'Error encountered. Data collection limited to ' + str(i) +
                    ' samples.', True)
                _wrap_up(brcddb_common.EXIT_STATUS_ERROR)
                return brcddb_common.EXIT_STATUS_ERROR
            obj = brcddb_int.get_rest(_session, stats_buf, switch_obj, fid)
            if fos_auth.is_error(
                    obj
            ):  # We typically get here when the login times out or network fails.
                brcdapi_log.log(
                    'Error encountered. Data collection limited to ' + str(i) +
                    ' samples.', True)
                _wrap_up(brcddb_common.EXIT_STATUS_ERROR)
                return brcddb_common.EXIT_STATUS_ERROR

            for p in _stats_diff(last_stats,
                                 obj).get('fibrechannel-statistics'):
                switch_obj.s_add_port(p.get('name')).s_new_key(
                    'fibrechannel-statistics', p)
            _switch_obj.append(switch_obj)
            last_stats = obj

        return _wrap_up(brcddb_common.EXIT_STATUS_OK)

    except BaseException as e:
        brcdapi_log.log([
            'Error capturing statistics. ' + _EXCEPTION_MSG,
            'Exception: ' + str(e)
        ], True)
        return _wrap_up(brcddb_common.EXIT_STATUS_ERROR)
Ejemplo n.º 25
0
def _config_fab_and_switch(session, switch_d, 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_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 _switch_d_to_api

    # Load common use stuff into local variables
    ec = brcddb_common.EXIT_STATUS_OK
    fid = switch_d['fid']
    idid = False if switch_d['switch_type'] == 'ficon' else switch_d['idid']

    # Set switch configuration parameters.
    sub_content = dict()
    for k, v in _switch_d_to_api.items():
        if switch_d[k] is not None:
            sub_content.update({v: switch_d[k]})
    if switch_d['switch_type'] == 'ficon':
        sub_content.update({
            'in-order-delivery-enabled': True,
            'dynamic-load-sharing': 'two-hop-lossless-dls'
        })

    # Send the changes.
    obj = brcdapi_switch.fibrechannel_switch(session, fid, sub_content, None,
                                             echo)
    if fos_auth.is_error(obj):
        # in-order-delivery-enabled and dynamic-load-sharing not supported in pre-FOS 9.0 so just try it again
        sub_content.pop('in-order-delivery-enabled', None)
        sub_content.pop('dynamic-load-sharing', None)
        obj = brcdapi_switch.fibrechannel_switch(session, fid, sub_content,
                                                 None, echo)
        if fos_auth.is_error(obj):
            brcdapi_log.log([
                'Failed to configure FID ' + str(fid),
                fos_auth.formatted_error_msg(obj)
            ], True)
            ec = brcddb_common.EXIT_STATUS_API_ERROR
        else:
            switch_d['err_msgs'].append(
                'Failed to set in order delivery and dynamic load sharing')
            buf = 'In order delivery and dynamic load sharing not supported via the API in this version of FOS. '\
                  'Remember to set these parameters manually.'
            brcdapi_log.log(buf, True)

    # Set the fabric parameters.
    # XISL (ability to use the base switch for ISLs) is enabled by default so we only need to disable it
    if not switch_d['xisl']:
        obj = brcdapi_rest.send_request(
            session,
            'running/brocade-fibrechannel-configuration/switch-configuration',
            'PATCH', {'switch-configuration': {
                'xisl-enabled': False
            }}, fid)
        if fos_auth.is_error(obj):
            switch_d['err_msgs'].append('Failed to disable XISL')
            ml = [
                'Failed to disable XISL for FID ' + str(fid),
                fos_auth.formatted_error_msg(obj),
                'Enabling and disabling of XISLs via the API was not supported until FOS v9.0.',
                'Unless there are other error messages, all other operations are or will be completed as expected.'
            ]
            brcdapi_log.log(ml, True)
            ec = brcddb_common.EXIT_STATUS_API_ERROR

    if idid:
        obj = brcdapi_rest.send_request(
            session, 'running/brocade-fibrechannel-configuration/fabric',
            'PATCH', {'fabric': {
                'insistent-domain-id-enabled': True
            }}, fid)
        if fos_auth.is_error(obj):
            switch_d['err_msgs'].append('Failed to set insistent domain id')
            brcdapi_log.log([
                'Failed to set insistent domain id for FID ' + str(fid),
                fos_auth.formatted_error_msg(obj)
            ], True)
            ec = brcddb_common.EXIT_STATUS_API_ERROR

    return ec
Ejemplo n.º 26
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
Ejemplo n.º 27
0
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
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().

    :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