示例#1
0
文件: mac.py 项目: zero804/sonic-mgmt
def delete_mac(dut, mac, vlan, cli_type=""):
    """
    :param dut:
    :type dut:
    :return:
    :rtype:
    """
    #st.log("config mac del <mac> <vlan>")
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type == 'click':
        command = "config mac del {} {}".format(mac, vlan)
        if not st.is_feature_supported("config-mac-add-command", dut):
            st.community_unsupported(command, dut)
            _json_mac_del(dut, mac, vlan)
        else:
            st.config(dut, command, type=cli_type)
    elif cli_type == 'klish':
        command = "no mac address-table {} vlan {}".format(mac, vlan)
        st.config(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        network_instance_name = 'default'
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['mac_entry_based_vlan_interface'].format(
            network_instance_name, mac, vlan)
        delete_rest(dut, rest_url=url)
    else:
        st.log("Unsupported cli")
        return False

    return True
示例#2
0
def clear_port_shaper(dut, port='', shaper_data='', **kwargs):
    """
    API to clear shaper and detach shaper from port
    :param dut:
    :type dut:
    :param port:
    :type port:
    :param shaper_data:
    :type shaper_data:
    :param cli_type:
    :type cli_type:
    :return:
    :rtype:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    skip_error = kwargs.get('skip_error', False)
    cli_type = 'klish' if skip_error and cli_type == 'click' else cli_type
    qos_clear = kwargs.get('qos_clear', False)
    remove_shaper = kwargs.get('remove_shaper', True)
    if (not qos_clear) and cli_type == 'click':
        cli_type = 'klish'
    if cli_type == 'click':
        clear_qos_config(dut)
    elif cli_type == 'klish':
        commands = list()
        if port:
            intf_data = get_interface_number_from_name(port)
            commands.append("interface {} {}".format(intf_data['type'],
                                                     intf_data['number']))
            commands.append("no scheduler-policy")
            commands.append("exit")
        if shaper_data and remove_shaper:
            commands.append("no qos scheduler-policy {}".format(shaper_data))
        response = st.config(dut,
                             commands,
                             type=cli_type,
                             skip_error_check=skip_error)
        if any(error in response.lower() for error in errors_list):
            st.error("The response is: {}".format(response))
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        rest_urls = st.get_datastore(dut, "rest_urls")
        if port:
            url = rest_urls['policy_apply_config'].format(port)
            if not delete_rest(dut, rest_url=url):
                st.error(
                    "Failed to remove scheduler-policy on port: {}".format(
                        port))
                return False
        if shaper_data and remove_shaper:
            url = rest_urls['scheduler_policy_config'].format(shaper_data)
            if not delete_rest(dut, rest_url=url):
                st.error("Failed to remove QOS scheduler-policy: {}".format(
                    shaper_data))
                return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
示例#3
0
def config_nat_interface(dut, **kwargs):
    """
    Config NAT interface
    Author:[email protected]
    :param :dut:
    :param :config: add-del:
    :param :interface_name:
    :param :zone_value:

    usage:
    config_nat_interface(dut1, interface_name, zone_value, config="add")
    config_nat_interface(dut1, interface_name, config="del")
    """
    result = False
    command = ''
    cli_type = st.get_ui_type(dut, **kwargs)
    skip_error_check = kwargs.get("skip_error_check", True)
    if cli_type not in ["klish", "click", "rest-patch", "rest-put"]:
        st.log("UNSUPPORTE CLI TYPE")
        return False
    if "interface_name" not in kwargs and "config" not in kwargs:
        st.error("Mandatory params interface_name or config not provided")
        return result
    if kwargs["config"] == "add":
        if "zone_value" not in kwargs:
            st.error("Mandatory params zone_vlaue not provided")
            return result
        if cli_type == "click":
            command = "config nat add interface {} -nat_zone {}".format(kwargs["interface_name"], kwargs["zone_value"])
        elif cli_type == "klish":
            command = list()
            intf_data = get_interface_number_from_name(kwargs["interface_name"])
            command.append("interface {} {}".format(intf_data["type"], intf_data["number"]))
            command.append("nat-zone {}".format(kwargs["zone_value"]))
            command.append("exit")
        elif cli_type in ["rest-patch", "rest-put"]:
            url = st.get_datastore(dut, "rest_urls")['config_nat_interface'].format(kwargs["interface_name"])
            data = {"openconfig-interfaces-ext:nat-zone": int(kwargs["zone_value"])}
            config_rest(dut, http_method=cli_type, rest_url=url, json_data=data)
            return True

    if kwargs["config"] == "del":
        if cli_type == "click":
            command = "config nat remove interface {}".format(kwargs["interface_name"])
        elif cli_type == "klish":
            command = list()
            intf_data = get_interface_number_from_name(kwargs["interface_name"])
            command.append("interface {} {}".format(intf_data["type"], intf_data["number"]))
            command.append("no nat-zone")
            command.append("exit")
        elif cli_type in ["rest-patch", "rest-put"]:
            url = st.get_datastore(dut, "rest_urls")['del_nat_interface'].format(kwargs["interface_name"])
            delete_rest(dut, rest_url=url)
            return True

    st.config(dut, command, type=cli_type, skip_error_check=skip_error_check)
    return True
示例#4
0
def clear_radius_statistics(dut, skip_error_check=False, cli_type=""):
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type in ['click', 'klish']:
        command = "sonic-clear radius"
        st.config(dut, command, skip_error_check=skip_error_check)
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['radius_statistics'].format("RADIUS")
        delete_rest(dut, rest_url=url, get_response=True)
    else:
        st.log("UNSUPPORTED CLI TYPE")
        return False
    return True
示例#5
0
def reset_port_shaper_params(dut, policy_name, params_list, **kwargs):
    """
    API to reset Port-Level shaper parameters
    :param dut:
    :type dut:
    :param policy_name:
    :type policy_name:
    :param params_list:
    :type params_list:
    :return:
    :rtype:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    cli_type = 'klish' if cli_type == 'click' else cli_type
    skip_error = kwargs.get('skip_error', False)
    params_list = [param.lower() for param in make_list(params_list)]
    if cli_type == 'klish':
        commands = list()
        commands.append("qos scheduler-policy {}".format(policy_name))
        commands.append("port")
        commands.extend(["no {}".format(param) for param in params_list])
        commands.extend(["exit", "exit"])
        response = st.config(dut,
                             commands,
                             type=cli_type,
                             skip_error_check=skip_error)
        if any(error in response.lower() for error in errors_list):
            st.error("The response is: {}".format(response))
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        rest_urls = st.get_datastore(dut, 'rest_urls')
        for param in params_list:
            if param.lower() not in ['pir', 'pbs']:
                st.error('Invalid port shaper parameter: {}'.format(param))
                return False
            if param == 'pir':
                url = rest_urls['shaper_pir_config'].format(policy_name, 255)
                if not delete_rest(dut, rest_url=url):
                    st.error("Failed to reset {} for port shaper profile: {}".
                             format(param, policy_name))
                    return False
            if param == 'pbs':
                url = rest_urls['shaper_pbs_config'].format(policy_name, 255)
                if not delete_rest(dut, rest_url=url):
                    st.error("Failed to reset {} for port shaper profile: {}".
                             format(param, policy_name))
                    return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    return True
示例#6
0
def delete_ntp_servers(dut, cli_type=''):
    """
    :param dut:
    :param iplist:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    output = show_ntp_server(dut)
    commands = []
    if output is None:
        st.log("No servers to delete")
        return True
    else:
        for ent in iterable(output):
            server_ip = ent["remote"].strip("+*#o-x").strip()
            if cli_type == "click":
                commands.append("config ntp del {}".format(server_ip))
            elif cli_type == "klish":
                commands.append("no ntp server {}".format(server_ip))
            elif cli_type in ['rest-patch', 'rest-put']:
                rest_urls = st.get_datastore(dut, "rest_urls")
                url1 = rest_urls['config_ntp_server'].format(server_ip)
                if not delete_rest(dut, rest_url=url1):
                    st.error("Failed to delete ntp {} server".format(server_ip))
            else:
                st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
                return False
    st.config(dut, commands, type=cli_type)
    return True
示例#7
0
def set_crm_clear_config(dut, cli_type=""):
    """
    API to clear CRM configuration.
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param cli_type: click or klish designation:
    :return: Command output
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type == "click":
        command = "crm config clear"
        if not st.is_feature_supported("crm-config-clear-command", dut):
            st.community_unsupported(command, dut)
            command = "crm config polling interval 9999999"
    elif cli_type == "klish":
        command = "no crm all"
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['crm_all']
        if not delete_rest(dut, rest_url=url):
            return False
        return True
    else:
        st.error("Unsupported cli type: {}".format(cli_type))
        return False
    return st.config(dut, command, type=cli_type)
示例#8
0
def set_crm_nothresholds(dut, cli_type=""):
    """
    Set no thresholds (default).
    :param dut:
    :param cli_type: click or klish designation:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    command = ""
    if cli_type == "click":
        command = "crm config clear"
    elif cli_type == "klish":
        command = "no crm thresholds all"
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['crm_thresholds']
        if not delete_rest(dut, rest_url=url):
            return False
    else:
        st.error("Unsupported cli type: {}".format(cli_type))
        return False
    if command:
        rv = st.config(dut, command, type=cli_type)
        if 'Error' in rv:
            st.error("{}".format(rv))
            return False
    return True
示例#9
0
def delete_vlan(dut, vlan_list, cli_type=''):
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    """
    To delete list of VLANs.
    Author : Prudvi Mangadu ([email protected])

    :param dut:
    :param vlan_list:
    :param cli_type:
    :return:
    """

    st.log("Delete vlan")
    vlan_li = map(str, vlan_list) if isinstance(vlan_list,
                                                list) else [vlan_list]
    commands = list()
    rest_fail_status = False
    try:
        for each_vlan in vlan_li:
            if cli_type == "click":
                commands.append("config vlan del {}".format(each_vlan))
            elif cli_type == "klish":
                commands.append("no interface Vlan {}".format(each_vlan))
            elif cli_type in ["rest-put", "rest-patch"]:
                rest_url = st.get_datastore(
                    dut, "rest_urls")["per_interface_details"].format(
                        "Vlan{}".format(each_vlan))
                output = delete_rest(dut, rest_url=rest_url, get_response=True)
                if not output:
                    st.error("OUTPUT IS EMPTY FROM DELETE VLAN REST CALL")
                    return False
                st.log("STATUS: {}".format(output["status"]))
                if not rest_status(output["status"]):
                    rest_fail_status = True
            else:
                st.log("Unsupported CLI type")
                return False
        if rest_fail_status:
            st.log("One of VLAN DELETE REST call failed")
            return False
        if commands:
            response = st.config(dut,
                                 commands,
                                 skip_error_check=True,
                                 type=cli_type)
            if "Error" in response:
                st.log(response)
                return False
            else:
                vlan_list = get_vlan_list(dut, cli_type=cli_type)
                for each_vlan in vlan_li:
                    if each_vlan in vlan_list:
                        st.error(" Vlan{} is not deleted".format(each_vlan))
                        return False
        return True
    except Exception as e1:
        st.log(e1)
        st.error(" Vlan is not deleted due to other reasons")
        return False
示例#10
0
def config_mclag_system_mac(dut, skip_error=False, **kwargs):
    '''
    Configures< mclag system-mac <add|del> <domain-id> mac > for Mclag
    Author: [email protected]
    :param dut:
    :param kwargs: optional parameters can be <config|domain_id|mac|cli_type>
    :return:

    Usage:
    config_mclag_system_mac(dut1, domain_id= 1, config='add', mac='xx:xx:xx:xx:xx:xx')
    config_mclag_system_mac(dut1, domain_id= 1, config='del')
    '''
    ### Optional parameters processing
    config = kwargs.get('config', 'add')
    if config == 'add' and 'mac' not in kwargs:
        st.error("Mandatory parameter mac address not found for config = add")
        return False
    if 'domain_id' not in kwargs:
        st.error("Mandatory parameter domain_id  not found")
        return False
    mac_val = kwargs.get('mac')
    domain_id = kwargs.get('domain_id')
    cli_type = kwargs.get('cli_type', st.get_ui_type(dut, **kwargs))
    mac_val = '' if config == 'del' else mac_val
    if cli_type == 'click':
        cmd = "config mclag system-mac {} {} {}\n".format(
            config, domain_id, mac_val)
        output = st.config(dut, cmd)
        if "configure mclag domain first" in output:
            st.error("Domain_id doesn't exist")
            return False
    elif cli_type == 'klish':
        config = 'no' if config == 'del' else ''
        cmd = "mclag domain {} \n{} mclag-system-mac {}".format(
            domain_id, config, mac_val)
        cmd = cmd + "\n" + "exit"
        output = st.config(dut, cmd, type="klish", conf=True)
        if "Could not connect to Management REST Server" in output:
            st.error("klish mode not working.")
            return False
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['mclag_config_mclag_system_mac'].format(int(domain_id))
        if config == "add":
            payload = {"openconfig-mclag:mclag-system-mac": mac_val}
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url,
                    json_data=payload):
                return False
        else:
            if not delete_rest(dut, rest_url=url):
                return False
    else:
        st.log("Invalid cli_type provided: {}".format(cli_type))
        return False
    return True
def config(dut, **kwargs):
    cli_type = st.get_ui_type(dut, **kwargs)
    """
    API to create Mgmt VRF.
    Author : Kiran Vedula ([email protected])
    :param :dut:
    :param :mgmtvrf:
    :param :cli_type:   default - klish
    :param :no_form:   default - False
    :return:

    Usage:
    config(vars.D1, cli_type='klish')

    config(vars.D1, no_form=True,cli_type='klish')

    """
    no_form = "no" if kwargs.get("no_form") else ""
    command_list = []
    if cli_type == 'klish':
        if not no_form:
            command_list.append("ip vrf mgmt")
            st.config(dut, command_list, type=cli_type, expect_ipchange=True)
        else:
            command_list.append("no ip vrf mgmt")
            st.config(dut, command_list, type=cli_type, expect_ipchange=True)
    elif cli_type == "click":
        st.log('Config Mgmt VRF API')
        if no_form != 'no':
            my_cmd = 'sudo config vrf add mgmt'
        else:
            my_cmd = 'sudo config vrf del mgmt'
        st.config(dut, my_cmd, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        if no_form != 'no':
            url = rest_urls['config_mgmt_vrf'].format("mgmt")
            config_data = {
                "openconfig-network-instance:config": {
                    "enabled": True,
                    "name": "mgmt"
                }
            }
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url,
                    json_data=config_data):
                return False
        else:
            url = rest_urls['unconfig_mgmt_vrf'].format("mgmt")
            if not delete_rest(dut, rest_url=url):
                return False
    else:
        st.error("Unsupported cli_type: {}".format(cli_type))
        return False
    return True
示例#12
0
def set_tacacs_properties(dut, property, value, cli_type="", **kwargs):
    '''
    Configuring tacacs properties.
    '''
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    property_mapping = {
        "authtype": "auth-type",
        "passkey": "key",
        "timeout": "timeout",
        "sourceip": "host",
        "source-interface": "source-interface"
    }
    if cli_type == "click":
        command = "config tacacs {} {}".format(property, value)
        st.config(dut, command, type=cli_type)
    elif cli_type == "klish":
        if property != "default":
            property = property_mapping[property]
            command = "tacacs-server {} {}".format(property, value)
        else:
            property = property_mapping[value]
            command = "no tacacs-server {}".format(property)
        st.config(dut, command, type=cli_type)
    elif cli_type in ['rest-put', 'rest-patch']:
        rest_urls = st.get_datastore(dut, "rest_urls")
        property_mapping = {
            "authtype": "openconfig-system-ext:auth-type",
            "passkey": "openconfig-system-ext:secret-key",
            "timeout": "openconfig-system-ext:timeout"
        }
        url_mapping = {
            "authtype": "tacacs_global_authtype_config",
            "passkey": "tacacs_global_passkey_config",
            "timeout": "tacacs_global_timeout_config"
        }
        if property != 'default':
            url = rest_urls[url_mapping[property]].format("TACACS")
            data = {property_mapping[property]: value}
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               timeout=time_out,
                               **kwargs):
                st.error("Failed to configure tacacs global params")
                return False
        else:
            url = rest_urls[url_mapping[value]].format("TACACS")
            if not delete_rest(dut, rest_url=url, timeout=time_out, **kwargs):
                st.error("Failed to delete tacacs global params")
                return False
    else:
        st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
        return False
    return True
示例#13
0
def config_udld_multiplier(dut, **kwargs):
    """
    Author: [email protected]
    config_udld_multiplier(dut=data.dut1,udld_multiplier='4',config='yes')
    config_udld_multipier(dut=data.dut1,udld_multiplier='4')
    config_udld_multipier(dut=data.dut1,udld_multiplier='4',config='no')
    udld.config_udld_multiplier(dut=dut1,udld_multiplier='3',config='yes',cli_type='rest-put')
    Configure udld multipllier globally
    :param dut:
    :param udld_multipier:
    :return:
    """
    cli_type = kwargs.pop('cli_type', st.get_ui_type(dut))
    if 'config' in kwargs:
        config = kwargs['config']
    else:
        config = 'yes'
    if config.lower() == 'yes':
        config_cmd = ''
    else:
        config_cmd = 'no'
    udld_multiplier = kwargs.get('udld_multiplier', None)
    if cli_type == 'klish' or cli_type == 'click':
        if 'udld_multiplier' in kwargs:
            my_cmd = '{} udld multiplier {} \n'.format(
                config_cmd, kwargs['udld_multiplier'])
        st.config(dut, my_cmd, type='klish')
    elif cli_type in ['rest-patch', 'rest-put']:
        http_method = kwargs.pop('http_method', cli_type)
        rest_urls = st.get_datastore(dut, 'rest_urls')
        rest_url = rest_urls['udld_multiplier_config']
        ocdata = {
            "openconfig-udld-ext:multiplier": int(kwargs['udld_multiplier'])
        }
        if config_cmd == '' and udld_multiplier != None:
            response = config_rest(dut,
                                   http_method=http_method,
                                   rest_url=rest_url,
                                   json_data=ocdata)
        else:
            response = delete_rest(dut,
                                   http_method='delete',
                                   rest_url=rest_url,
                                   json_data=ocdata)
        if not response:
            st.log('UDLD global message time config/unconfig failed')
            st.log(response)
            return False
        return True
    else:
        st.log("Unsupported CLI TYPE - {}".format(cli_type))
        return False
示例#14
0
def enable_ssh_in_user_vrf(dut, **kwargs):
    """
    To enable SSH-in over user defined VRF
    :param dut:
    :param kwargs:
    :return:
    Usage:enable_ssh_in_user_vrf(vars.D1, config='add',vrf_name='mgmt')
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    st.log(" Configure SSH-in for user VRF")
    if not kwargs.get('vrf_name'):
        st.error("Mandatory arguments are missing.")
        return False
    if kwargs.get('config') not in ['add', 'del']:
        st.error("Incorrect config type")
        return False
    if cli_type == "click":
        command = "config ssh-server vrf {} {}".format(kwargs.get('config'), kwargs.get('vrf_name'))
        st.config(dut, command, type=cli_type, skip_error_check=True)
    elif cli_type == "klish":
        config = "no " if kwargs.get('config') == "del" else ""
        command = "{}ssh-server vrf {}".format(config, kwargs.get('vrf_name'))
        st.config(dut, command, type=cli_type, skip_error_check=True)
    elif cli_type in ["rest-patch","rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['config_ssh_server'].format(kwargs.get('vrf_name'))
        ssh_config={"openconfig-system-ext:ssh-server-vrf":[{"vrf-name": kwargs.get('vrf_name'),"config":{
            "vrf-name": kwargs.get('vrf_name'),"port": 22}}]}
        if kwargs.get('config') == 'add':
            if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=ssh_config):
                st.error("ssh server configuration failed")
                return False
        else:
            if not delete_rest(dut, rest_url=url):
                st.error("ssh server deletion failed")
                return False
    else:
        st.error("Unsupported cli_type: {}".format(cli_type))
        return False
    return True
示例#15
0
def delete_session(dut, mirror_session='', skip_err_check=False, cli_type=""):
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    '''
    :param dut:
    :param mirror_session:
    :return:
    '''
    if not mirror_session:
        st.error("Mirror session name not provided ...")
        return False
    if cli_type == "click":
        command = "config mirror_session remove {}".format(mirror_session)
        st.config(dut, command, skip_error_check=skip_err_check)
        return True if show_session(dut, mirror_session) else False
    elif cli_type == "klish":
        commands = list()
        command = "no mirror-session {}".format(mirror_session)
        commands.append(command)
        output = st.config(dut,
                           commands,
                           type=cli_type,
                           skip_error_check=skip_err_check)
        st.config(dut, "exit", type=cli_type)
        output = remove_last_line_from_string(output)
        if output:
            if "Failed" not in output or "Error" not in output:
                return False
        return True
    elif cli_type in ['rest-put', "rest-patch"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['get_session_session_name'].format(mirror_session)
        if not delete_rest(dut, rest_url=url):
            return False
        return True
    else:
        st.log("Unsupported cli")
        return False
示例#16
0
def set_tacacs_server(dut,
                      mode,
                      address,
                      tcp_port=None,
                      timeout=None,
                      passkey=None,
                      auth_type=None,
                      priority=None,
                      use_mgmt_vrf=False,
                      cli_type="",
                      **kwargs):
    '''
    Configuring tacacs server properties.
    '''
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type == "click":
        sub_opts = []
        if mode.lower() == 'add':
            command = "config tacacs {} {} ".format('add', address)
            if tcp_port:
                sub_opts.append('{} {}'.format('-o', tcp_port))
            if timeout:
                sub_opts.append('{} {}'.format('-t', timeout))
            if passkey:
                sub_opts.append('{} {}'.format('-k', passkey))
            if auth_type:
                sub_opts.append('{} {}'.format('-a', auth_type))
            if priority:
                sub_opts.append('{} {}'.format('-p', priority))
            if use_mgmt_vrf:
                sub_opts.append('{}'.format('-m'))
            command = command + ' '.join(sub_opts)
        elif mode.lower() == 'delete':
            command = "config tacacs {} {} ".format('delete', address)
        st.config(dut, command, type=cli_type)
    elif cli_type == "klish":
        no_form = "no" if mode.lower() == "delete" else ""
        if not no_form:
            command = "tacacs-server host {}".format(address)
            if timeout:
                command += " timeout {}".format(timeout)
            if passkey:
                command += " key {}".format(passkey)
            if auth_type:
                command += " type {}".format(auth_type)
            if tcp_port:
                command += " port {}".format(tcp_port)
            if priority:
                command += " priority {}".format(priority)
            if use_mgmt_vrf:
                command += " vrf mgmt"
        else:
            command = "{} tacacs-server host {}".format(no_form, address)
        st.config(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        if mode.lower() == 'add':
            url = rest_urls['tacacs_authtype_config']
            data = {
                "openconfig-system:server-group": [{
                    "name": "TACACS",
                    "config": {
                        "name": "TACACS",
                        "openconfig-system-ext:auth-type": str(auth_type),
                        "openconfig-system-ext:secret-key": str(passkey),
                        "openconfig-system-ext:timeout": int(timeout)
                    },
                    "servers": {
                        "server": [{
                            "address": str(address),
                            "config": {
                                "name": "TACACS",
                                "address": str(address),
                                "timeout": int(timeout),
                                "openconfig-system-ext:auth-type":
                                str(auth_type),
                                "openconfig-system-ext:priority": int(priority)
                            },
                            "tacacs": {
                                "config": {
                                    "port": int(tcp_port),
                                    "secret-key": str(passkey)
                                }
                            }
                        }]
                    }
                }]
            }
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               timeout=time_out,
                               **kwargs):
                st.error("Failed to configure auth_type for {} server".format(
                    address))
                return False
            if use_mgmt_vrf:
                url = rest_urls['tacacs_vrf_config'].format('TACACS', address)
                data = {"openconfig-system-ext:vrf": "mgmt"}
                if not config_rest(dut,
                                   http_method=cli_type,
                                   rest_url=url,
                                   json_data=data,
                                   timeout=time_out,
                                   **kwargs):
                    st.error("Failed to configure VRF for {} server".format(
                        address))
                    return False
        if mode.lower() == 'delete':
            url = rest_urls['delete_tacacs_server'].format('TACACS', address)
            if not delete_rest(dut, rest_url=url, timeout=time_out, **kwargs):
                st.error('Failed to delete the server {}'.format(address))
                return False
    else:
        st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
        return False
    return True
示例#17
0
def config_snapshot_interval(dut, **kwargs):
    """
    configuring the water mark intervals
    Author: prudviraj k ([email protected])
    :param dut:
    :param kwargs: Needed arguments to update the  watermark configuration
    :return:
    """
    snapshot_arg = kwargs
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type in ["rest-patch", "rest-put"] and snapshot_arg['snap'] in [
            "clear_buffer-pool watermark", "sonic-clear buffer-pool watermark"
    ]:
        cli_type = 'klish'
    if not snapshot_arg:
        st.error("Mandatory arguments are not given")
    if cli_type == "click":
        if snapshot_arg['snap'] == "interval":
            command = "config watermark interval {}".format(
                snapshot_arg['interval_val'])
        elif snapshot_arg['snap'] == "telemetry":
            command = "config watermark telemetry interval {}".format(
                snapshot_arg['interval_val'])
        elif snapshot_arg['snap'] == "clear_snaphot_interval":
            command = "sonic-clear watermark interval"
        elif snapshot_arg['snap'] == "clear_snapshot_counters":
            command = "sonic-clear {} {} {}".format(
                snapshot_arg['group'], snapshot_arg['table'],
                snapshot_arg['counter_type'])
        elif snapshot_arg['snap'] == "clear_buffer-pool watermark":
            command = "sonic-clear buffer-pool watermark"
        elif snapshot_arg['snap'] == "clear_buffer-pool persistent-watermark":
            command = "sonic-clear buffer-pool persistent-watermark"
        st.config(dut, command, type=cli_type)
        return True
    elif cli_type == "klish":
        if snapshot_arg['snap'] == "interval":
            command = "watermark interval {}".format(
                snapshot_arg['interval_val'])
        elif snapshot_arg['snap'] == "telemetry":
            command = "watermark telemetry interval {}".format(
                snapshot_arg['interval_val'])
        elif snapshot_arg['snap'] == "clear_snaphot_interval":
            command = "no watermark interval"
        elif snapshot_arg['snap'] == "clear_snapshot_counters":
            command = "clear {} {} {}".format(snapshot_arg['group'],
                                              snapshot_arg['table'],
                                              snapshot_arg['counter_type'])
        elif snapshot_arg['snap'] == "clear_buffer-pool watermark":
            command = "clear buffer_pool watermark"
        elif snapshot_arg['snap'] == "clear_buffer-pool persistent-watermark":
            command = "clear buffer_pool persistent-watermark"
        st.config(dut, command, type=cli_type)
        return True
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        if snapshot_arg['snap'] == "interval":
            url = rest_urls['config_watermark_interval']
            data = {
                "openconfig-qos-ext:refresh-interval":
                snapshot_arg['interval_val']
            }
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url, json_data=data):
                return False
        elif snapshot_arg['snap'] == "telemetry":
            url = rest_urls['config_telemetry_interval']
            data = {
                "openconfig-qos-ext:refresh-interval":
                snapshot_arg['interval_val']
            }
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url, json_data=data):
                return False
        elif snapshot_arg['snap'] == "clear_snaphot_interval":
            url = rest_urls['config_watermark_interval']
            if not delete_rest(dut, http_method='delete', rest_url=url):
                return False
        elif snapshot_arg['snap'] == "clear_snapshot_counters":
            url = rest_urls['clear_watermark_counters']
            data = {
                "openconfig-qos-ext:input": {
                    "buffer": snapshot_arg['group'],
                    "buffer-type": snapshot_arg['counter_type'],
                    "watermark-type": snapshot_arg['table']
                }
            }
            if not config_rest(
                    dut, http_method='post', rest_url=url, json_data=data):
                return False
        return True
    else:
        st.error("Unsupported UI Type: {} provided".format(cli_type))
        return False
