示例#1
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)
示例#2
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 _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
示例#4
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():
    """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)
def pseudo_main():
    """Basically the main(). Did it this way so it can easily be used as a standalone module or called from another.

    :return: Exit code. See exist codes in brcddb.brcddb_common
    :rtype: int
    """
    ec = brcddb_common.EXIT_STATUS_OK

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

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

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

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

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

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

    return ec