示例#18
0
def config_static_ndp(dut,
                      ip6_address,
                      mac_address,
                      interface,
                      operation="add",
                      **kwargs):
    """
    Config static ndp
    Author: Chaitanya Vella ([email protected])
    :param dut:
    :param ip6_address:
    :param mac_address:
    :param interface:
    :param operation:
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    command = ''
    if cli_type == 'click':
        interface = st.get_other_names(
            dut, [interface])[0] if '/' in interface else interface
        oper = "replace" if operation == "add" else "del"
        command = "ip -6 neighbor {} {} lladdr {} dev {}".format(
            oper, ip6_address, mac_address, interface)
    elif cli_type == 'klish':
        command = list()
        intf = get_interface_number_from_name(interface)
        command.append('interface {} {}'.format(intf["type"], intf["number"]))
        cmd = 'ipv6 neighbor {} {}'.format(
            ip6_address, mac_address
        ) if operation == 'add' else 'no ipv6 neighbor {} {}'.format(
            ip6_address, mac_address)
        command.extend([cmd, 'exit'])
    elif cli_type in ['rest-patch', 'rest-put']:
        rest_urls = st.get_datastore(dut, 'rest_urls')
        port_index = get_subinterface_index(dut, interface)
        if operation == 'add':
            url = rest_urls['config_static_ndp'].format(name=interface,
                                                        index=port_index)
            config_data = {
                "openconfig-if-ip:neighbor": [{
                    "ip": ip6_address,
                    "config": {
                        "ip": ip6_address,
                        "link-layer-address": mac_address
                    }
                }]
            }
            if not config_rest(
                    dut, rest_url=url, http_method=cli_type,
                    json_data=config_data):
                st.error(
                    "Failed to configure static neighbor with IP: {} MAC: {} on INTF: {}"
                    .format(ip6_address, mac_address, interface))
                return False
        else:
            url = rest_urls['delete_static_ndp'].format(name=interface,
                                                        index=port_index,
                                                        ip=ip6_address)
            if not delete_rest(dut, rest_url=url):
                st.error(
                    "Failed to delete static neighbor with IP: {} MAC: {} on INTF: {}"
                    .format(ip6_address, mac_address, interface))
                return False
    else:
        st.error("Unsupported CLI Type: {}".format(cli_type))
        return False
    if command:
        st.config(dut, command, type=cli_type)
    return True
示例#19
0
def delete_static_arp(dut,
                      ipaddress,
                      interface="",
                      mac="",
                      cli_type="",
                      vrf=""):
    """
    To delete static arp
    Author: Prudvi Mangadu ([email protected])
    :param dut:
    :param ipaddress:
    :param interface:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    command = ''
    if cli_type == "click":
        command = "arp -d {} ".format(ipaddress)
        if interface:
            command += " -i {}".format(interface)
    elif cli_type == "klish":
        if interface:
            if mac:
                macaddress = mac
            else:
                output = show_arp(dut,
                                  ipaddress=ipaddress,
                                  interface=interface,
                                  vrf=vrf)
                if len(output) == 0:
                    st.error(
                        "Did not find static arp entry with IP : {} and Interface : {}"
                        .format(ipaddress, interface))
                    return False
                else:
                    macaddress = output[0]["macaddress"]
            intf = get_interface_number_from_name(interface)
            command = "interface {} {}".format(intf['type'], intf['number'])
            command = command + "\n" + "no ip arp {} {}".format(
                ipaddress, macaddress) + "\n" + "exit"
        else:
            st.error(
                "'interface' option is mandatory for deleting static arp entry in KLISH"
            )
            return False
    elif cli_type in ['rest-patch', 'rest-put']:
        if not interface:
            st.error(
                "'interface' option is mandatory for deleting static arp entry in REST"
            )
            return False
        port_index = get_subinterface_index(dut, interface)
        rest_urls = st.get_datastore(dut, 'rest_urls')
        url = rest_urls['delete_static_arp'].format(name=interface,
                                                    index=port_index,
                                                    ip=ipaddress)
        if not delete_rest(dut, rest_url=url):
            st.error(
                "Failed to delete static ARP with INTF: {},  IP: {}".format(
                    interface, ipaddress))
            return False
    else:
        st.error("Unsupported CLI_TYPE: {}".format(cli_type))
        return False
    if command:
        st.config(dut, command, type=cli_type)
    return True
示例#20
0
def config(dut, **kwargs):
    """
    Add/Delete  username with password and role to the device.
    Author : Prudvi Mangadu ([email protected])
    :param :dut:
    :param :username:
    :param :password:
    :param :role:   admin | operator
    :param :group:
    :param :cli_type:  click | klish
    :param :no_form: 0[False] | 1[True]

    :Usage:
    config(vars.D1, username='******', password='******', role='operator', cli_type='kilsh')
    config(vars.D1, username='******', cli_type='kilsh', no_form=True)
    config(vars.D1, username='******', password='******', role='admin', cli_type='click', no_form=0)
    config(vars.D1, username='******', password_update='test1234', cli_type='click', no_form=0)
    config(vars.D1, group='admin_test', cli_type='click', no_form=0)
    config(vars.D1, group='admin_test', cli_type='click', no_form=1)
    config(vars.D1, username='******', password='******', role='admin', cli_type='click', no_form=1)
    """
    cli_type = kwargs.get("cli_type", "")
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    no_form = kwargs.get("no_form", False)

    if cli_type == "click":
        if not no_form:
            if kwargs.get('group'):
                st.config(dut, "groupadd {}".format(kwargs['group']))
            if kwargs.get('username'):
                command = "useradd {} -m".format(kwargs['username'])
                if kwargs.get('role'):
                    command += " -g {}".format(kwargs['role'])
                st.config(dut, command)
            if kwargs.get('username') and kwargs.get('password'):
                st.change_passwd(dut, kwargs['username'], kwargs['password'])
            if kwargs.get('username') and kwargs.get('append_role'):
                st.config(
                    dut, "usermod -aG {} {}".format(kwargs['append_role'],
                                                    kwargs['username']))
        else:
            if kwargs.get('username') and kwargs.get('role'):
                st.config(
                    dut, "gpasswd -d {} {}".format(kwargs['username'],
                                                   kwargs['role']))
            if kwargs.get('group'):
                st.config(dut, "groupdel {}".format(kwargs['group']))
            if kwargs.get('username'):
                st.config(dut, "userdel {} -r".format(kwargs['username']))

    elif cli_type == "klish":
        if not kwargs.get('username'):
            st.error("Mandatory parameter 'username' is missing")
            return False
        if not no_form:
            if not kwargs.get("password") and not kwargs.get('role'):
                st.error(
                    "Mandatory parameter 'password' and 'role' is missing")
                return False
            if kwargs['role'] == 'sudo':
                kwargs['role'] = 'operator'
        command = "username {} password {} role {}".format(
            kwargs['username'], kwargs['password'], kwargs['role'])
        if no_form:
            command = "no username {} ".format(kwargs['username'])
        st.config(dut, command, type=cli_type, skip_error_check=True)
        add_user(dut, kwargs['username'])
    elif cli_type in ['rest-patch', 'rest-put']:
        if not no_form:
            if kwargs['role'] == 'sudo':
                kwargs['role'] = 'operator'
            data = {
                "openconfig-system:user": [{
                    "username": str(kwargs['username']),
                    "config": {
                        "username": str(kwargs['username']),
                        "password": "",
                        "password-hashed": hashed_pwd(kwargs['password']),
                        "ssh-key": "",
                        "role": str(kwargs['role'])
                    }
                }]
            }
            rest_urls = st.get_datastore(dut, "rest_urls")
            url1 = rest_urls['user_creation_del'].format(kwargs['username'])
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url1, json_data=data):
                st.error("Failed to configure user {} ".format(
                    kwargs['username']))
                return False
        if no_form:
            rest_urls = st.get_datastore(dut, "rest_urls")
            url1 = rest_urls['user_creation_del'].format(kwargs['username'])
            if not delete_rest(dut, http_method=cli_type, rest_url=url1):
                st.error("Failed to delete user {} ".format(
                    kwargs['username']))
    else:
        st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
        return False
    return True
示例#21
0
def delete_vlan_member(dut,
                       vlan,
                       port_list,
                       tagging_mode=False,
                       cli_type='',
                       skip_error_check=False):
    """
    Delete Members in VLAN
    Author : Prudvi Mangadu ([email protected])
    :param dut:
    :param vlan:
    :param port_list:
    :param participation_mode:
    :param cli_type:
    :return:
    """
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    st.log("Delete member {} from the VLAN {}".format(port_list, vlan))
    if tagging_mode:
        participation_mode = "trunk"
    else:
        participation_mode = "access"
    port_li = make_list(port_list)
    commands = list()
    rest_fail_status = False
    for each_port in port_li:
        if cli_type == "click":
            command = "config vlan member del {} {}".format(vlan, each_port)
            out = st.config(dut, command, skip_error_check=skip_error_check)
            if "is not a member of Vlan{}".format(vlan) in out:
                st.error("{} is not a member of Vlan{}".format(
                    each_port, vlan))
                return False
            if "Vlan{} doesn't exist".format(vlan) in out:
                st.error("Vlan{} doesn't exist".format(vlan))
                return False
        elif cli_type == "klish":
            interface_details = get_interface_number_from_name(each_port)
            if not interface_details:
                st.log(
                    "Interface details not found {}".format(interface_details))
                return False
            commands.append("interface {} {}".format(
                interface_details.get("type"),
                interface_details.get("number")))
            if participation_mode == "trunk":
                command = "switchport trunk allowed Vlan remove {}".format(
                    vlan)
                commands.append("{}".format(command))
            elif participation_mode == "access":
                command = "switchport access Vlan"
                commands.append("no {}".format(command))
            commands.append("exit")
        elif cli_type in ["rest-put", "rest-patch"]:
            if participation_mode == "access":
                if "Eth" in get_interface_number_from_name(each_port)["type"]:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["interface_access_member_config"].format(
                            each_port)
                else:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["aggregate_access_member_config"].format(
                            each_port)
            else:
                vlan_id = str(vlan).split('-')
                vlan = '{}..{}'.format(
                    vlan_id[0], vlan_id[1]) if len(vlan_id) > 1 else vlan
                if "Eth" in get_interface_number_from_name(each_port)["type"]:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["interface_trunk_member_config"].format(
                            each_port, vlan)
                else:
                    rest_url = st.get_datastore(
                        dut,
                        "rest_urls")["aggregate_trunk_member_config"].format(
                            each_port, vlan)
            output = delete_rest(dut, rest_url=rest_url, get_response=True)
            if not output:
                st.error("OUTPUT IS EMPTY FROM DELETE VLAN MEMBER REST CALL")
                return False
            st.log("STATUS: {}".format(output["status"]))
            if not rest_status(output["status"]):
                rest_fail_status = True
        else:
            st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
            return False
    if rest_fail_status:
        st.log("One of VLAN member DELETE REST call failed")
        return False
    if commands:
        st.config(dut,
                  commands,
                  type=cli_type,
                  skip_error_check=skip_error_check)
    return True
示例#22
0
def lldp_config(dut, **kwargs):
    """
    Set LLDP non default config parameters
    Author: Prasad Darnasi ([email protected])
    :param dut:
    :param txinterval:LLDP update packet interval
    txinterval in klish is timer
    :param txhold:LLDP hold time
    txhold in klish is multiplier
    :param interface:remote interface
    :param status:LLDP rx|tx|rx-and-tx|disabled|enable
    :param hostname:remote system name
    hostname in klish is system-name
    :param description:remote system description
    :param capability:LLDP optional capabilities
    capability in klish is tlv-select
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    config = kwargs.get('config', 'yes')
    no_form = '' if config == 'yes' else 'no'
    rest_urls = st.get_datastore(dut, "rest_urls")
    if cli_type == 'click':
        if 'txinterval' in kwargs:
            command = "configure lldp {} {}".format('tx-interval', kwargs['txinterval'])
            st.config(dut, command, type='lldp')
        if 'txhold' in kwargs:
            command = "configure lldp {} {}".format('tx-hold', kwargs['txhold'])
            st.config(dut, command, type='lldp')
        if 'status' in kwargs:
            if kwargs['status'] == "enable":
                kwargs['status'] = "rx-and-tx"
            if 'interface' in kwargs:
                command = "configure ports {} lldp status {}".format(kwargs['interface'], kwargs['status'])
            else:
                command = "configure lldp status {}".format(kwargs['status'])
            st.config(dut, command, type='lldp')
        if 'hostname' in kwargs:
            command = "configure system hostname {}".format(kwargs['hostname'])
            st.config(dut, command, type='lldp')
        if 'capability' in kwargs and 'config' in kwargs:
            cap = kwargs['capability']
            cap_li = list(cap) if isinstance(cap, list) else [cap]
            for each_cap in cap_li:
                if kwargs['config'] == 'yes':
                    command = "config lldp {}".format(each_cap)
                else:
                    command = "unconfigure lldp {}".format(each_cap)
                st.config(dut, command, type='lldp')
        return True

    elif cli_type == 'klish':
        cmds = []
        if 'txinterval' in kwargs:
            cmds.append("{} lldp timer {}".format(no_form, kwargs['txinterval']))
        if 'txhold' in kwargs:
            cmds.append("{} lldp multiplier {}".format(no_form, kwargs['txhold']))
        if 'hostname'in kwargs:
            cmds.append("{} lldp system-name {}".format(no_form, kwargs['hostname']))
        if 'description'in kwargs:
            cmds.append("{} lldp system-description {}".format(no_form, kwargs['description']))
        if 'capability' in kwargs:
            cap = kwargs['capability']
            cap_li = list(cap) if isinstance(cap, list) else [cap]
            for e_cap in cap_li:
                if 'management-addresses-advertisements' in e_cap:
                    cmds.append("{} lldp tlv-select management-address".format(no_form))
                if 'capabilities-advertisements' in e_cap:
                    cmds.append("{} lldp tlv-select system-capabilities".format(no_form))
        if 'status' in kwargs:
            if 'interface' in kwargs:
                port = get_interface_number_from_name(kwargs['interface'])
                cmds.append('interface {} {}'.format(port['type'], port['number']))
            intf_mode = {"rx": "receive", "tx": "transmit", "rx-and-tx": "enable", "disabled": "disable", "enable":"enable"}
            status = intf_mode[kwargs['status']]
            if status == 'disable':
                no_form = "no"
                status = "enable"
            cmds.append("{} lldp {}".format(no_form, status))
            if 'interface' in kwargs:
                cmds.append('exit')
        output = st.config(dut, cmds, type=cli_type)
        if "Error:" in output:
            st.error("LLDP config failed")
            st.log(output)
            return False
        return True
    elif cli_type in ["rest-put", "rest-patch"]:
        if 'status' in kwargs and 'interface' not in kwargs:
            status = kwargs['status']
            if status in ['enable','rx-and-tx']:
                url = rest_urls['config_lldp_enabled']
                json_data = {"openconfig-lldp:enabled": True}
                if config == 'yes':
                    config_rest(dut, http_method=cli_type, rest_url=url, json_data=json_data)
                else:
                    delete_rest(dut, rest_url=url)
            elif status == 'disabled':
                url = rest_urls['tx_rx_lldp_enable']
                delete_rest(dut,rest_url = url)
            elif status == 'tx':
                json_data = {"openconfig-lldp-ext:mode": "TRANSMIT"}
                url = rest_urls['tx_rx_lldp_enable']
                if kwargs.get('config', 'yes') == 'yes':
                    config_rest(dut, http_method=cli_type, url= url, json_data=json_data)
                else:
                    delete_rest(dut, rest_url = url)
            elif status == 'rx':
                json_data = {"openconfig-lldp-ext:mode": "RECEIVE"}
                url = rest_urls['tx_rx_lldp_enable']
                if kwargs.get('config', 'yes') == 'yes':
                    config_rest(dut, http_method=cli_type, url= url, json_data=json_data)
                else:
                    delete_rest(dut, rest_url = url)
        if 'txinterval' in kwargs:
            url = rest_urls['txinterval_config']
            json_data = { "openconfig-lldp:hello-timer": str(kwargs['txinterval']) }
            if kwargs.get('config', 'yes') == 'yes':
                config_rest(dut, http_method=cli_type, rest_url = url, json_data=json_data)
            else:
                delete_rest(dut, rest_url = url)
        if 'txhold' in kwargs:
            json_data = { "openconfig-lldp-ext:multiplier": kwargs['txhold'] }
            url = rest_urls['txhold_config']
            if kwargs.get('config', 'yes') == 'yes':
                config_rest(dut, http_method=cli_type, rest_url = url, json_data=json_data)
            else:
                delete_rest(dut, rest_url = url)
        if 'hostname'in kwargs:
            json_data = { "openconfig-lldp:system-name": str(kwargs['hostname']) }
            url = rest_urls['system_name_config']
            if kwargs.get('config', 'yes') == 'yes':
                config_rest(dut, http_method=cli_type, rest_url = url, json_data=json_data)
            else:
                delete_rest(dut, rest_url = url)
        if 'description'in kwargs:
            json_data= { "openconfig-lldp:system-description": kwargs['description'] }
            url = rest_urls['system_description_config']
            if kwargs.get('config', 'yes') == 'yes':
                config_rest(dut, http_method=cli_type, rest_url = url, json_data=json_data)
            else:
                delete_rest(dut, rest_url = url)
        if 'capability' in kwargs:
            cap = kwargs['capability']
            cap_li = list(cap) if isinstance(cap, list) else [cap]
            for e_cap in cap_li:
                if 'management-addresses-advertisements' in e_cap:
                    if kwargs.get('config', 'yes') == 'yes':
                        url = rest_urls['clear_tlv_advertise'].format("MANAGEMENT_ADDRESS")
                        if not delete_rest(dut, rest_url = url):
                            st.error("Failed to enable LLDP TLV: MANAGEMENT_ADDRESS")
                            return False
                    else:
                        json_data = {"openconfig-lldp:suppress-tlv-advertisement": ["MANAGEMENT_ADDRESS"]}
                        url = rest_urls['suppress_tlv_advertisement']
                        if not config_rest(dut, http_method=cli_type, rest_url = url, json_data=json_data):
                            st.error("Failed to disable LLDP TLV: MANAGEMENT_ADDRESS")
                            return False
                if 'capabilities-advertisements' in e_cap:
                    if kwargs.get('config', 'yes') == 'yes':
                        url = rest_urls['clear_tlv_advertise'].format("SYSTEM_CAPABILITIES")
                        if not delete_rest(dut, rest_url = url):
                            st.error("Failed to enable LLDP TLV: SYSTEM_CAPABILITIES")
                            return False
                    else:
                        json_data = {"openconfig-lldp:suppress-tlv-advertisement": ["SYSTEM_CAPABILITIES"]}
                        url = rest_urls['suppress_tlv_advertisement']
                        if not config_rest(dut, http_method=cli_type, rest_url = url, json_data=json_data):
                            st.error("Failed to disable LLDP TLV: SYSTEM_CAPABILITIES")
                            return False
        if 'interface' in kwargs and 'status' in kwargs:
            status = kwargs['status']
            url = rest_urls['config_lldp']
            params_data = {"name": kwargs['interface']}
            if status == 'disabled':
                params_data.update(enabled=False)
            if status == 'enable' or status == "rx-and-tx":
                params_data.update(enabled=True)
            if status == 'tx':
                if config == 'yes':
                    params_data.update({"openconfig-lldp-ext:mode": "TRANSMIT"})
                else:
                    del_url = rest_urls['tx_rx_lldp_enable_intf'].format(kwargs['interface'])
                    if not delete_rest(dut, rest_url = del_url):
                        return False
            if status == 'rx':
                if config == 'yes':
                    params_data.update({"openconfig-lldp-ext:mode": "RECEIVE"})
                else:
                    del_url = rest_urls['tx_rx_lldp_enable_intf'].format(kwargs['interface'])
                    if not delete_rest(dut, rest_url = del_url):
                        return False
            if len(params_data) > 1:
                json_data = {"openconfig-lldp:interfaces": {"interface": [{"name": kwargs['interface'], "config": params_data}]}}
                if not config_rest(dut, http_method=cli_type, rest_url = url, json_data=json_data):
                    return False
        return True
    else:
        st.error('Unsupported UI TYPE - {}'.format(cli_type))
        return False
示例#23
0
def config_nat_pool_binding(dut, **kwargs):
    """
    Config NAT pool bindings
    Author:[email protected]

    :param :dut:
    :param :config: add/del:
    :param :binding_name:
    :param :pool_name:
    :param :nat_type:
    :param :twice_nat_id:
    :param :acl_name:

    usage:
    config_nat_pool_binding(dut1, binding_name="name", pool_name="pool1", acl_name="acl1", nat_type="dnat",
    config="add")
    """
    #  config nat add binding bind1 test1 acl1
    instance = 0
    result = False
    command = ''
    cli_type = st.get_ui_type(dut, **kwargs)
    skip_error_check = kwargs.get("skip_error_check", True)
    if cli_type not in ["click", "klish", "rest-patch", "rest-put"]:
        st.log("UNSUPPORTE CLI TYPE")
        return False
    if "binding_name" not in kwargs and "config" not in kwargs:
        st.error("Mandatory params binding_name, config not provided ")
        return result

    if kwargs["config"] == "add":
        if "pool_name" not in kwargs:
            st.error("Mandatory params pool_name is not provided ")
            return result
        if cli_type == "click":
            command = "config nat add binding {} {}".format(kwargs["binding_name"], kwargs["pool_name"])
            if "acl_name" in kwargs:
                command += " {}".format(kwargs["acl_name"])
            if "nat_type" in kwargs:
                command += " -nat_type {}".format(kwargs["nat_type"])
            if "twice_nat_id" in kwargs:
                command += ' -twice_nat_id {}'.format(kwargs["twice_nat_id"])
        elif cli_type == "klish":
            command = list()
            command.append("nat")
            cmd = "binding {} {}".format(kwargs["binding_name"], kwargs["pool_name"])
            if "acl_name" in kwargs:
                cmd += " {}".format(kwargs["acl_name"])
            if "nat_type" in kwargs:
                cmd += " {}".format(kwargs["nat_type"])
            if "twice_nat_id" in kwargs:
                cmd += " twice-nat-id {}".format(kwargs["twice_nat_id"])
            command.append(cmd)
            command.append("exit")
        elif cli_type in ["rest-patch", "rest-put"]:
            url = st.get_datastore(dut, "rest_urls")['config_nat_pool_binding'].format(instance, kwargs["binding_name"])
            data = {"openconfig-nat:config": {"nat-pool": kwargs["pool_name"]}}
            if "acl_name" in kwargs:
                data['openconfig-nat:config']['access-list'] = kwargs["acl_name"]
            if "nat_type" in kwargs:
                data['openconfig-nat:config']['type'] = kwargs["nat_type"].upper()
            if "twice_nat_id" in kwargs:
                data['openconfig-nat:config']['twice-nat-id'] = int(kwargs["twice_nat_id"])
            config_rest(dut, http_method=cli_type, rest_url=url, json_data=data)
            return True

    if kwargs["config"] == "del":
        if cli_type == "click":
            command = "config nat remove binding {} ".format(kwargs['binding_name'])
        elif cli_type == "klish":
            command = list()
            command.append("nat")
            command.append("no binding {}".format(kwargs["binding_name"]))
            command.append("exit")
        elif cli_type in ["rest-patch", "rest-put"]:
            url = st.get_datastore(dut, "rest_urls")['del_nat_pool_binding'].format(instance, kwargs["binding_name"])
            delete_rest(dut, rest_url=url)
            return True
    st.config(dut, command, type=cli_type, skip_error_check=skip_error_check)
    return True
示例#24
0
def config_remote_syslog_server(dut, **kwargs):
    """
    Configuring syslog server
    :param dut:
    :param host:
    :param source_intf:
    :param remote_port:
    :param vrf:
    :param skip_error:
    :param config:
    :return:
    log_obj.config_remote_syslog_server(dut = dut1, host = '10.59.130.43', config = 'yes')
    log_obj.config_remote_syslog_server(dut = data.dut1_client, host = dut1_dut2_ip[0], config = 'yes',source_intf = 'Ethernet48')
    log_obj.config_remote_syslog_server(dut = data.dut1_client, host = dut1_dut2_ip[0], config = 'yes',source_intf = 'Ethernet48', remote_port = 514)
    log_obj.config_remote_syslog_server(dut = data.dut1_client, host = dut2_dut1_ip[0], source_intf = 'Ethernet48',config = 'yes',cli_type='rest-put')
    log_obj.config_remote_syslog_server(dut = data.dut1_client, host = dut2_dut1_ip[0], source_intf = 'Ethernet48',config = 'yes',vrf = 'mgmt',cli_type='rest-put')
    """
    st.log('Config Syslog server')
    config =  kwargs.get('config','')
    host =  kwargs.get('host',None)
    source_intf =  kwargs.get('source_intf',None)
    remote_port =  kwargs.get('remote_port',None)
    vrf =  kwargs.get('vrf',None)
    skip_error = kwargs.get('skip_error',False)
    cli_type = kwargs.pop('cli_type', st.get_ui_type(dut,**kwargs))
    if config.lower() == 'yes':
        config = ''
    if host is None:
        st.error("Mandatory parameter hostname/IP address not found")
        return False
    if cli_type == 'klish':
        command = "{} logging server {}".format(config, host)
        if source_intf != None and config == '':
            command = command + " source-interface {}".format(source_intf)
        if remote_port != None and config == '':
            command = command + " remote-port {}".format(remote_port)
        if vrf != None and config == '':
            command = command + " vrf {}".format(vrf)
        output = st.config(dut, command, skip_error_check=skip_error, type="klish", conf=True)
        if "Could not connect to Management REST Server" in output:
            st.error("klish mode not working.")
            return False
        if "Error" in output:
            st.error("Error during configuration")
            return False
        return True
    elif cli_type in ['rest-patch','rest-put']:
        http_method = kwargs.pop('http_method',cli_type)
        rest_urls = st.get_datastore(dut,'rest_urls')
        if config == '':
            rest_url = rest_urls['config_remote_server'].format(str(host))
            ocdata = {"openconfig-system:config":{"host":str(host)}}
            if source_intf != None:
                ocdata["openconfig-system:config"]["openconfig-system-ext:source-interface"] = str(source_intf)
            if remote_port != None:
                ocdata["openconfig-system:config"]["remote-port"] = int(remote_port)
            if vrf != None:
                ocdata["openconfig-system:config"]["openconfig-system-ext:vrf-name"] = str(vrf)
                response = config_rest(dut, http_method=http_method, rest_url=rest_url, json_data=ocdata)
                if not response:
                    st.log(response)
                    return False
            return True
        else:
            rest_url = rest_urls['delete_remote_server'].format(str(host))
            response = delete_rest(dut, http_method='delete', rest_url=rest_url)
            if not response:
                st.log(response)
                return False
            return True
    else:
        st.log("Unsupported cli")
示例#25
0
def config_ntp_parameters(dut, **kwargs):
    """
    To Configure NTP paramters
    Author: Jagadish Chatrasi ([email protected])
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    config = kwargs.get('config', True)
    skip_error = kwargs.get('skip_error', False)
    commands = list()
    if cli_type == "klish":
        if 'source_intf' in kwargs:
            config_string = '' if config else 'no '
            for src_intf in make_list(kwargs['source_intf']):
                intf_data = get_interface_number_from_name(src_intf)
                commands.append('{}ntp source-interface {} {}'.format(config_string, intf_data['type'], intf_data['number']))
        if 'vrf' in kwargs:
            if not config:
                commands.append('no ntp vrf')
            else:
                commands.append('ntp vrf {}'.format(kwargs['vrf']))
        if 'authenticate' in kwargs:
            config_string = '' if config else 'no '
            commands.append('{}ntp authenticate'.format(config_string))
        if kwargs.get('auth_key_id'):
            if not config:
                commands.append('no ntp authentication-key {}'.format(kwargs['auth_key_id']))
            else:
                if kwargs.get('auth_type') and kwargs.get('auth_string'):
                    commands.append('ntp authentication-key {} {} "{}"'.format(kwargs['auth_key_id'], kwargs['auth_type'], kwargs['auth_string']))
        if kwargs.get('trusted_key'):
            config_string = '' if config else 'no '
            commands.append('{}ntp trusted-key {}'.format(config_string, kwargs['trusted_key']))
        if kwargs.get('servers'):
            servers = make_list(kwargs.get('servers'))
            for server in servers:
                if not config:
                    commands.append('no ntp server {}'.format(server))
                else:
                    commands.append('ntp server {} key {}'.format(server, kwargs['server_key']) if kwargs.get('server_key') else 'ntp server {}'.format(server))
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        if 'source_intf' in kwargs:
            for src_intf in make_list(kwargs['source_intf']):
                src_intf = 'eth0' if src_intf == "Management0" else src_intf
                if config:
                    url = rest_urls['ntp_config_source_interface']
                    payload = json.loads("""{"openconfig-system-ext:ntp-source-interface": ["string"]}""")
                    payload["openconfig-system-ext:ntp-source-interface"] = [src_intf]
                    if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload):
                        return False
                else:
                    url = rest_urls['ntp_delete_source_interface'].format(src_intf)
                    if not delete_rest(dut, rest_url=url):
                        return False
        if 'vrf' in kwargs:
            if config:
                url = rest_urls['ntp_config_vrf_delete']
                payload = json.loads("""{"openconfig-system-ext:vrf": "string"}""")
                payload["openconfig-system-ext:vrf"] = kwargs['vrf']
                if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload):
                    return False
            else:
                url = rest_urls['ntp_config_vrf_delete']
                if not delete_rest(dut, rest_url=url):
                    return False
        if 'authenticate' in kwargs:
            url = rest_urls['ntp_config']
            if config:
                payload = json.loads("""{"openconfig-system:config": {"enable-ntp-auth": true}}""")
                if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload):
                    return False
            else:
                payload = json.loads("""{"openconfig-system:config": {"enable-ntp-auth": false}}""")
                if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload):
                    return False
        if kwargs.get('auth_key_id'):
            keymap = {"md5" : "NTP_AUTH_MD5", 'sha1' : 'NTP_AUTH_SHA1', 'sha2-256' : 'NTP_AUTH_SHA2_256'}
            if not config:
                url = rest_urls['ntp_key_delete'].format(kwargs['auth_key_id'])
                if not delete_rest(dut, rest_url=url):
                    return False
            else:
                if kwargs.get('auth_type') and kwargs.get('auth_string'):
                    url = rest_urls['ntp_key_config']
                    payload = json.loads("""{"openconfig-system:ntp-keys": {
                                                "ntp-key": [
                                                  {
                                                    "key-id": 0,
                                                    "config": {
                                                      "key-id": 0,
                                                      "key-type": "string",
                                                      "openconfig-system-ext:encrypted": false,
                                                      "key-value": "string"
                                                    }
                                                  }
                                                ]
                                              }
                                            }""")
                    payload["openconfig-system:ntp-keys"]["ntp-key"][0]["key-id"] = int(kwargs['auth_key_id'])
                    payload["openconfig-system:ntp-keys"]["ntp-key"][0]["config"]["key-id"] = int(kwargs['auth_key_id'])
                    payload["openconfig-system:ntp-keys"]["ntp-key"][0]["config"]["key-type"] = keymap[kwargs['auth_type']]
                    payload["openconfig-system:ntp-keys"]["ntp-key"][0]["config"]["key-value"] = kwargs['auth_string']
                    if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload):
                        return False
        if kwargs.get('trusted_key'):
            if config:
                url = rest_urls['ntp_config']
                payload = json.loads("""{"openconfig-system:config": {"openconfig-system-ext:trusted-key": [0]}}""")
                payload["openconfig-system:config"]["openconfig-system-ext:trusted-key"] = [int(kwargs['trusted_key'])]
                if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload):
                    return False
            else:
                url = rest_urls["ntp_trusted_key_delete"].format(kwargs['trusted_key'])
                if not delete_rest(dut, rest_url=url):
                    return False
        if kwargs.get('servers'):
            servers = make_list(kwargs.get('servers'))
            for server in servers:
                if not config:
                    url = rest_urls['delete_ntp_server'].format(server)
                    if not delete_rest(dut, rest_url=url):
                        return False
                else:
                    url = rest_urls['config_ntp_server']
                    if kwargs.get('server_key'):
                        payload = json.loads("""{"openconfig-system:servers": {
                                                    "server": [
                                                      {
                                                        "address": "string",
                                                        "config": {
                                                          "address": "string",
                                                          "openconfig-system-ext:key-id": 0
                                                        }
                                                      }
                                                    ]
                                                  }
                                                }""")
                        payload["openconfig-system:servers"]["server"][0]["address"] = server
                        payload["openconfig-system:servers"]["server"][0]["config"]["address"] = server
                        payload["openconfig-system:servers"]["server"][0]["config"]["openconfig-system-ext:key-id"] = int(kwargs.get('server_key'))
                    else:
                        payload = json.loads("""{"openconfig-system:servers": {
                                                    "server": [
                                                      {
                                                        "address": "string",
                                                        "config": {
                                                          "address": "string"
                                                        }
                                                      }
                                                    ]
                                                  }
                                                }""")
                        payload["openconfig-system:servers"]["server"][0]["address"] = server
                        payload["openconfig-system:servers"]["server"][0]["config"]["address"] = server
                    if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload):
                        return False
    else:
        st.error("Unsupported CLI_TYPE: {}".format(cli_type))
        return False
    if commands:
        response = st.config(dut, commands, type=cli_type, skip_error_check=skip_error)
        if any(error in response.lower() for error in errors_list):
            st.error("The response is: {}".format(response))
            return False
    return True
示例#26
0
def config_nat_static(dut, **kwargs):
    """
    Config NAT Static
    Author:[email protected]

    :param :dut:
    :param :config: add/del
    :param :local_ip: local ipv4 address
    :param :global_ip: global ipv4 address
    :param :nat_type: snat/dnat
    :param :twice_nat_id: twice_nat_id for group
    :param :protocol: basic/tcp/udp
    :param :local_port_id: L4 port number:
    :param :global_port_id: L4 port number

    usage:
    config_nat_static(dut1, protocol="basic, global_ip="65,89.12.11", local_ip="10.0.0.1", nat_type="dnat",
    config="add")
    config_nat_static(dut1, protocol="basic, global_ip="65,89.12.11", local_ip="10.0.0.1", nat_type="snat",
    config="add")
    config_nat_static(dut1, protocol="basic, global_ip="65,89.12.11",local_ip="10.0.0.1", nat_type="dnat",
    twice_nat_id ="100", config="yes")
    config_nat_static(dut1, protocol="basic, global_ip="65,89.12.11",local_ip="10.0.0.1", nat_type="snat",
    twice_nat_id ="100", config="yes")
    config_nat_static(dut1, protocol="basic, global_ip="65,89.12.11", local_ip="10.0.0.1", config="del")
    """
    instance = 0
    result = False
    command = ""
    if "local_ip" not in kwargs and "global_ip" not in kwargs and "config" not in kwargs and "protocol" not in kwargs:
        st.error("Mandatory params local_ip,global_ip,config,protocol not provided ")
        return result
    cli_type = st.get_ui_type(dut, **kwargs)
    skip_error_check = kwargs.get("skip_error_check", True)
    if cli_type == "click":
        if kwargs["config"] == "add":
            if kwargs['protocol'] == 'all':
                command = "config nat add static basic {} {} ".format(kwargs["global_ip"], kwargs["local_ip"])

            if kwargs['protocol'] in ['tcp', 'udp']:
                command = "config nat add static {} {} {} {} {}".format(kwargs['protocol'],
                                                                        kwargs["global_ip"],
                                                                        kwargs["global_port_id"],
                                                                        kwargs["local_ip"],
                                                                        kwargs["local_port_id"])
            if "nat_type" in kwargs:
                command += ' -nat_type {}'.format(kwargs["nat_type"])

            if "twice_nat_id" in kwargs:
                command += ' -twice_nat_id {}'.format(kwargs["twice_nat_id"])

        if kwargs["config"] == "del":
            if kwargs['protocol'] == 'all':
                command = "config nat remove static basic {} {} ".format(kwargs["global_ip"],
                                                                         kwargs["local_ip"])
            if kwargs['protocol'] in ['tcp', 'udp']:
                command = "config nat remove static {} {} {} {} {} ".format(kwargs['protocol'], kwargs["global_ip"],
                                                                            kwargs["global_port_id"],
                                                                            kwargs["local_ip"],
                                                                            kwargs["local_port_id"])
        st.config(dut, command, type=cli_type, skip_error_check=skip_error_check)
    elif cli_type == "klish":
        commands = list()
        cmd = ''
        commands.append("nat")
        if kwargs.get("config") == "add":
            if kwargs['protocol'] == 'all':
                cmd = "static basic {} {}".format(kwargs["global_ip"], kwargs["local_ip"])
            elif kwargs['protocol'] in ['tcp', 'udp']:
                cmd = "static {} {} {} {} {}".format(kwargs['protocol'], kwargs["global_ip"], kwargs["global_port_id"],
                                                     kwargs["local_ip"], kwargs["local_port_id"])
            if "nat_type" in kwargs:
                cmd += " {}".format(kwargs["nat_type"])
            if "twice_nat_id" in kwargs:
                cmd += " twice-nat-id {}".format(kwargs["twice_nat_id"])
            commands.append(cmd)
        else:
            if kwargs['protocol'] == 'all':
                commands.append("no static basic {}".format(kwargs["global_ip"]))
            elif kwargs['protocol'] in ['tcp', 'udp']:
                commands.append(
                    "no static {} {} {}".format(kwargs['protocol'], kwargs["global_ip"], kwargs["global_port_id"]))
        commands.append("exit")
        st.config(dut, commands, type=cli_type, skip_error_check=skip_error_check)

    elif cli_type in ["rest-patch", "rest-put"]:
        data = {}
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = ''
        if kwargs.get("config") == "add":
            if kwargs['protocol'] == 'all':
                url = rest_urls['config_nat_static'].format(instance, kwargs["global_ip"])
                data = {"openconfig-nat:config": {"internal-address": kwargs["local_ip"]}}

            elif kwargs['protocol'] in ['tcp', 'udp']:
                protocol_no = 6 if kwargs['protocol'] == 'tcp' else 17
                url = rest_urls['config_napt_static'].format(instance, kwargs["global_ip"], protocol_no,
                                                             kwargs["global_port_id"])
                data = {"openconfig-nat:config": {"internal-address": kwargs["local_ip"],
                                                  "internal-port": int(kwargs["local_port_id"])}}
            if "nat_type" in kwargs:
                data['openconfig-nat:config']['type'] = kwargs["nat_type"].upper()
            if "twice_nat_id" in kwargs:
                data['openconfig-nat:config']['twice-nat-id'] = int(kwargs["twice_nat_id"])

            config_rest(dut, http_method=cli_type, rest_url=url, json_data=data)
            return True
        else:
            if kwargs['protocol'] == 'all':
                url = rest_urls['del_nat_static'].format(instance, kwargs["global_ip"])
            elif kwargs['protocol'] in ['tcp', 'udp']:
                protocol_no = 6 if kwargs['protocol'] == 'tcp' else 17
                url = rest_urls['del_napt_static'].format(instance, kwargs["global_ip"], protocol_no,
                                                          kwargs["global_port_id"])
            delete_rest(dut, rest_url=url)
            return True
    else:
        st.log("UNSUPPORTED CLI TYPE")
        return False
    return True
示例#27
0
def set_aaa_authentication_properties(dut,
                                      property,
                                      value,
                                      cli_type="",
                                      **kwargs):
    '''
    Configuring aaa authentication properties.
    '''
    cli_type = st.get_ui_type(dut, cli_type=cli_type)
    if cli_type == "click":
        command = "config aaa  authentication {} {}".format(property, value)
        st.config(dut, command, type=cli_type)
    elif cli_type == "klish":
        if property == "login":
            value = "local" if value == "default" else value
            if value == "local":
                command = "aaa authentication {} default {}".format(
                    property, value)
            else:
                values = re.split(" +", value)
                if len(values) == 2 and values[0] == "local":
                    command = "aaa authentication {} default {} group {}".format(
                        property, values[0], values[1])
                else:
                    command = "aaa authentication {} default group {}".format(
                        property, value)
        elif property == "failthrough":
            value = "disable" if value == "default" else value
            command = "aaa authentication failthrough {}".format(value)
        else:
            st.log(
                "UNSUPPORTED AUTHENTICATION PROPERTY -- {}".format(property))
            return False
        st.config(dut, command, type=cli_type)
    elif cli_type in ["rest-patch", "rest-put"]:
        rest_urls = st.get_datastore(dut, "rest_urls")
        url = rest_urls['aaa_autentication_method']
        url1 = rest_urls['aaa_autentication_failthrough']
        if property == "login" and value == "radius local":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method": [
                              "radius",
                              "local"
                            ]
                        }
                    """)
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               timeout=time_out):
                return False
        elif property == "login" and value == "local radius":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method": [
                              "local",
                              "radius"
                            ]
                        }
                    """)
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               timeout=time_out):
                return False
        elif property == "login" and value == "default":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method": [
                              "local"
                            ]
                        }
                    """)
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               timeout=time_out):
                return False
        elif property == "login" and value == "radius":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method": [
                              "radius"
                            ]
                        }
                    """)
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               timeout=time_out):
                return False
        elif property == "failthrough" and value == "enable":
            data = json.loads("""
                        {
                            "openconfig-system-ext:failthrough": "True"
                        }
                    """)
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url1,
                               json_data=data,
                               timeout=time_out,
                               **kwargs):
                return False
        elif property == "failthrough" and value == "default":
            if not delete_rest(dut, rest_url=url1, timeout=time_out):
                return False
        elif property == "login" and value == "tacacs+ local":
            data = json.loads("""
                            {
                              "openconfig-system:authentication-method": [
                                  "tacacs+",
                                  "local"
                                ]
                            }
                        """)
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               **kwargs):
                return False
        elif property == "login" and value == "local tacacs+":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method": [
                              "local",
                              "tacacs+"
                            ]
                        }
                    """)
            if not config_rest(dut,
                               http_method=cli_type,
                               rest_url=url,
                               json_data=data,
                               **kwargs):
                return False
        elif property == "login" and value == "tacacs+":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method":[
                              "tacacs+"
                            ]
                        }
                    """)
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url, json_data=data):
                return False
        elif property == "login" and value == "ldap":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method":[
                              "ldap"
                            ]
                        }
                    """)
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url, json_data=data):
                return False
        elif property == "login" and value == "ldap local":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method":[
                              "ldap",
                              "local"
                            ]
                        }
                    """)
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url, json_data=data):
                return False
        elif property == "login" and value == "local ldap":
            data = json.loads("""
                        {
                          "openconfig-system:authentication-method":[
                              "local",
                              "ldap"
                            ]
                        }
                    """)
            if not config_rest(
                    dut, http_method=cli_type, rest_url=url, json_data=data):
                return False

    else:
        st.log("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
        return False
    return True
示例#28
0
def config_udld_recover(dut, **kwargs):
    """
    Author: [email protected]
    config_udld_recover(dut=data.dut1,udld_recover='enable',module="udld")
    config_udld_recover(dut=data.dut1,udld_recover='disable',module="udld")
    udld.config_udld_recover(dut=dut1,udld_recover='enable',module="udld",cli_type = 'klish')
    udld.config_udld_recover(dut=dut1,udld_recover='enable',module="udld",cli_type = 'rest-put')
    Configure udld recover global
    :param dut:
    :param udld_recover:
    :module:
    :return:
    """
    cli_type = kwargs.pop('cli_type', st.get_ui_type(dut))
    module = kwargs.get('module', None)
    udld_recover = kwargs.get('udld_recover', None)
    st.log("Starting UDLD recover Configurations1...")
    my_cmd = ''
    if cli_type == 'click':
        if 'udld_recover' in kwargs and 'module' in kwargs:
            my_cmd = 'config errdisable recovery cause {} {}'.format(
                kwargs['udld_recover'], kwargs['module'])
        else:
            st.error(
                "Mandatory arguments udld enable or disable and module name should be given"
            )
            return False
        st.config(dut, my_cmd, type=cli_type)
    elif cli_type == 'klish':
        if udld_recover != None and module != None:
            if udld_recover == 'enable':
                my_cmd = 'errdisable recovery cause {}'.format(
                    kwargs['module'])
            elif udld_recover == 'disable':
                my_cmd = 'no errdisable recovery cause {}'.format(
                    kwargs['module'])
        else:
            st.error(
                "Mandatory arguments udld recover and module name should be given"
            )
            return False
        st.config(dut, my_cmd, type=cli_type)
    elif cli_type in ['rest-patch', 'rest-put']:
        http_method = kwargs.pop('http_method', cli_type)
        rest_urls = st.get_datastore(dut, 'rest_urls')
        rest_url = rest_urls['errdisable_recover_cause_config']
        if module != None and udld_recover != None:
            ocdata = {"openconfig-errdisable-ext:cause": [module.upper()]}
            if udld_recover.lower() == 'enable':
                response = config_rest(dut,
                                       http_method=http_method,
                                       rest_url=rest_url,
                                       json_data=ocdata)
            elif udld_recover.lower() == 'disable':
                response = delete_rest(dut,
                                       http_method='delete',
                                       rest_url=rest_url,
                                       json_data=ocdata)
        else:
            st.error(
                "Mandatory arguments udld recover and module name should be given"
            )
            return False
        if not response:
            st.log('Errdisable recovery cause config/unconfig failed')
            st.log(response)
            return False
        return True
    else:
        st.log("Unsupported CLI TYPE - {}".format(cli_type))
        return False
示例#29
0
def config_udld_recover_timer(dut, **kwargs):
    """
    Author: [email protected]
    config_udld_recover_timer(dut=data.dut1,udld_recover_timer='30')
    config_udld_recover_timer(dut=data.dut1,udld_recover_timer='300')
    udld.config_udld_recover_timer(dut=dut1,udld_recover_timer='30',cli_type = 'klish')

    Configure udld recover timer
    :param dut:
    :param udld_recover_timer: 300 default in sec
    :return:
    """
    cli_type = kwargs.pop('cli_type', st.get_ui_type(dut))
    udld_recover_timer = kwargs.get('udld_recover_timer', None)
    config = kwargs.get('config', '')
    st.log("Starting UDLD recover timer Configurations1...")
    my_cmd = ''
    if cli_type == 'click':
        if 'udld_recover_timer' in kwargs:
            my_cmd = 'config errdisable recovery interval {}'.format(
                kwargs['udld_recover_timer'])
        else:
            st.error("Mandatory argument udld recover timer should be given")
            return False
        st.config(dut, my_cmd, type=cli_type)
    elif cli_type == 'klish':
        if udld_recover_timer != None:
            if config == '':
                my_cmd = 'errdisable recovery interval {}'.format(
                    kwargs['udld_recover_timer'])
            else:
                my_cmd = 'no errdisable recovery interval'
        else:
            st.error("Mandatory argument udld recover timer should be given")
            return False
        st.config(dut, my_cmd, type=cli_type)
    elif cli_type in ['rest-patch', 'rest-put']:
        http_method = kwargs.pop('http_method', cli_type)
        rest_urls = st.get_datastore(dut, 'rest_urls')
        rest_url = rest_urls['errdisable_recover_interval_config']
        if udld_recover_timer != None:
            ocdata = {
                "openconfig-errdisable-ext:interval": int(udld_recover_timer)
            }
            if config == '':
                response = config_rest(dut,
                                       http_method=http_method,
                                       rest_url=rest_url,
                                       json_data=ocdata)
            else:
                response = delete_rest(dut,
                                       http_method='delete',
                                       rest_url=rest_url,
                                       json_data=ocdata)
        else:
            st.error(
                "Mandatory arguments udld recover interval should be given")
            return False
        if not response:
            st.log('Errdisable recovery interval config/unconfig failed')
            st.log(response)
            return False
        return True
    else:
        st.log("Unsupported CLI TYPE - {}".format(cli_type))
        return False
示例#30
0
def clear_threshold(dut, **kwargs):
    """
    Clear threshold configuration.
    Author: Prudvi Mangadu ([email protected])

    :param :dut:
    :param :threshold_type:  priority-group|queue
    :param :port_alias:
    :param :buffer_type: if threshold_type:priority-group {shared|headroom} |
                                                            else threshold_type:queue {unicast|multicast} | all
    :param :index: if threshold_type:priority-group - PGindex value | else threshold_type:queue - queueindex value
    :param :breach: all | event-id
    :param :cli_type:  click|klish
    :return:
    """
    cli_type = st.get_ui_type(dut, **kwargs)
    if cli_type == "click":
        if kwargs.get('port_alias') == 'CPU':
            kwargs['buffer_type'] = 'all'
        if kwargs.get("breach"):
            if kwargs.get('breach') == "all":
                commands = "sonic-clear threshold breach"
            else:
                commands = "sonic-clear threshold breach {}".format(kwargs.get("breach"))
        elif kwargs.get("threshold_type") and kwargs.get('buffer_type') == "all":
            commands = "sonic-clear {} threshold".format(kwargs['threshold_type'])
        else:
            if 'threshold_type' not in kwargs and 'port_alias' not in kwargs and 'buffer_type' not in kwargs and \
                    'index' not in kwargs:
                st.error("Mandatory parameter threshold_type/port_alias/index/type not found")
                return False
            if kwargs['threshold_type'] in ["priority-group", "queue"]:
                commands = "sonic-clear {} threshold {} {} {}".format(kwargs['threshold_type'], kwargs['port_alias'],
                                                                      kwargs['index'], kwargs['buffer_type'])
            else:
                st.error("Invalid threshold_type provided '{}'".format(kwargs['threshold_type']))
                return False
    elif cli_type == "klish":
        if kwargs.get("breach"):
            if kwargs.get('breach') == "all":
                commands = "clear threshold breach all"
            else:
                commands = "clear threshold breach {}".format(kwargs['breach'])
        else:
            if 'threshold_type' not in kwargs or 'port_alias' not in kwargs or 'buffer_type' not in kwargs:
                st.error("Mandatory parameter threshold_type/port_alias not found")
                return False
            ports_list = utils.make_list(kwargs['port_alias'])
            if kwargs['threshold_type'] in ["priority-group", "queue"]:
                commands = list()
                buffers = ['unicast', 'multicast'] if kwargs['threshold_type'] == 'queue' else ['shared', 'headroom']
                for port in ports_list:
                    if port.upper() == 'CPU':
                        commands.append("interface {}".format(port.upper()))
                    else:
                        interface_details = get_interface_number_from_name(port)
                        commands.append("interface {} {}".format(interface_details['type'], interface_details['number']))
                    if kwargs['buffer_type'] == 'all':
                        for buffer in buffers:
                            commands.extend(["no threshold {} {} {}".format(kwargs['threshold_type'], i, buffer) for i in range(8)])
                    else:
                        commands.append("no threshold {} {} {}".format(kwargs['threshold_type'], kwargs['index'], kwargs['buffer_type']))
                    commands.append("exit")
            else:
                st.error("Invalid threshold_type provided '{}'".format(kwargs['threshold_type']))
                return False
    elif cli_type in ["rest-patch","rest-put"]:
        if kwargs.get("breach"):
            if kwargs.get('breach') == "all":
                data = {"openconfig-qos-ext:input": {"breach-event-id": "ALL"}}
            else:
                data = {"openconfig-qos-ext:input": {"breach-event-id": str(kwargs.get('breach'))}}
            url = st.get_datastore(dut, "rest_urls")["clear_threshold_breaches"]
            if not config_rest(dut, http_method="post", rest_url= url, json_data=data):
                st.debug("Failed to clear threshold breaches")
                return False
        else:
            if 'threshold_type' not in kwargs or 'port_alias' not in kwargs or 'buffer_type' not in kwargs:
                st.error("Mandatory parameter threshold_type/port_alias not found")
                return False
            ports_list = utils.make_list(kwargs['port_alias'])
            if kwargs['threshold_type'] in ["priority-group", "queue"]:
                buffers = ['unicast', 'multicast'] if kwargs['threshold_type'] == 'queue' else ['shared', 'headroom']
                for port in ports_list:
                    if kwargs['buffer_type'] == 'all':
                        for buffer in buffers:
                            for i in range(8):
                                url = st.get_datastore(dut,"rest_urls")["delete_int_threshold"].\
                                format(kwargs['threshold_type'], buffer,port, i)
                                if not delete_rest(dut, rest_url=url):
                                    st.debug("Failed to clear threshold buffers")
                                    return False
                    else:
                        url = st.get_datastore(dut,"rest_urls")["delete_int_threshold"].format(kwargs['threshold_type'],
                                            kwargs['buffer_type'], port, kwargs['index'])
                        if not delete_rest(dut, rest_url=url):
                            st.debug("Failed to clear threshold buffers")
                            return False
            else:
                st.error("Invalid threshold_type provided '{}'".format(kwargs['threshold_type']))
                return False
        return True
    else:
        st.error("UNSUPPORTED CLI TYPE -- {}".format(cli_type))
        return False
    st.config(dut, commands, type=cli_type)
    return True