def config(dut, *argv, **kwargs): """ Calls to Configure IGMP Snooping. Author : Prudvi Mangadu ([email protected]) :param :dut: :param :vlan: :param :mode: :param :querier: :param :fast_leave: :param :query_interval: :param :last_member_query_interval: :param :query_max_response_time: :param :version: :param :mrouter_interface: :param :static_group_interface: :param :static_group_address: :param :cli_type: default - klish :param :no_form: default - False :return: Usage: config(vars.D1, 'mode', 'querier', 'fast_leave', query_interval=100, last_member_query_interval=300, query_max_response_time=400, version=2, mrouter_interface=vars.D1D2P1, static_group_interface=vars.D1D2P2, static_group_address='224.1.2.3', cli_type='klish') config(vars.D1, 'no_form' , 'mode', 'querier', 'fast_leave', query_interval='', last_member_query_interval='', query_max_response_time='', version='', mrouter_interface=vars.D1D2P1, static_group_interface=vars.D1D2P2, static_group_address='224.1.2.3', cli_type='klish') """ result = True cli_type = st.get_ui_type(dut, **kwargs) no_form = 'no' if 'no_form' in argv else '' if not kwargs.get('vlan'): st.error('vlan - Mandatory parameter is missing.') return False vlan = kwargs.get('vlan') if cli_type == 'klish': command = "ip igmp snooping" sub_cmd = [] if 'mode' in argv: sub_cmd.append('') if "querier" in argv: sub_cmd.append("querier") if "fast_leave" in argv: sub_cmd.append("fast-leave") for each_cmd in kwargs: if each_cmd in [ 'query_interval', 'last_member_query_interval', 'query_max_response_time', 'version' ]: if no_form: kwargs[each_cmd] = '' sub_cmd.append("{} {}".format(each_cmd.replace('_', '-'), kwargs[each_cmd])) if "mrouter_interface" in kwargs: sub_cmd.append("mrouter interface {}".format( kwargs['mrouter_interface'])) if "static_group_interface" in kwargs and "static_group_address" in kwargs: sub_cmd.append("static-group {} interface {}".format( kwargs['static_group_address'], kwargs['static_group_interface'])) command_list = [ "{} {} {}".format(no_form, command, each) for each in sub_cmd ] st.config(dut, ["interface Vlan {}".format(vlan)] + command_list + ["exit"], type=cli_type) elif cli_type == 'click': command = 'sudo config igmp_snooping' config0 = 'disable' if no_form else 'enable' config1 = 'del' if no_form else 'add' sub_cmd = [] if "mode" in argv: sub_cmd.append("{} {}".format(config0, vlan)) if "querier" in argv: sub_cmd.append("querier-{} {}".format(config0, vlan)) if "fast_leave" in argv: sub_cmd.append("fast-leave-{} {}".format(config0, vlan)) for each_cmd in kwargs: if each_cmd in [ 'query_interval', 'last_member_query_interval', 'query_max_response_time', 'version' ]: if no_form: kwargs[each_cmd] = DEFAULTS[each_cmd] sub_cmd.append("{} {} {}".format(each_cmd.replace('_', '-'), vlan, kwargs[each_cmd])) if "mrouter_interface" in kwargs: sub_cmd.append("mrouter-{} {} {}".format( config1, vlan, kwargs['mrouter_interface'])) if "static_group_interface" in kwargs and "static_group_address" in kwargs: sub_cmd.append("static-group-{} {} {} {}".format( config1, vlan, kwargs['static_group_interface'], kwargs['static_group_address'])) command_list = ["{} {}".format(command, each) for each in sub_cmd] st.config(dut, '; '.join(command_list), type=cli_type) elif cli_type in ["rest-put", "rest-patch"]: vlanid = "Vlan{}".format(vlan) rest_urls = st.get_datastore(dut, "rest_urls") if "mode" in argv: url = rest_urls['igmp_snooping_vlan_config_mode'].format(vlanid) if no_form: payload = json.loads( """{"openconfig-network-instance-deviation:enabled": false}""" ) else: payload = json.loads( """{"openconfig-network-instance-deviation:enabled": true}""" ) if not config_rest( dut, http_method=cli_type, rest_url=url, json_data=payload): result = False if "querier" in argv: url = rest_urls['igmp_snooping_vlan_config_querier'].format(vlanid) if no_form: payload = json.loads( """{"openconfig-network-instance-deviation:querier": false}""" ) else: payload = json.loads( """{"openconfig-network-instance-deviation:querier": true}""" ) if not config_rest( dut, http_method=cli_type, rest_url=url, json_data=payload): result = False if "fast_leave" in argv: url = rest_urls['igmp_snooping_vlan_config_fast_leave'].format( vlanid) if no_form: payload = json.loads( """{"openconfig-network-instance-deviation:fast-leave": false}""" ) else: payload = json.loads( """{"openconfig-network-instance-deviation:fast-leave": true}""" ) if not config_rest( dut, http_method=cli_type, rest_url=url, json_data=payload): result = False for each_cmd in kwargs: if each_cmd in [ 'query_interval', 'last_member_query_interval', 'query_max_response_time', 'version' ]: url = rest_urls['igmp_snooping_vlan_config_{}'.format( each_cmd)].format(vlanid) if no_form: if not delete_rest(dut, rest_url=url): result = False else: payload = { "openconfig-network-instance-deviation:{}".format( each_cmd.replace('_', '-')): int(kwargs[each_cmd]) } if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=payload): result = False elif each_cmd in ['mrouter_interface']: if no_form: url = rest_urls['igmp_snooping_vlan_delete_{}'.format( each_cmd)].format(vlanid, [kwargs[each_cmd]]) if not delete_rest(dut, rest_url=url): result = False else: cliType = "rest-patch" if cli_type == "rest-put" else cli_type url = rest_urls['igmp_snooping_vlan_config_{}'.format( each_cmd)].format(vlanid) payload = json.loads( """{"openconfig-network-instance-deviation:interface": [{"name": "string","config": {"enabled": true,"mrouter-interface": ["string"]}}]}""" ) payload["openconfig-network-instance-deviation:interface"][ 0]["name"] = vlanid payload["openconfig-network-instance-deviation:interface"][ 0]["config"]["mrouter-interface"] = [kwargs[each_cmd]] if not config_rest(dut, http_method=cliType, rest_url=url, json_data=payload): result = False if "static_group_interface" in kwargs and "static_group_address" in kwargs: if no_form: url = rest_urls[ 'igmp_snooping_vlan_config_static_entry_delete'].format( vlanid, kwargs["static_group_address"], "0.0.0.0", kwargs["static_group_interface"]) if not delete_rest(dut, rest_url=url): result = False else: url = rest_urls[ 'igmp_snooping_vlan_config_static_entry'].format(vlanid) payload = json.loads( """{"openconfig-network-instance-deviation:interface": [ { "name": "", "config": { "name": "", "enabled": true }, "staticgrps": { "static-multicast-group": [ { "group": "", "source-addr": "0.0.0.0", "config": { "group": "", "source-addr": "0.0.0.0", "outgoing-interface": [ {} ] } } ] } } ] }""") payload["openconfig-network-instance-deviation:interface"][0][ "name"] = vlanid payload["openconfig-network-instance-deviation:interface"][0][ "config"]["name"] = vlanid payload["openconfig-network-instance-deviation:interface"][0][ "staticgrps"]["static-multicast-group"][0][ "group"] = kwargs["static_group_address"] payload["openconfig-network-instance-deviation:interface"][0][ "staticgrps"]["static-multicast-group"][0]["config"][ "group"] = kwargs["static_group_address"] payload["openconfig-network-instance-deviation:interface"][0][ "staticgrps"]["static-multicast-group"][0]["config"][ "outgoing-interface"] = [ kwargs["static_group_interface"] ] if not config_rest( dut, http_method=cli_type, rest_url=url, json_data=payload): result = False else: st.log("Invalid cli_type provided: {}".format(cli_type)) result = False return result
def apply_queue_shaping_config(dut, shaper_data, **kwargs): """ API to configure Queue-Level shaper :param dut: :type dut: :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 st.debug("Provided queue-shaper configuration is: {}".format(shaper_data)) ports = list() if shaper_data.get('port'): ports = make_list(shaper_data['port']) if not shaper_data.get("policy_name"): st.error("policy_name is not provided") return False if cli_type == 'click': config_data = {"QUEUE": {}, "SCHEDULER": {}} if shaper_data.get('shaper_data'): shaper_info = make_list(shaper_data['shaper_data']) for ent in shaper_info: policy = "{}@{}".format(shaper_data['policy_name'], ent['queue']) if ('cir' in ent) or ('cbs' in ent) or ('pir' in ent) or ('pbs' in ent): temp = dict() temp[policy] = {} if 'meter_type' in ent: temp[policy].update(meter_type=ent['meter_type']) if 'cir' in ent: temp[policy].update(cir=str(ent['cir'])) if 'cbs' in ent: temp[policy].update(cbs=str(ent['cbs'])) if 'pir' in ent: temp[policy].update(pir=str(ent['pir'])) if 'pbs' in ent: temp[policy].update(pbs=str(ent['pbs'])) config_data["SCHEDULER"].update(temp) if ports: queue_map = dict() queue_map = { "{}|{}".format(port, ent['queue']): { "scheduler": "{}".format(policy) } for port in ports } config_data["QUEUE"].update(queue_map) config_data2 = {key: value for key, value in config_data.items()} for key, value in config_data2.items(): if not value: config_data.pop(key) json_config = json.dumps(config_data) json.loads(json_config) st.apply_json2(dut, json_config) elif cli_type == 'klish': shaper_info = make_list(shaper_data['shaper_data']) commands = list() commands.append("qos scheduler-policy {}".format( shaper_data['policy_name'])) for ent in shaper_info: if ('cir' in ent) or ('cbs' in ent) or ('pir' in ent) or ('pbs' in ent): commands.append("queue {}".format(ent['queue'])) if 'cir' in ent: commands.append("cir {}".format(get_klish_rate( ent['cir']))) if 'cbs' in ent: commands.append("cbs {}".format(ent['cbs'])) if 'pir' in ent: commands.append("pir {}".format(get_klish_rate( ent['pir']))) if 'pbs' in ent: commands.append("pbs {}".format(ent['pbs'])) commands.append("exit") commands.append("exit") if ports: for port in ports: intf_data = get_interface_number_from_name(port) commands.append("interface {} {}".format( intf_data['type'], intf_data['number'])) commands.append("scheduler-policy {}".format( shaper_data['policy_name'])) commands.append("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') shaper_info = make_list(shaper_data['shaper_data']) for ent in shaper_info: if ('cir' in ent) or ('cbs' in ent) or ('pir' in ent) or ('pbs' in ent): url = rest_urls['shaper_create_config'] params_config = dict() if 'cir' in ent: params_config.update(cir=str(get_rest_rate(ent['cir']))) if 'cbs' in ent: params_config.update(bc=int(ent['cbs'])) if 'pir' in ent: params_config.update(pir=str(get_rest_rate(ent['pir']))) if 'pbs' in ent: params_config.update(be=int(ent['pbs'])) config_data = { "openconfig-qos:scheduler-policies": { "scheduler-policy": [{ "name": shaper_data['policy_name'], "config": { "name": shaper_data['policy_name'] }, "schedulers": { "scheduler": [{ "sequence": int(ent['queue']), "config": { "sequence": int(ent['queue']) }, "two-rate-three-color": { "config": params_config } }] } }] } } if not config_rest(dut, rest_url=url, http_method=cli_type, json_data=config_data): st.error( "Failed to create queue-level shaper with shaper-data: {}" .format(ent)) return False if ports: for port in ports: url = rest_urls['apply_shaper_config'].format(port) config_data = { "openconfig-qos:config": { "name": shaper_data['policy_name'] } } if not config_rest(dut, rest_url=url, http_method=cli_type, json_data=config_data): st.error( "Failed to attach queue-shaper configuration to port: {}" .format(port)) return False else: st.error("Unsupported CLI Type: {}".format(cli_type)) return False return True
def apply_queue_shcheduling_config(dut, scheduler_data, **kwargs): """ API to configure scheduler parameters :param dut: :type dut: :param scheduler_data: :type scheduler_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 st.debug("Provided scheduler configuration is: {}".format(scheduler_data)) ports = list() if scheduler_data.get('port'): ports = make_list(scheduler_data['port']) if not scheduler_data.get("policy_name"): st.error("policy_name is not provided") return False if cli_type == 'click': config_data = {"QUEUE": {}, "SCHEDULER": {}} scheduler_info = make_list(scheduler_data['scheduler_data']) for ent in scheduler_info: temp = dict() queue_map = dict() policy = "{}@{}".format(scheduler_data['policy_name'], ent['queue']) temp[policy] = dict() if 'weight' in ent: temp[policy].update(weight=str(ent['weight'])) if ent.get('type'): temp[policy].update(type=ent['type'].upper()) if ports: queue_map = { "{}|{}".format(port, ent['queue']): { "scheduler": "{}".format(policy) } for port in ports } if temp[policy]: config_data['SCHEDULER'].update(temp) if queue_map: config_data['QUEUE'].update(queue_map) if not config_data['QUEUE']: config_data.pop('QUEUE') if not config_data['SCHEDULER']: config_data.pop('SCHEDULER') json_config = json.dumps(config_data) json.loads(json_config) st.apply_json2(dut, json_config) elif cli_type == 'klish': commands = list() commands.append("qos scheduler-policy {}".format( scheduler_data['policy_name'])) scheduler_info = make_list(scheduler_data['scheduler_data']) for ent in scheduler_info: commands.append("queue {}".format(ent['queue'])) if ent.get('type'): commands.append("type {}".format(ent['type'].lower())) if 'weight' in ent: commands.append("weight {}".format(ent['weight'])) commands.append("exit") commands.append("exit") if ports: for port in ports: intf_data = get_interface_number_from_name(port) commands.append("interface {} {}".format( intf_data['type'], intf_data['number'])) commands.append("scheduler-policy {}".format( scheduler_data['policy_name'])) commands.append("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') scheduler_info = make_list(scheduler_data['scheduler_data']) for ent in scheduler_info: if ent.get('type') or 'weight' in ent: url = rest_urls['shaper_create_config'] params_config = {"sequence": int(ent['queue'])} if ent.get('type'): params_config.update(priority=ent['type'].upper()) if 'weight' in ent: params_config.update( {"openconfig-qos-ext:weight": int(ent['weight'])}) config_data = { "openconfig-qos:scheduler-policies": { "scheduler-policy": [{ "name": scheduler_data['policy_name'], "config": { "name": scheduler_data['policy_name'] }, "schedulers": { "scheduler": [{ "sequence": int(ent['queue']), "config": params_config }] } }] } } if not config_rest(dut, rest_url=url, http_method=cli_type, json_data=config_data): st.error( 'Failed to create scheduler with data: {}'.format(ent)) return False if ports: for port in ports: url = rest_urls['apply_shaper_config'].format(port) config_data = { "openconfig-qos:config": { "name": scheduler_data['policy_name'] } } if not config_rest(dut, rest_url=url, http_method=cli_type, json_data=config_data): st.error( "Failed to attach queue-shaper configuration to port: {}" .format(port)) return False else: st.error("Unsupported CLI Type: {}".format(cli_type)) return False return True
def show_session(dut, mirror_session='', cli_type=""): cli_type = st.get_ui_type(dut, cli_type=cli_type) return show_session_all(dut, mirror_session, cli_type=cli_type)
def dhcp_relay_option_config(dut, **kwargs): """ API for DHCP relay option configuration like link-selection, src-interface and max-hop count :param dut: :param kwargs: :return: """ interface = kwargs.get("vlan", kwargs.get("interface", None)) option = kwargs.get("option", None) src_interface = kwargs.get("src_interface", None) hop_count = kwargs.get("max_hop_count",0) policy_action = kwargs.get("policy_action",None) ip_family = kwargs.get("family", "ipv4") cli_type = st.get_ui_type(dut, **kwargs) skip_error_check = kwargs.get("skip_error_check", False) action = kwargs.get("action","add") if not (interface): st.error("required interface value is not passed") return False command = "" if cli_type == "click": if ip_family == "ipv4": if option == "policy-action": command = "config interface ip dhcp-relay policy-action {} {}".format(interface,policy_action) else: command = "config interface ip dhcp-relay {} {} {}".format(option, action, interface) else: command = "config interface ipv6 dhcp-relay {} {} {}".format(option, action, interface) if action == "add": if option == "src-intf": if not src_interface: st.log("required src_interface value is not passed") return False command += " {}".format(src_interface) if option == "max-hop-count": command += " {}".format(hop_count) elif cli_type == "klish": command = list() interface_data = get_interface_number_from_name(interface) command.append("interface {} {}".format(interface_data.get("type"), interface_data.get("number"))) no_form = "" if action == "add" else "no" cmd = "" if ip_family == "ipv4": cmd += "{} ip dhcp-relay".format(no_form) else: cmd += "{} ipv6 dhcp-relay".format(no_form) if option == "src-intf": if not src_interface: if no_form != 'no': st.error("Required 'src_interface' value is not passed") return False src_interface = src_interface if no_form != "no" else "" cmd += " source-interface {}".format(src_interface) if option == "max-hop-count": max_hop_count = hop_count if no_form != "no" else "" cmd += " max-hop-count {}".format(max_hop_count) if option == "link-select": cmd += " link-select" if option == "vrf-select": cmd += " vrf-select" if option == "policy-action": cmd += " policy-action {}".format(policy_action) command.append(cmd) elif cli_type in ["rest-patch", "rest-put"]: config_dict = {'action': action, 'interface': interface, 'family': ip_family, 'cli_type': cli_type} if option == "src-intf": if not src_interface: if no_form != 'no': st.error("required src_interface value is not passed") return False config_dict['src_interface'] = src_interface elif option == "max-hop-count": config_dict['max_hop_count'] = hop_count elif option == "link-select": config_dict['link_select'] = True elif option == "vrf-select": config_dict['vrf_select'] = True elif option == "policy-action": config_dict['policy_action'] = policy_action else: st.error("Invalid option: {}".format(option)) return False if not dhcp_relay_config(dut, **config_dict): st.error("Failed to set the option: {}".format(option)) return False else: st.error("Unsupported CLI_type: {}".format(cli_type)) return False if command: st.debug("command is {}".format(command)) output = st.config(dut, command, skip_error_check=skip_error_check, type=cli_type) if "Error" in output: if skip_error_check: return True else: return False return True
def pre_config_ztp(): global vars global ssh_conn_obj_oob_v6 global ssh_conn_obj global ssh_conn_obj_oob_v4 global ssh_conn_obj_inb_v4 global ssh_conn_obj_inb_v6 vars = st.get_testbed_vars() # DHCPV6 out of band params ztp_params.dhcp6.ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "ip") ztp_params.dhcp6.username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "username") ztp_params.dhcp6.password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "password") ztp_params.dhcp6.oob_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "interface") ztp_params.dhcp6.oob_static_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "static_ip") # DHCPV4 out of band params ztp_params.dhcp.ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "ip") ztp_params.dhcp.username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "username") ztp_params.dhcp.password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "password") ztp_params.oob_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "interface") ztp_params.static_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "static_ip") #DHCPV6 in band params ztp_params.dhcp6.inband_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "ip") ztp_params.dhcp6.inband_username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "username") ztp_params.dhcp6.inband_password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "password") ztp_params.dhcp6.inband_static_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "static_ip") ztp_params.dhcp6.inband_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "interface") # DHCPV4 in band params ztp_params.dhcp.inband_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "ip") ztp_params.dhcp.inband_username = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "username") ztp_params.dhcp.inband_password = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "password") ztp_params.dhcp.inband_static_ip = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "static_ip") ztp_params.inband_port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "interface") ztp_params.dhcp6.oob_config_file = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "config_file") ztp_params.dhcp6.inband_config_file = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "config_file") ztp_params.config_path = utils_obj.ensure_service_params(vars.D1, "ztp", "config_path") ztp_params.dhcp6.oob_home_path = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "home_path") ztp_params.dhcp6.inband_home_path = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "home_path") ztp_params.port = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "port") ztp_params.dut_path = utils_obj.ensure_service_params(vars.D1, "ztp", "dut_path") ztp_params.ztp_cfg_file_name = utils_obj.ensure_service_params(vars.D1, "ztp", "ztp_cfg_file_name") ztp_params.provision_script_path = utils_obj.ensure_service_params(vars.D1, "ztp", "provision_script_path") ztp_params.dhcp.inband_v4_subnet = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "inband", "subnet") ztp_params.dhcp.oob_v4_subnet = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "subnet") ztp_params.dhcp6.inband_v6_subnet = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "subnet") ztp_params.dhcp6.oob_v6_subnet = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "subnet") ztp_params.dhcp6.client_ip_inband = utils_obj.ensure_service_params(vars.D1, "ztp", "dhcpv6", "inband", "client_ip") ztp_params.breakout = utils_obj.ensure_service_params(vars.D1, "ztp", "breakout") ztp_params.cli_type = st.get_ui_type(vars.D1) st.log("Clearing V4/V6 lease database from DUT ...") basic_obj.delete_directory_contents(vars.D1, config_params.lease_db_path) st.log("####### Connecting to DHCPV6 server -- OUT OF BAND ...###########") ssh_conn_obj_oob_v6 = con_obj.connect_to_device(ztp_params.dhcp6.ip, ztp_params.dhcp6.username, ztp_params.dhcp6.password) if not ssh_conn_obj_oob_v6: st.error("SSH connection object not found for DHCPV6 server OUT OF BAND.") if network_flag != "inband": reset_module_config() st.report_env_fail("ssh_connection_failed", ztp_params.dhcp6.ip) st.log("############Connecting to DHCPV4 server -- OUT OF BAND ...#############") ssh_conn_obj_oob_v4 = con_obj.connect_to_device(ztp_params.dhcp.ip, ztp_params.dhcp.username, ztp_params.dhcp.password) if not ssh_conn_obj_oob_v4: st.error("SSH connection object not found for DHCPV4 server OUT OF BAND.") # st.report_env_fail("ssh_connection_failed", ztp_params.dhcp6.ip) st.log("###########Connecting to DHCPV4 server -- IN BAND ...##############") ssh_conn_obj_inb_v4 = con_obj.connect_to_device(ztp_params.dhcp.inband_ip, ztp_params.dhcp.inband_username, ztp_params.dhcp.inband_password) if not ssh_conn_obj_inb_v4: st.error("SSH connection object not found for DHCPV4 server OUT OF BAND.") # st.report_env_fail("ssh_connection_failed", ztp_params.dhcp6.ip) ssh_conn_obj_inb_v6 = con_obj.connect_to_device(ztp_params.dhcp6.inband_ip, ztp_params.dhcp6.inband_username, ztp_params.dhcp6.inband_password) if not ssh_conn_obj_inb_v6: st.error("SSH connection object not found for DHCPV4 server OUT OF BAND.") if network_flag == "inband": reset_module_config() st.report_env_fail("ssh_connection_failed", ztp_params.dhcp6.inband_ip) st.log("###########Stopping V4/V6 services to avoid the DHCP option conflict .. ###########") v4_connection_objs = [ssh_conn_obj_oob_v4, ssh_conn_obj_inb_v4] for connection_obj in v4_connection_objs: if connection_obj: basic_obj.service_operations(connection_obj, config_params.dhcp_service_name, "stop", "server") if ztp_obj.verify_dhcpd_service_status(connection_obj, config_params.dhcpd_pid): st.log("{} service is running which is not expected".format(config_params.dhcp_service_name)) reset_module_config() st.report_fail("service_running_not_expected", config_params.dhcp_service_name) st.log("Restarting V6 services on required server .. ") if network_flag != "inband": ssh_conn_obj = ssh_conn_obj_oob_v6 st.log("Using OUT OF BAND V6 ssh object ... ") if ssh_conn_obj_inb_v6: basic_obj.service_operations(ssh_conn_obj_inb_v6, config_params.dhcp6_service_name, "stop", "server") if ztp_obj.verify_dhcpd_service_status(ssh_conn_obj_inb_v6, config_params.dhcpd6_pid): st.log("{} service is running which is not expected".format(config_params.dhcp6_service_name)) reset_module_config() st.report_fail("service_running_not_expected", config_params.dhcp6_service_name) else: st.log("SSH object for INB V6 server is not found ...") else: st.log("Using INBAND V6 ssh object ... ") ssh_conn_obj = ssh_conn_obj_inb_v6 if ssh_conn_obj_oob_v6: basic_obj.service_operations(ssh_conn_obj_oob_v6, config_params.dhcp6_service_name, "stop", "server") if ztp_obj.verify_dhcpd_service_status(ssh_conn_obj_oob_v6, config_params.dhcpd6_pid): st.log("{} service is running which is not expected".format(config_params.dhcp6_service_name)) reset_module_config() st.report_fail("service_running_not_expected", config_params.dhcp6_service_name) else: st.log("SSH object for OOB V6 server is not found ...") basic_obj.service_operations(ssh_conn_obj, config_params.dhcp6_service_name, "restart", "server") if not ztp_obj.verify_dhcpd_service_status(ssh_conn_obj, config_params.dhcpd6_pid): st.log("{} service is not running ".format(config_params.dhcp6_service_name)) reset_module_config() st.report_fail("service_running_not_expected", config_params.dhcp6_service_name) global dhcp6_port global dhcp6_static_ip global dhcp6_home_path global dhcp6_config_file if network_flag != "inband": dhcp6_port = ztp_params.dhcp6.oob_port dhcp6_static_ip = ztp_params.dhcp6.oob_static_ip dhcp6_home_path = ztp_params.dhcp6.oob_home_path dhcp6_config_file = ztp_params.dhcp6.oob_config_file ztp_params.home_path = ztp_params.dhcp6.oob_home_path else: dhcp6_port = ztp_params.dhcp6.inband_port # intf_obj.interface_noshutdown(vars.D1, dhcp6_port) dhcp6_static_ip = ztp_params.dhcp6.inband_static_ip dhcp6_home_path = ztp_params.dhcp6.inband_home_path dhcp6_config_file = ztp_params.dhcp6.inband_config_file ztp_params.home_path = ztp_params.dhcp6.inband_home_path basic_obj.ifconfig_operation(vars.D1, ztp_params.dhcp6.oob_port, "down") basic_obj.poll_for_system_status(vars.D1) # intf_obj.enable_dhcp_on_interface(vars.D1, dhcp6_port, "v6") ztp_cfg = {"admin-mode": True, "restart-ztp-interval": 30, "feat-console-logging": feat_logging_console} ztp_obj.config_ztp_backdoor_options(vars.D1, ztp_cfg)
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
def get_crm_resources(dut, family, cli_type=""): """ GET CRM resources w.r.t family. Author : Prudvi Mangadu ([email protected]) :param dut: :param family: :param cli_type: click or klish designation: :return: """ cli_type = st.get_ui_type(dut, cli_type=cli_type) family = family.lower() family_list = crm_get_family_list(dut) if family not in family_list: log = "family:'{}' is invalid , use any of valid family from - {}".format( family, ','.join(family_list)) st.error(log) return False if family in ['acl_table']: family = 'acl_group' if family in [ 'acl_table_entry', 'acl_table_counter', 'acl_table_stats', 'acl_group_entry', 'acl_group_counter' ]: temp = family family = 'acl_table' if cli_type == "click": command = 'crm show resources {}'.format(family.replace('_', ' ')) output = st.show(dut, command, type=cli_type) elif cli_type == "klish": command = 'show crm resources {}'.format(family.replace('_', ' ')) output = st.show(dut, command, type=cli_type) elif cli_type in ["rest-patch", "rest-put"]: output = list() rest_urls = st.get_datastore(dut, "rest_urls") if family == "all": family = [ 'dnat', 'fdb', 'ipmc', 'ipv4_route', 'ipv4_neighbor', 'ipv4_nexthop', 'ipv6_route', 'ipv6_neighbor', 'ipv6_nexthop', 'nexthop_group_member', 'nexthop_group_object', 'acl_table', 'acl_group' ] for each_family in family: output.append(get_crm_resources(dut, each_family)) elif "acl" not in family: resource = dict() url = rest_urls['crm_resources'].format("statistics") result = get_rest( dut, rest_url=url)["output"]["openconfig-system-crm:statistics"] if "_" not in family: resource["resourcename"] = "{}_entry".format(family) resource["usedcount"] = str( result["{}-entries-used".format(family)]) resource["availablecount"] = str( result["{}-entries-available".format(family)]) else: family = family.replace("_object", "") resource["resourcename"] = "{}".format(family) resource["usedcount"] = str(result["{}s-used".format( family.replace("_", "-"))]) resource["availablecount"] = str(result["{}s-available".format( family.replace("_", "-"))]) output.append(resource) else: if family == "acl_table": url = rest_urls['crm_resources'].format("acl-table-statistics") result = get_rest( dut, rest_url=url )["output"]["openconfig-system-crm:acl-table-statistics"] for each in result["acl-table-statistics-list"]: temp = {} temp["tableid"] = each["id"] temp["resourcename"] = "acl_counter" temp["availablecount"] = str(each["counter"]["available"]) temp["usedcount"] = str(each["counter"]["used"]) output.append(copy.copy(temp)) temp["resourcename"] = "acl_entry" temp["availablecount"] = str(each["entry"]["available"]) temp["usedcount"] = str(each["entry"]["used"]) output.append(copy.copy(temp)) else: url = rest_urls['crm_resources'].format("acl-statistics") result = get_rest( dut, rest_url=url )["output"]["openconfig-system-crm:acl-statistics"] for stage, stage_val in result.items(): resource = {} resource["state"] = stage.upper() for bindpoint, bindpoint_value in stage_val.items(): resource["bindpoint"] = bindpoint.upper() families = ["acl_group", "acl_table"] for each in families: resource["resourcename"] = each acl = each.replace("acl_", "") + "s" resource["availablecount"] = int( bindpoint_value["{}-available".format(acl)]) resource["usedcount"] = int( bindpoint_value["{}-used".format(acl)]) output.append(copy.copy(resource)) else: st.error("Unsupported cli type: {}".format(cli_type)) return False return output
def verify_crm_thresholds(dut, family, thresholdtype=None, highthreshold=None, lowthreshold=None, cli_type=""): """ To verify the CRM Threshold parameters Author : Prudvi Mangadu ([email protected]) :param dut: :param family: :param thresholdtype: :param highthreshold: :param lowthreshold: :param cli_type: click or klish designation: :return: """ family_list = crm_get_family_list(dut) if family not in family_list: st.log("CRM config for {} is not supported -- ignoring".format(family)) return True cli_type = st.get_ui_type(dut, cli_type=cli_type) output = get_crm_thresholds(dut, family, cli_type) # Handling few crm family cli commands for verify if cli_type in ['click', 'klish']: if family == "fdb": family = 'fdb_entry' if family == "dnat": family = 'dnat_entry' if family == "ipmc": family = 'ipmc_entry' if family == "snat": family = 'snat_entry' if family == "acl_group_entry": family = 'acl_entry' if family == "acl_group_counter": family = 'acl_counter' if family == 'nexthop_group_object': family = 'nexthop_group' entries = filter_and_select(output, None, {"resourcename": family}) if not entries: st.error( "No Entry found for given family in the table - {}".format(family)) return False if thresholdtype and not filter_and_select(entries, None, { "resourcename": family, "thresholdtype": thresholdtype }): st.error("Configured and Provided thresholdtype is not match.") return False if lowthreshold and not filter_and_select(entries, None, { "resourcename": family, 'lowthreshold': lowthreshold }): st.error("Configured and Provided lowthreshold is not match.") return False if highthreshold and not filter_and_select(entries, None, { "resourcename": family, "highthreshold": highthreshold }): st.error("Configured and Provided highthreshold is not match.") return False return True
def prologue_epilogue(): if st.get_ui_type() in ['klish']: st.report_unsupported( 'test_execution_skipped', 'Skipping Chef_MCLAG test case for ui_type={}'.format( st.get_ui_type())) st.log('Define Common config, including TGEN related, if any') initialize_topology() loc_lib.chef_pre_config(data.d1, data.d1_ip) if not chef_evpn_obj.sync_with_server_time( data.my_dut_list, chef_server.ip, chef_server.username, chef_server.password): st.report_env_fail("test_case_not_executeds") f1 = lambda x: chef_evpn_obj.delete_client_pem_files( data.d1, chef_server.client_path) f2 = lambda x: chef_evpn_obj.delete_client_pem_files( data.d2, chef_server.client_path) f3 = lambda x: chef_evpn_obj.delete_client_pem_files( data.d3, chef_server.client_path) putils.exec_all(True, [[f1, 1], [f2, 1], [f3, 1]]) chef_evpn_obj.generate_certs(chef_server.ssh_obj, chef_server.path) # Cleanup exisitng node if any chef_evpn_obj.delete_chef_node(chef_server.ssh_obj, ' '.join(data.node_list_mc), ' '.join(data.role_list_mc)) # Generate certs and bootstrap node chef_evpn_obj.generate_certs(chef_server.ssh_obj, chef_server.path) if not chef_evpn_obj.bootstrap_chef_node( chef_server.ssh_obj, chef_server.path, data.d1_ip, 'admin', 'broadcom', data.node_list_mc[0]): st.report_env_fail("chef_bootstrap_fail") if not chef_evpn_obj.bootstrap_chef_node( chef_server.ssh_obj, chef_server.path, data.d2_ip, 'admin', 'broadcom', data.node_list_mc[1]): st.report_env_fail("chef_bootstrap_fail") if not chef_evpn_obj.bootstrap_chef_node( chef_server.ssh_obj, chef_server.path, data.d3_ip, 'admin', 'broadcom', data.node_list_mc[2]): st.report_env_fail("chef_bootstrap_fail") # upload cookbook #chef_evpn_obj.upload_chef_cookbook(chef_server.ssh_obj, chef_server.path) yield st.log('Define Common cleanup, including TGEN related, if any') for role, node_name in zip(data.role_list_mc, data.node_list_mc): run_list = 'role[{}],recipe[sonic::vlan],recipe[sonic::lag],recipe[sonic::interface],recipe[sonic::mclag]'.format( role) chef_evpn_obj.update_node_run_list(chef_server.ssh_obj, node_name, run_list, 'remove') # Cleanup exisitng node if any chef_evpn_obj.delete_chef_node(chef_server.ssh_obj, ' '.join(data.node_list_mc), ' '.join(data.role_list_mc))
def set_crm_thresholds_value(dut, family, mode, value, cli_type=""): """ Configuring CRM Threshold values. Author : Prudvi Mangadu ([email protected]) :param dut: :param family: :param mode: :param value: :param cli_type: click or klish designation: :return: """ cli_type = st.get_ui_type(dut, cli_type=cli_type) family = family.lower() mode = mode.lower() if family == 'acl_table_stats': family = 'acl_table' family_list = crm_get_family_list(dut) if family not in family_list: log = "family: '{}' is invalid , use any of valid family from - {}".format( family, ','.join(family_list)) st.error(log) return False if mode not in mode_list: log = "mode:'{}' is invalid , use any of valid mode from - {}".format( mode, ','.join(mode_list)) st.error(log) return False command = "" if cli_type == "click": command = 'crm config thresholds {} {} {}'.format( family.replace('_', ' '), mode, value) if family == 'all': st.warn("Command: '{}' is not a Click command".format(command)) elif cli_type == "klish": command = 'crm thresholds {} {} {}'.format(family.replace('_', ' '), mode, value) elif cli_type in ["rest-patch", "rest-put"]: rest_urls = st.get_datastore(dut, "rest_urls") url = rest_urls['crm_thresholds'] config_json = {"openconfig-system-crm:threshold": {}} k = {"config": {}} k["config"][mode] = int(value) temp = dict() list1 = family.split("_") if len(list1) == 3: if "acl" in list1: temp = {list1[1]: {list1[2]: k}} else: temp["{}-{}".format(list1[1], list1[2])] = k config_json["openconfig-system-crm:threshold"][list1[0]] = temp elif len(list1) == 2: temp[list1[0]] = {list1[1]: k} config_json["openconfig-system-crm:threshold"] = temp else: temp[list1[0]] = k config_json["openconfig-system-crm:threshold"] = temp if not config_rest( dut, http_method=cli_type, rest_url=url, json_data=config_json): 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
def add_vlan_member(dut, vlan, port_list, tagging_mode=False, skip_error=False, no_form=False, cli_type=""): """ Add Members to VLAN Author : Prudvi Mangadu ([email protected]) :param dut: :param vlan: :param port_list: :param tagging_mode: :param skip_error: :param no_form: :param cli_type: :return: """ if not cli_type: cli_type = st.get_ui_type(dut) st.log("Add member to the VLAN") port_li = list(port_list) if isinstance(port_list, list) else [port_list] commands = list() for each_port in port_li: if cli_type == "click": if tagging_mode: command = "config vlan member add {} {}".format( vlan, each_port) else: command = "config vlan member add {} {} -u ".format( vlan, each_port) # Here handling the error while adding interface to vlan out = st.config(dut, command, skip_error_check=True) if "is already a member of Vlan{}".format(vlan) in out: st.error("{} is already 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 if "has ip address configured" in out: st.error( "Error: {} has ip address configured".format(each_port)) return False else: 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"))) participation_mode = "trunk" if tagging_mode else "access" if participation_mode == "trunk": command = "switchport trunk allowed Vlan {}".format(vlan) commands.append("no {}".format(command) if no_form else "{}". format(command)) elif participation_mode == "access": command = "switchport access Vlan" commands.append("no {}".format(command) if no_form else "{} {}".format(command, vlan)) commands.append("exit") if commands: out = st.config(dut, commands, type=cli_type, skip_error_check=True) if "Invalid VLAN:" in out: st.log("Vlan{} doesn't exist".format(vlan)) return False return True
def verify_groups(dut, *argv, **kwargs): """ Call to verify - show ip igmp snooping groups * Author : Prudvi Mangadu ([email protected]) :param :dut: :param :argv: groups | groups_vlan | vlan :param :verify_list [{"vlan':"500", "source_address":"192.168.1.2", "group_address":"224.1.2.2", "outgoing_ports":["Ethernet2","Ethernet4"], 'number_of_entries': '10'}, {"vlan": "600", "source_address":"192.168.3.2", "group_address":"224.4.2.2", "outgoing_ports":"Ethernet8"}] :return: """ result = True previous_vlan = None output = [] cli_type = st.get_ui_type(dut, **kwargs) if not kwargs.get('verify_list'): st.error("verify_list - mandatory parameter missing.") return False for data in kwargs.get("verify_list"): if not data.get('vlan'): st.error("vlan key is not found in verify_list data.") return False if "groups" in argv: if not output: output = show(dut, 'groups', cli_type=cli_type) elif "groups_vlan" in argv: if previous_vlan != data.get('vlan'): output = show(dut, groups_vlan=data.get('vlan'), cli_type=cli_type) elif "vlan" in argv: if previous_vlan != data.get('vlan'): output = show(dut, vlan=data.get('vlan'), cli_type=cli_type) else: if not output: output = show(dut, cli_type=cli_type) match = {"vlan": data.get('vlan')} if data.get("source_address"): match["source_address"] = data.get("source_address") if data.get("group_address"): match["group_address"] = data.get("group_address") entries = utils.filter_and_select(output, None, match) if not entries: st.log("No match found for - {}".format(data)) return False if data.get("outgoing_ports"): outgoing_ports_li = utils.make_list(data['outgoing_ports']) for each in outgoing_ports_li: if each not in entries[0]['outgoing_ports'].split(', '): st.log("Outgoing interface {} is not found in vlan {}". format(each, data.get('vlan'))) result = False if data.get('number_of_entries'): if not utils.filter_and_select( entries, None, { "vlan": data.get('vlan'), 'number_of_entries': str(data['number_of_entries']) }): st.log("number_of_entries {} for Vlan {} is not match".format( data['number_of_entries'], data.get('vlan'))) result = False previous_vlan = data.get('vlan') return result
def show(dut, *argv, **kwargs): """ To Perform IGMP Snooping show command calls. Author : Prudvi Mangadu ([email protected]) :param :dut: :param :vlan: :param :groups: :param :groups_vlan: :param :cli_type: default - klish :return: Usage: show(vars.D1, cli_type='klish') show(vars.D1, vlan=200, cli_type='klish') show(vars.D1, 'groups', cli_type='klish') show(vars.D1, groups_vlan=200, cli_type='klish') """ cli_type = st.get_ui_type(dut, **kwargs) if cli_type in ["click", "klish"]: cmd_prefix = ' all' if cli_type == 'click' else '' command = "show ip igmp snooping" if "groups" in argv: sub_cmd = "groups{}".format(cmd_prefix) elif "groups_vlan" in kwargs: sub_cmd = "groups vlan {}".format(kwargs['groups_vlan']) elif "vlan" in kwargs: sub_cmd = "vlan {}".format(kwargs['vlan']) else: sub_cmd = "{}".format(cmd_prefix) show_cmd = "{} {}".format(command, sub_cmd) if sub_cmd != '' else command output = st.show(dut, show_cmd, type=cli_type) elif cli_type in ["rest-put", "rest-patch"]: rest_urls = st.get_datastore(dut, "rest_urls") output = [] if "groups" in argv: url = rest_urls['igmp_snooping_show'] payload = get_rest( dut, rest_url=url )["output"]["openconfig-network-instance-deviation:interfaces"][ "interface"] for row in payload: if "staticgrps" in row: for each_item in row["staticgrps"][ "static-multicast-group"]: table_data = {} table_data["vlan"] = row["state"]["name"].strip("Vlan") table_data["group_address"] = each_item["state"][ "group"] table_data[ "source_address"] = "*" if each_item["state"][ "source-addr"] == "0.0.0.0" else each_item[ "state"]["source-addr"] table_data["outgoing_ports"] = ', '.join( each_item["state"]["outgoing-interface"]) table_data["number_of_entries"] = len( row["staticgrps"]["static-multicast-group"]) output.append(table_data) elif "groups_vlan" in kwargs: groups_vlanid = "Vlan{}".format(kwargs['groups_vlan']) url = rest_urls['igmp_snooping_show_vlan'].format(groups_vlanid) payload = get_rest( dut, rest_url=url )["output"]["openconfig-network-instance-deviation:interface"] for row in payload: if "staticgrps" in row: for each_item in row["staticgrps"][ "static-multicast-group"]: table_data = {} table_data["vlan"] = row["state"]["name"].strip("Vlan") table_data["group_address"] = each_item["state"][ "group"] table_data[ "source_address"] = "*" if each_item["state"][ "source-addr"] == "0.0.0.0" else each_item[ "state"]["source-addr"] table_data["outgoing_ports"] = ', '.join( each_item["state"]["outgoing-interface"]) table_data["number_of_entries"] = len( row["staticgrps"]["static-multicast-group"]) output.append(table_data) elif "vlan" in kwargs: vlanid = "Vlan{}".format(kwargs['vlan']) url = rest_urls['igmp_snooping_show_vlan'].format(vlanid) payload = get_rest( dut, rest_url=url )["output"]["openconfig-network-instance-deviation:interface"] for row in payload: table_data = { 'igmp_operation_mode': '', 'vlan': '', 'last_member_query_interval': '', 'query_max_response_time': '', 'querier': '', 'fast_leave': '', 'query_interval': '', 'mrouter_interface': '' } if "version" in row["state"]: table_data["igmp_operation_mode"] = "IGMPv{}".format( row["state"]["version"]) if "name" in row["state"]: table_data["vlan"] = row["state"]["name"].strip("Vlan") if "last-member-query-interval" in row["state"]: table_data["last_member_query_interval"] = row["state"][ "last-member-query-interval"] if "query-max-response-time" in row["state"]: table_data["query_max_response_time"] = row["state"][ "query-max-response-time"] if "querier" in row["state"]: table_data["querier"] = row["state"]["querier"] if "fast-leave" in row["state"]: table_data["fast_leave"] = row["state"]["fast-leave"] if "query-interval" in row["state"]: table_data["query_interval"] = row["state"][ "query-interval"] if "mrouter-interface" in row["state"]: table_data["mrouter_interface"] = ", ".join( row["state"]["mrouter-interface"]) output.append(table_data) else: url = rest_urls['igmp_snooping_show'] payload = get_rest( dut, rest_url=url )["output"]["openconfig-network-instance-deviation:interfaces"][ "interface"] for row in payload: table_data = { 'igmp_operation_mode': '', 'vlan': '', 'last_member_query_interval': '', 'query_max_response_time': '', 'querier': '', 'fast_leave': '', 'query_interval': '', 'mrouter_interface': '' } if "version" in row["state"]: table_data["igmp_operation_mode"] = "IGMPv{}".format( row["state"]["version"]) if "name" in row["state"]: table_data["vlan"] = row["state"]["name"].strip("Vlan") if "last-member-query-interval" in row["state"]: table_data["last_member_query_interval"] = row["state"][ "last-member-query-interval"] if "query-max-response-time" in row["state"]: table_data["query_max_response_time"] = row["state"][ "query-max-response-time"] if "querier" in row["state"]: table_data["querier"] = row["state"]["querier"] if "fast-leave" in row["state"]: table_data["fast_leave"] = row["state"]["fast-leave"] if "query-interval" in row["state"]: table_data["query_interval"] = row["state"][ "query-interval"] if "mrouter-interface" in row["state"]: table_data["mrouter_interface"] = ", ".join( row["state"]["mrouter-interface"]) output.append(table_data) else: st.log("Invalid cli_type provided: {}".format(cli_type)) return False return output
def breakout(dut, data, undo=False, brk_verify=True, cli_type="", skip_error=False): cli_type = st.get_ui_type(dut, cli_type=cli_type) platform_check=False cmds = [] cmds_1 =[] dut_type=basic.get_hwsku(dut) if dut_type: if "9716" in dut_type or "IX9" in dut_type: platform_check=True data_port = list(data) if cli_type == "klish": for x in range(0,len(data_port),2): res1 = get_interface_breakout_mode(dut, data_port[x], 'port') if res1: data_port[x] = 'port ' + res1[0]['port'] else: st.error('Invalid interface, cannot breakout') return False for index in range(0, len(data_port), 2): intf, opt = data_port[index].strip(), data_port[index+1].strip() if not opt.endswith("G"): opt = "{}G".format(opt) if intf in ['port 1/31','port 1/32'] and platform_check: if intf == 'port 1/31': intf1 = 'Ethernet240' else: intf1 = 'Ethernet248' st.log("The platform used is {}, if the ports are 1/31 (Intf: Ethernet240) or 1/32 (Intf: Ethernet248) it will be broken into 8x10G by default".format(dut_type)) if undo: cmds_1.append("config interface breakout {} 1x400G -y".format(intf1)) else: cmds_1.append("config interface breakout {} 8x10G -y".format(intf1)) else: if undo: cmds.append("no interface breakout {}".format(intf)) else: cmds.append("interface breakout {} mode {}".format(intf, opt)) elif cli_type == "click": for index in range(0, len(data), 2): intf, opt = data[index].strip(), data[index+1].strip() if not opt.endswith("G"): opt = "{}G".format(opt) if intf in ['Ethernet240','Ethernet248'] and platform_check: st.log("The platform used is {}, if the ports are Ethernet240 or Ethernet248 it will be broken into 8x10G by default".format(dut_type)) if undo: cmds.append("config interface breakout {} 1x400G -y -f".format(intf)) else: cmds.append("config interface breakout {} 8x10G -y -f".format(intf)) else: if undo: cmds.append("config interface breakout {} 1x100G -y -f".format(intf)) else: cmds.append("config interface breakout {} {} -y -f".format(intf, opt)) else: st.error("Unsupported CLI TYPE {}".format(cli_type)) return False if len(cmds_1) > 0: st.config(dut, cmds_1, type='click', skip_error_check=skip_error) try: st.config(dut, cmds, type=cli_type, skip_error_check=skip_error) except Exception as e: st.log(e) if brk_verify and cli_type == "klish" and not undo: for index in range(0, len(data), 2): intf, opt = data_port[index].strip(), data_port[index+1].strip() if not opt.endswith("G"): opt = "{}G".format(opt) intf = "Ethernet".join(intf.split("Ethernet")) if retry_api(verify_dpb_status,dut,interface=intf,status='Completed',breakout_mode=opt,retry_count=12, delay=5): st.log("Breakout of {} to speed {} is successful".format(intf,opt)) else: st.error("Breakout is not successful for {} of speed {}, even after 60 seconds".format(intf,opt)) return False return True
def verify_crm_resources(dut, family, availablecount=None, usedcount=None, tableid=None, bindpoint=None, stage=None, cli_type=""): """ To verify the CRM Resources parameters Author : Prudvi Mangadu ([email protected]) :param dut: :param family: :param availablecount: :param usedcount: :param tableid: :param bindpoint: :param stage: :param cli_type: click or klish designation: :return: """ cli_type = st.get_ui_type(dut, cli_type=cli_type) if family == 'acl_entry': family = 'acl_table_entry' elif family == 'acl_counter': family = 'acl_table_counter' elif family == 'acl_table_stats': family = 'acl_table' output = get_crm_resources(dut, family, cli_type) # Handling few crm family cli commands for verify if family == "fdb": family = 'fdb_entry' if family == "dnat": family = 'dnat_entry' if family == "ipmc": family = 'ipmc_entry' if family == "snat": family = 'snat_entry' if family == "acl_group_entry": family = 'acl_entry' if family == "acl_group_counter": family = 'acl_counter' if family == "acl_table_counter": family = 'acl_counter' if family == "acl_table_entry": family = 'acl_entry' if family == 'nexthop_group_object': family = 'nexthop_group' entries = filter_and_select(output, None, {"resourcename": family}) if not entries: st.error( "No Entry found for given family in the table - {}".format(family)) return False if availablecount and not filter_and_select( entries, None, { "resourcename": family, "availablecount": availablecount }): st.error("Available and Provided availablecount is not match.") return False if usedcount and not filter_and_select(entries, None, { "resourcename": family, 'usedcount': usedcount }): st.error("Available and Provided usedcount is not match.") return False if tableid and not filter_and_select(entries, None, { "resourcename": family, "tableid": tableid }): st.error("Available and Provided tableid is not match.") return False if bindpoint and not filter_and_select(entries, None, { "resourcename": family, "bindpoint": bindpoint }): st.error("Available and Provided bindpoint is not match.") return False if stage and not filter_and_select(entries, None, { "resourcename": family, "stage": stage }): st.error("Available and Provided stage is not match.") return False return True
def dyn_port_breakout(dut, **kwargs): """ Author:[email protected] :param dut: :param portlist: :param speed : 1x40G 2x100G 2x50G 4x100G 4x25G 4x10G: :param cli_type: :return: :rtype: :Usuage : port.dyn_port_breakout(dut7,portlist=["Ethernet0","Ethernet4"],speed="4x10",config="yes",skip_error="yes") port.dyn_port_breakout(dut7,portlist=["Ethernet0","Ethernet4"],config="no") """ config = kwargs.get('config','yes') cli_type = kwargs.pop('cli_type',st.get_ui_type(dut,**kwargs)) if 'portlist' not in kwargs: st.error("Mandatory arg portlist is not present") return False elif type(kwargs['portlist']) is not list: kwargs['portlist'] = [kwargs['portlist']] if 'speed' in kwargs: speed = kwargs['speed'] skip_error = kwargs.pop('skip_error', False) data_port = kwargs['portlist'] for x in range(len(data_port)): res1 = get_interface_breakout_mode(dut, data_port[x], 'port') if res1: data_port[x] = 'port ' + res1[0]['port'] else: st.error('Invalid interface, cannot breakout') return False my_cmd = '' if cli_type == 'klish': if config.lower() == "yes": if 'speed' not in kwargs: st.error(':Speed parameter is required to breakout a port') return False else: for port in data_port: my_cmd += 'interface breakout {} mode {}G\n'.format(port,speed) else: for port in data_port: my_cmd += 'no interface breakout {}\n'.format(port) st.config(dut, my_cmd, type='klish',skip_error_check=skip_error) elif cli_type in ['rest-patch', 'rest-put']: rest_urls = st.get_datastore(dut, 'rest_urls') ocdata = {} if config.lower() == "yes": if 'speed' not in kwargs: st.error(':Speed parameter is required to breakout a port') return False else: for port in data_port: port=port.replace('/','%2F') port = port.strip('port ') base_url = rest_urls['config_dpb'].format(port) speed= speed.split('x') ocdata['openconfig-platform-port:config'] = {"num-channels" : int(speed[0]), "channel-speed" : "SPEED_{}GB".format(int(speed[1]))} response = config_rest(dut,http_method=cli_type, rest_url=base_url, json_data=ocdata) if not response: return False else: for port in data_port: port=port.replace('/','%2F') port = port.strip('port ') base_url = rest_urls['config_dpb'].format(port) response = delete_rest(dut, rest_url=base_url) if not response: return False
def check_bgp_session(dut, nbr_list=[], state_list=[], vrf_name='default', **kwargs): """ Author:[email protected] :param nbr_list: :type list of BGPneighbors :param state_list: :type list of states :param dut: :type dut: :return: :rtype: """ ret_val = True cli_type = kwargs.pop('cli_type', st.get_ui_type(dut, **kwargs)) # if cli_type in ['rest-patch', 'rest-put']: cli_type = 'klish' output = [] if cli_type == 'click': if vrf_name == 'default': output = st.show(dut, 'show ip bgp summary', type='vtysh') else: output = st.show(dut, 'show ip bgp vrf {} summary'.format(vrf_name), type='vtysh') elif cli_type == 'klish': family = kwargs.pop('family', 'ipv4') if vrf_name == 'default': output = st.show(dut, 'show bgp {} unicast summary'.format(family), type='klish') else: output = st.show(dut, 'show bgp {} unicast vrf {} summary'.format( family, vrf_name), type='klish') elif cli_type in ["rest-put", "rest-patch"]: family = kwargs.pop('family', 'ipv4') if family == "ipv4": output = show_bgp_ipv4_summary_vtysh(dut, vrf_name, cli_type=cli_type) else: output = show_bgp_ipv6_summary_vtysh(dut, vrf_name, cli_type=cli_type) if len(output) != 0: for nbr, state in zip(nbr_list, state_list): match = {'neighbor': nbr} entry = filter_and_select(output, None, match) if not bool(entry): st.log("BGP Neighbor entry {} is not found".format(nbr)) ret_val = False for entries in entry: if state == 'Established': if entries['state'].isdigit( ) or entries['state'] == "ESTABLISHED": st.log( "BGP Neighbor {} in Established state".format(nbr)) else: st.error( "BGP Neighbor {} state check Failed. Expected:{} Actual :{} " .format(nbr, state, entries['state'])) ret_val = False else: if str(state).upper() == str(entries['state']).upper(): st.log( "BGP Neighbor {} check passed. Expected : {} Actual {}" .format(nbr, state, entries['state'])) else: st.error( "BGP Neighbor {} state check Failed. Expected:{} Actual :{} " .format(nbr, state, entries['state'])) ret_val = False else: st.error("Output is empty") ret_val = False return ret_val
def global_vars_and_constants_init(): global eh_data, vars eh_data = SpyTestDict() vars = st.ensure_min_topology('D1D2:1', 'D1T1:2') eh_data.platform = bsapi.get_hwsku(vars.D1).lower() hw_constants = st.get_datastore(vars.D1, "constants", eh_data.platform) if not hw_constants: hw_constants = st.get_datastore(vars.D1, "constants") # Falgs eh_data.debug = True eh_data.clear_logs = True eh_data.thread_mode = True eh_data.dut_list = [vars.D1, vars.D2] eh_data.ping_delay = 5 eh_data.ping_retry = 1 eh_data.error_route_table = "ERROR_ROUTE_TABLE" eh_data.error_neigh_table = "ERROR_NEIGH_TABLE" eh_data.swss_rc_success = "SWSS_RC_SUCCESS" eh_data.swss_rc_exists = "SWSS_RC_EXISTS" eh_data.swss_rc_not_found = "SWSS_RC_NOT_FOUND" eh_data.swss_rc_table_full = "SWSS_RC_TABLE_FULL" eh_data.log_str_swss = "swss#orchagent:" eh_data.log_str_bgp = "bgp#fpmsyncd:" eh_data.route_not_install_flag = '#' # Global vars eh_data.ipv4_addr = "10.1.1.1" eh_data.ipv4_nbr = "10.1.1.2" eh_data.ipv4_mask = "255.255.255.0" eh_data.ipv4_mask_len = '24' eh_data.ipv6_addr = "2001::1" eh_data.ipv6_nbr = "2001::2" eh_data.ipv6_mask_len = '64' eh_data.local_asn = '65400' eh_data.remote_asn = '65007' eh_data.tg_remote_asn = '65009' eh_data.ipv4_route = "12.12.12.0" eh_data.ipv4_route2 = "13.13.13.0" eh_data.ipv6_route = "0600:0000:0000:0000:0000:0000:0000:0000" eh_data.ipv6_route2 = "0700:0000:0000:0000:0000:0000:0000:0000" eh_data.ipv6_route_mask = "600::0/64" eh_data.ipv6_route2_mask = "700::0/64" eh_data.ipv6_route_sf = "600::" eh_data.ipv6_route2_sf = "700::" eh_data.egr_intf = '100002' eh_data.vrf = '0' eh_data.loopback4_1 = "66.66.66.66" eh_data.loopback4_2 = "77.77.77.77" eh_data.loopback6_1 = "6666::6666" eh_data.loopback6_2 = "7777::7777" eh_data.af_ipv4 = "ipv4" eh_data.af_ipv6 = "ipv6" eh_data.shell_sonic = "sonic" eh_data.shell_vtysh = "vtysh" eh_data.route_map_name = 'error_handling_route_map' eh_data.peer_gp_namev4 = 'error_handlingv4' eh_data.tg_peer_gp_namev4 = 'tg_error_handlingv4' eh_data.peer_gp_namev6 = 'error_handlingv6' eh_data.tg_peer_gp_namev6 = 'tg_error_handlingv6' eh_data.ipv4_nbr2 = "10.1.1.3" eh_data.ipv6_nbr2 = "2001::3" eh_data.ipv4_nbr2_mac = "00:00:00:00:00:01" eh_data.ipv6_nbr2_mac = "00:00:00:00:00:02" eh_data.ipv4_nbr3 = "10.1.1.4" eh_data.ipv6_nbr3 = "2001::4" eh_data.ipv4_nbr3_mac = "00:00:00:00:00:03" eh_data.ipv6_nbr3_mac = "00:00:00:00:00:04" # TG vars eh_data.tg1_ipv4_addr = "20.1.1.1" eh_data.tg1_ipv4_nbr = "20.1.1.2" eh_data.tg1_ipv4_mask = "255.255.255.0" eh_data.tg1_ipv4_mask_len = '24' eh_data.tg1_ipv6_addr = "3001::1" eh_data.tg1_ipv6_nbr = "3001::2" eh_data.tg1_ipv6_mask_len = '64' # Constants eh_data.ipv4_max_routes = int( hw_constants['MAX_IPV4_ROUTES_FOR_ERROR_HANDLING']) st.log("MAX_IPV4_ROUTES_FOR_ERROR_HANDLING: {}".format( eh_data.ipv4_max_routes)) eh_data.ipv6_max_routes = int( hw_constants['MAX_IPV6_ROUTES_FOR_ERROR_HANDLING']) st.log("MAX_IPV6_ROUTES_FOR_ERROR_HANDLING: {}".format( eh_data.ipv6_max_routes)) eh_data.max_route_install_wait_time = 120 eh_data.bcmcmd_timeout = 600 eh_data.cli_type = st.get_ui_type(vars.D1)
def verify_bgp_neighbor(dut, **kwargs): """ Author:[email protected] :param neighbor_address: :type bgp-neighbor-address (list or string) :param remoteasn: :type bgp-remote-as :param localasn: :type bgp-local-as :param dut: :type dut: :return: :rtype: usage: bgp.verify_bgp_neighbor(dut1,neighborip="10.1.1.12",remoteasn='12',localasn='10') Example output in dictionary forms [{'neighborip': '10.1.1.12', 'peergroup': 'ava', 'updatercvd': '0', 'inqdepth': '0', 'opensent': '31', 'bgpversion': '4', 'bfdrxintr': '300', 'capabilityrcvd': '0', 'lastwrite': '00:00:40', 'keepalivesent': '7351', 'keepalive': '60', 'outqdepth': '0', 'uptime': '5d00h25m', 'lastread': '00:00:27', 'bfdmultiplier': '3', 'bfdstatus': 'Down', 'state': 'Established,', 'routerefreshrcvd': '0', 'remrouterid': '23.23.23.23', 'bfdtxintr': '300', 'grcapability': 'advertised', 'bfdlastupdate': '5:00:37:18', 'routerefreshsent': '0', 'senttotal': '7404', 'notificationrcvd': '2', 'bfdtype': 'single', 'rcvdtotal': '8601', 'notificationsent': '22', 'remoteasn': '12', 'openrcvd': '14', 'localasn': '10', 'keepalivercvd': '8585', 'asbyte': '4', 'localrouterid': '1.1.1.1', 'capablitysent': '0', 'updatesent': '0', 'holdtime': '180'}] """ cli_type = kwargs.pop('cli_type', st.get_ui_type(dut, **kwargs)) cli_type = 'vtysh' if cli_type in ['vtysh', 'click'] else cli_type result = False st.log("verify show bgp neighbor") if 'neighborip' not in kwargs: st.error("Mandatory parameter neighborip is not found") return result if 'vrf' in kwargs: vrf = kwargs['vrf'] del kwargs['vrf'] else: vrf = 'default-vrf' family = kwargs.pop('family', 'ipv4') #Converting all kwargs to list type to handle single or multiple BGP neighbors for key in kwargs: if type(kwargs[key]) is list: kwargs[key] = list(kwargs[key]) else: kwargs[key] = [kwargs[key]] if vrf != 'default-vrf': if cli_type == 'vtysh': if len(kwargs['neighborip']) == 1: cmd = "show bgp vrf {} neighbors {}".format( vrf, kwargs['neighborip'][0]) else: cmd = "show bgp vrf {} neighbors ".format(vrf) elif cli_type == 'klish': if len(kwargs['neighborip']) == 1: cmd = "show bgp {} unicast vrf {} neighbors {}".format( family, vrf, kwargs['neighborip'][0]) else: cmd = "show bgp {} unicast vrf {} neighbors".format( family, vrf) elif cli_type in ["rest-patch", "rest-put"]: if family == "ipv4": if len(kwargs['neighborip']) == 1: output = show_bgp_ipv4_neighbor_vtysh( dut, neighbor_ip=kwargs['neighborip'][0], vrf=vrf, cli_type=cli_type) else: output = show_bgp_ipv4_neighbor_vtysh(dut, vrf=vrf, cli_type=cli_type) else: if len(kwargs['neighborip']) == 1: output = show_bgp_ipv6_neighbor_vtysh( dut, neighbor_ip=kwargs['neighborip'][0], vrf=vrf, cli_type=cli_type) else: output = show_bgp_ipv6_neighbor_vtysh(dut, vrf=vrf, cli_type=cli_type) else: if cli_type == 'vtysh': if len(kwargs['neighborip']) == 1: cmd = "show bgp neighbors {}".format(kwargs['neighborip'][0]) else: cmd = "show bgp neighbors" elif cli_type == 'klish': if len(kwargs['neighborip']) == 1: cmd = "show bgp {} unicast neighbors {}".format( family, kwargs['neighborip'][0]) else: cmd = "show bgp {} unicast neighbors".format(family) elif cli_type in ["rest-patch", "rest-put"]: if family == "ipv4": if len(kwargs['neighborip']) == 1: output = show_bgp_ipv4_neighbor_vtysh( dut, neighbor_ip=kwargs['neighborip'][0], vrf="default", cli_type=cli_type) else: output = show_bgp_ipv4_neighbor_vtysh(dut, vrf=vrf, cli_type=cli_type) else: if len(kwargs['neighborip']) == 1: output = show_bgp_ipv6_neighbor_vtysh( dut, neighbor_ip=kwargs['neighborip'][0], vrf="default", cli_type=cli_type) else: output = show_bgp_ipv6_neighbor_vtysh(dut, vrf=vrf, cli_type=cli_type) if cli_type not in ["rest-patch", "rest-put"]: output = st.show(dut, cmd, type=cli_type) #Get the index of peer from list of parsed output for i in range(len(kwargs['neighborip'])): nbr_index = None st.log("Validation for BGP Neighbor : %s" % kwargs['neighborip'][i]) for peer_info in output: if peer_info['neighborip'] == kwargs['neighborip'][i]: nbr_index = output.index(peer_info) if nbr_index is not None: #Iterate through the user parameters for k in kwargs.keys(): if k != 'neighborip': if output[nbr_index][k] == kwargs[k][i]: st.log( 'Match Found for %s :: Expected: %s Actual : %s' % (k, kwargs[k][i], output[nbr_index][k])) result = True else: if kwargs[k][i] in [ 'BFD down received', 'Interface down', 'Hold Timer Expired' ] and 'Waiting for NHT' in output[nbr_index][k]: st.log( 'Match checking for Waiting for NHT and Found for %s :: Expected: %s Actual : %s' % (k, output[nbr_index][k], output[nbr_index][k])) result = True else: st.error( 'Match Not Found for %s :: Expected: %s Actual : %s' % (k, kwargs[k][i], output[nbr_index][k])) return False else: st.error(" BGP neighbor %s not found in output" % kwargs['neighborip'][i]) return False return result
def create_session(dut, **kwargs): cli_type = st.get_ui_type(dut, **kwargs) """ API to configure mirror session for both erspan, span and legacy configuration support Author: Chaitanya Vella ([email protected]) :param dut: :param kwargs: session_name : Name of the session (Mandatory) mirror_type: erspan or span. (Not mamdatory, as to support Mirror configuration in ARLO) destination_ifname: destination interface name in case of span source_ifname: source interface name in case of span rx_tx: rx/tx in case of span src_ip: source ip address in case of erspan dst_ip: destination ip address in case of erspan dscp: DSCP in case of erspan ttl: TTL in case of erspan queue: QUEUE in case of erspan gre_type: GRE_TYPE in case of erspan :return: """ kwargs["mirror_type"] = kwargs.get("mirror_type", "erspan") skip_err_check = kwargs.get("skip_err_check", False) if 'session_name' not in kwargs: st.error("Session name not provided ...") return False if kwargs.get("mirror_type") not in ["erspan", "span"]: st.log("Unsupported mirror type ..") return False if cli_type == "click": command = "config mirror_session add " if st.is_feature_supported("span-mirror-session", dut): command += " {}".format(kwargs["mirror_type"]) command += " {}".format(kwargs["session_name"]) if "mirror_type" in kwargs and kwargs["mirror_type"] == "span": if "destination_ifname" in kwargs: command += " {}".format(kwargs["destination_ifname"]) if "source_ifname" in kwargs: command += " {}".format(kwargs["source_ifname"]) if "rx_tx" in kwargs: command += " {}".format(kwargs["rx_tx"]) else: if 'src_ip' not in kwargs: st.error("Source IP not provided ...") return False command += " {}".format(kwargs["src_ip"]) if 'dst_ip' not in kwargs: st.error("Destination IP not provided ...") return False command += " {}".format(kwargs["dst_ip"]) if 'dscp' not in kwargs: st.error("dscp not provided ...") return False command += " {}".format(kwargs["dscp"]) if 'ttl' in kwargs: command += " {}".format(kwargs["ttl"]) if 'gre_type' not in kwargs: st.error("gre_type not provided ...") return False gre_type = kwargs["gre_type"] command += " {}".format(gre_type) if 'queue' in kwargs: command += " {}".format(kwargs["queue"]) if kwargs.get("src_port"): command += " {}".format(kwargs.get("src_port")) if kwargs.get("direction"): command += " {}".format(kwargs.get("direction")) output = st.config(dut, command, type=cli_type, skip_error_check=skip_err_check) output = remove_last_line_from_string(output) if skip_err_check: if "Failed" or "Error" in output: st.debug("Failed to create/delete mirror session") return False if ("mirror_type" in kwargs and kwargs["mirror_type"] != "span") or ("mirror_type" not in kwargs): session_data = verify_session(dut, session_name=kwargs["session_name"], src_ip=kwargs["src_ip"], dst_ip=kwargs["dst_ip"], dscp=kwargs["dscp"], ttl=kwargs["ttl"], gre_type=gre_type, queue=kwargs["queue"]) return False if not session_data else True return True elif cli_type == "klish": commands = list() cmd_mirror_session = "mirror-session {}".format(kwargs["session_name"]) commands.append(cmd_mirror_session) if kwargs.get("mirror_type") == "span": if not kwargs.get("destination_ifname"): st.log("Please provide destination interface") return False command = "destination {}".format(kwargs.get("destination_ifname")) if kwargs.get("source_ifname"): command = "{} source {}".format(command, kwargs.get("source_ifname")) if kwargs.get("rx_tx"): command = "{} direction {}".format(command, kwargs.get("rx_tx")) else: command = "destination erspan" gre_type = kwargs["gre_type"] if kwargs.get("src_ip"): command += " src-ip {}".format(kwargs.get("src_ip")) if kwargs.get("dst_ip"): command += " dst-ip {}".format(kwargs.get("dst_ip")) if kwargs.get("gre_type"): command += " gre {}".format(gre_type) if kwargs.get("dscp"): command += " dscp {}".format(kwargs.get("dscp")) if kwargs.get("ttl"): command += " ttl {}".format(kwargs.get("ttl")) if kwargs.get("queue"): command += " queue {}".format(kwargs.get("queue")) if kwargs.get("src_port"): command += " source {}".format(kwargs.get("src_port")) if kwargs.get("direction"): command += " direction {}".format(kwargs.get("direction")) commands.append(command) commands.append("exit") st.log("COMMAND : {}".format(commands)) output = st.config(dut, commands, type=cli_type, skip_error_check=skip_err_check) if skip_err_check: if "Error" in output: st.debug("Failed to create mirror session") return False if ("mirror_type" in kwargs and kwargs["mirror_type"] != "span") or ("mirror_type" not in kwargs): session_data = verify_session(dut, session_name=kwargs["session_name"], src_ip=kwargs["src_ip"], dst_ip=kwargs["dst_ip"], dscp=kwargs["dscp"], ttl=kwargs["ttl"], gre_type=gre_type, queue=kwargs["queue"]) if not session_data: return False if kwargs.get("no_form_session_name"): command = "no mirror-session {}".format(kwargs["session_name"]) output = st.config(dut, command, type=cli_type, skip_error_check=skip_err_check) output = remove_last_line_from_string(output) if skip_err_check: if "Error" in output: st.debug("Failed to delete mirror session") return False return True elif cli_type in ["rest-put", "rest-patch"]: rest_urls = st.get_datastore(dut, "rest_urls") mirror_type = kwargs.get("mirror_type") url = rest_urls['config_mirror_session'].format(kwargs["session_name"]) data = {} if mirror_type == "span": if kwargs.get("source_ifname"): data["src-port"] = str(kwargs.get("source_ifname")) if kwargs.get("destination_ifname"): data["dst-port"] = str(kwargs.get("destination_ifname")) if kwargs.get("rx_tx"): data["direction"] = str(kwargs.get("rx_tx").upper()) else: if kwargs.get("src_ip"): data["src-ip"] = str(kwargs.get("src_ip")) if kwargs.get("dst_ip"): data["dst-ip"] = str(kwargs.get("dst_ip")) if kwargs.get("dscp"): data["dscp"] = int(kwargs.get("dscp")) if kwargs.get("gre_type"): data["gre-type"] = str(kwargs.get("gre_type")) if kwargs.get("ttl"): data["ttl"] = int(kwargs.get("ttl")) if 'queue' in kwargs: data["queue"] = int(kwargs.get("queue")) if kwargs.get("src_port"): data["src-port"] = str(kwargs.get("src_port")) if kwargs.get("direction"): data["direction"] = str(kwargs.get("direction").upper()) config_data = {"openconfig-mirror-ext:config": data} if not config_rest( dut, http_method=cli_type, rest_url=url, json_data=config_data): return False else: st.log("Unsupported cli") return False return True
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
def show_session_all(dut, session_name=None, cli_type=""): cli_type = st.get_ui_type(dut, cli_type=cli_type) """ API to show the mirror session output for both erspan and span Author: Chaitanya Vella ([email protected]) :param dut: :param session_name: :return: {'span': [{u'source_port': 'Ethernet4', u'direction': 'INGRESS', u'span_name': 'portmir0', u'destination_port': 'Ethernet0', u'span_status': 'active'}, {u'source_port': 'Ethernet84', u'direction': 'INGRESS', u'span_name': 'portmir3', u'destination_port': 'Ethernet5', u'span_status': 'active'}], 'erspan': [{u'status': 'active', u'queue': '', u'name': 'everflow0', u'dscp': '78', u'src_ip': '10.1.0.32', u'ttl': '', u'dst_ip': '10.0.0.7', u'gre_type': '0x866'}, {u'status': 'active', u'queue': '', u'name': 'everflow0', u'dscp': '64', u'src_ip': '10.1.0.33', u'ttl': '', u'dst_ip': '10.0.0.7', u'gre_type': '0x866'}]} """ result = dict() erspan_cols = [ "name", "status", "src_ip", "dst_ip", "gre_type", "dscp", "ttl", "queue", "policer", "erspan_src_port", "erspan_direction" ] span_cols = [ "span_name", "span_status", "destination_port", "source_port", "direction" ] if cli_type == "click": command = "show mirror_session" if session_name: command += " {}".format(session_name) output = st.show(dut, command, type=cli_type) elif cli_type == "klish": command = "show mirror-session" if session_name: command += " {}".format(session_name) output = st.show(dut, command, type=cli_type) elif cli_type in ["rest-put", "rest-patch"]: output = [] rest_urls = st.get_datastore(dut, "rest_urls") if not session_name: url = rest_urls['get_session_all'] rest_get_output = get_rest(dut, rest_url=url) if rest_get_output and rest_get_output.get( "output") and rest_status(rest_get_output["status"]): actual_data = rest_get_output['output'][ 'openconfig-mirror-ext:mirror']['sessions']['session'] for i in actual_data: process_data = i['state'] rest_out_keys = process_data.keys() if 'dscp' in rest_out_keys: temp1 = {} temp1['name'] = i['name'] temp1['erspan_direction'] = i['state'][ 'direction'] if 'direction' in i['state'] else '' temp1['erspan_src_port'] = i['state'][ 'src-port'] if 'src-port' in i['state'] else '' temp1['dscp'] = i['state']['dscp'] if 'dscp' in i[ 'state'] else '' temp1['dst_ip'] = str( i['state'] ['dst-ip']) if 'dst-ip' in i['state'] else '' temp1['queue'] = str(i['state']['queue'] ) if 'queue' in i['state'] else '' temp1['src_ip'] = i['state'][ 'src-ip'] if 'src-ip' in i['state'] else '' temp1['gre_type'] = i['state'][ 'gre-type'] if 'gre-type' in i['state'] else '' temp1['ttl'] = str( i['state']['ttl']) if 'ttl' in i['state'] else '' temp1['span_name'] = temp1['direction'] = temp1[ 'source_port'] = temp1['destination_port'] = '' url = rest_urls['get_mirror_status'].format(i['name']) status_out = get_rest(dut, rest_url=url) temp1['status'] = status_out['output'][ 'openconfig-mirror-ext:status'] output.append(temp1) else: temp2 = {} temp2['span_name'] = i['name'] temp2['direction'] = i['state'][ 'direction'] if 'direction' in i['state'] else '' temp2['source_port'] = i['state'][ 'src-port'] if 'src-port' in i['state'] else '' temp2['destination_port'] = i['state'][ 'dst-port'] if 'dst-port' in i['state'] else '' temp2['name'] = temp2['erspan_direction'] = temp2['erspan_src_port'] = temp2['dscp'] = temp2[ 'dst_ip'] = temp2['queue'] \ = temp2['src_ip'] = temp2['gre_type'] = temp2['ttl'] = '' url = rest_urls['get_mirror_status'].format(i['name']) status_out = get_rest(dut, rest_url=url) temp2['span_status'] = status_out['output'][ 'openconfig-mirror-ext:status'] output.append(temp2) if session_name: url = rest_urls['get_session_session_name'].format(session_name) rest_get_output = get_rest(dut, rest_url=url) if rest_get_output and rest_get_output.get( "output") and rest_status(rest_get_output["status"]): actual_data = rest_get_output['output'][ 'openconfig-mirror-ext:session'][0] temp = {} process_data = actual_data['state'] rest_out_keys = process_data.keys() st.log("getting mirror status") url = rest_urls['get_mirror_status'].format(session_name) status_out = get_rest(dut, rest_url=url) if 'dscp' in rest_out_keys: if 'dscp' in erspan_cols: temp['name'] = actual_data['name'] temp['erspan_direction'] = actual_data['state'][ 'direction'] if 'direction' in actual_data[ 'state'] else '' temp['erspan_src_port'] = actual_data['state'][ 'src-port'] if 'src-port' in actual_data[ 'state'] else '' temp['dscp'] = str( actual_data['state'] ['dscp']) if 'dscp' in actual_data['state'] else '' temp['dst_ip'] = actual_data['state'][ 'dst-ip'] if 'dst-ip' in actual_data[ 'state'] else '' temp['queue'] = str( actual_data['state']['queue'] ) if 'queue' in actual_data['state'] else '' temp['src_ip'] = actual_data['state'][ 'src-ip'] if 'src-ip' in actual_data[ 'state'] else '' temp['gre_type'] = actual_data['state'][ 'gre-type'] if 'gre-type' in actual_data[ 'state'] else '' temp['ttl'] = str( actual_data['state'] ['ttl']) if 'ttl' in actual_data['state'] else '' temp['span_name'] = temp['direction'] = temp[ 'source_port'] = temp['destination_port'] = '' temp['status'] = status_out['output'][ 'openconfig-mirror-ext:status'] output.append(temp) else: temp['span_name'] = actual_data['name'] temp['direction'] = actual_data['state'][ 'direction'] if 'direction' in actual_data[ 'state'] else '' temp['source_port'] = actual_data['state'][ 'src-port'] if 'src-port' in actual_data[ 'state'] else '' temp['destination_port'] = actual_data['state'][ 'dst-port'] if 'dst-port' in actual_data[ 'state'] else '' temp['name']=temp['erspan_direction']=temp['erspan_src_port']=temp['dscp']=temp['dst_ip']=temp['queue']\ = temp['src_ip'] = temp['gre_type']=temp['ttl'] = '' temp['span_status'] = status_out['output'][ 'openconfig-mirror-ext:status'] output.append(temp) if output: result["erspan"] = list() result["span"] = list() for data in output: erspan_dict = dict() span_dict = dict() for key, value in data.items(): if data["name"] and key in erspan_cols: erspan_dict[key] = value if data["span_name"] and key in span_cols: span_dict[key] = value if span_dict: result["span"].append(span_dict) if erspan_dict: result["erspan"].append(erspan_dict) return result
def pre_config_ztp(): global vars global ssh_conn_obj global inband_ssh_conn_obj global ssh_conn_obj_oob_v6 global ssh_conn_obj_inb_v6 vars = st.get_testbed_vars() # DHCPV4 out of band params ztp_params.dhcp.ip = mutils.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "ip") ztp_params.dhcp.username = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "outofband", "username") ztp_params.dhcp.password = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "outofband", "password") ztp_params.dhcp.config_file = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "outofband", "config_file") ztp_params.dhcp.static_ip = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "outofband", "static_ip") ztp_params.oob_port = mutils.ensure_service_params(vars.D1, "ztp", "dhcp", "outofband", "interface") # DHCPV4 in band params ztp_params.dhcp.inband_ip = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "inband", "ip") ztp_params.dhcp.inband_username = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "inband", "username") ztp_params.dhcp.inband_password = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "inband", "password") ztp_params.config_path = mutils.ensure_service_params( vars.D1, "ztp", "config_path") ztp_params.firmware_path = mutils.ensure_service_params( vars.D1, "ztp", "firmware_path") ztp_params.home_path = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "outofband", "home_path") ztp_params.build_file_name = mutils.ensure_service_params( vars.D1, "ztp", "build_file_name") ztp_params.uninstall_image = mutils.ensure_service_params( vars.D1, "ztp", "uninstall_image") ztp_params.dut_path = mutils.ensure_service_params(vars.D1, "ztp", "dut_path") ztp_params.ztp_cfg_file_name = mutils.ensure_service_params( vars.D1, "ztp", "ztp_cfg_file_name") ztp_params.provision_script_path = mutils.ensure_service_params( vars.D1, "ztp", "provision_script_path") ztp_params.docker_path = mutils.ensure_service_params( vars.D1, "ztp", "docker_path") ztp_params.docker_image = mutils.ensure_service_params( vars.D1, "ztp", "docker_image") ztp_params.docker_component_name = mutils.ensure_service_params( vars.D1, "ztp", "docker_component_name") ztp_params.inband_port = mutils.ensure_service_params( vars.D1, "ztp", "dhcp", "inband", "interface") ztp_params.minigraph_file = mutils.ensure_service_params( vars.D1, "ztp", "minigraph_file") ztp_params.xml_path = mutils.ensure_service_params(vars.D1, "ztp", "xml_path") # DHCPV6 out of band params ztp_params.dhcp6.ip = mutils.ensure_service_params(vars.D1, "ztp", "dhcpv6", "outofband", "ip") ztp_params.dhcp6.username = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "outofband", "username") ztp_params.dhcp6.password = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "outofband", "password") ztp_params.dhcp6.oob_port = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "outofband", "interface") ztp_params.dhcp6.oob_static_ip = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "outofband", "static_ip") # DHCPV6 IN band params ztp_params.dhcp6.inband_ip = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "inband", "ip") ztp_params.dhcp6.inband_username = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "inband", "username") ztp_params.dhcp6.inband_password = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "inband", "password") ztp_params.dhcp6.inband_static_ip = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "inband", "static_ip") ztp_params.dhcp6.inband_port = mutils.ensure_service_params( vars.D1, "ztp", "dhcpv6", "inband", "interface") ztp_params.cli_type = st.get_ui_type(vars.D1) st.log("Clearing V4/V6 lease database from DUT ...") basic_obj.delete_directory_contents(vars.D1, config_params.lease_db_path) st.log("####### Connecting to DHCPV4 server -- OUT OF BAND ...###########") ssh_conn_obj = con_obj.connect_to_device(ztp_params.dhcp.ip, ztp_params.dhcp.username, ztp_params.dhcp.password) if not ssh_conn_obj: st.error("SSH connetion object not found.") reset_module_config() st.report_env_fail("ssh_connection_failed", ztp_params.dhcp.ip) inband_ssh_conn_obj = con_obj.connect_to_device( ztp_params.dhcp.inband_ip, ztp_params.dhcp.inband_username, ztp_params.dhcp.inband_password) if not inband_ssh_conn_obj: st.log("SSH connection to inband DHCP server is not successfull") # st.report_env_fail("ssh_connection_failed", ztp_params.dhcp.inband_ip) st.log( "############Connecting to DHCPV6 server -- OUT OF BAND ...#########") ssh_conn_obj_oob_v6 = con_obj.connect_to_device(ztp_params.dhcp6.ip, ztp_params.dhcp6.username, ztp_params.dhcp6.password) if not ssh_conn_obj_oob_v6: st.error( "SSH connection object not found for DHCPV6 server OUT OF BAND.") ssh_conn_obj_inb_v6 = con_obj.connect_to_device( ztp_params.dhcp6.inband_ip, ztp_params.dhcp6.inband_username, ztp_params.dhcp6.inband_password) if not ssh_conn_obj_inb_v6: st.error( "SSH connection object not found for DHCPV4 server OUT OF BAND.") st.log("Stopping V4/V6 services on unwanted servers .. ") v6_connection_objs = [ssh_conn_obj_inb_v6, ssh_conn_obj_oob_v6] for connection_obj in v6_connection_objs: if connection_obj: basic_obj.service_operations(connection_obj, config_params.dhcp6_service_name, "stop", "server") if ztp_obj.verify_dhcpd_service_status(connection_obj, config_params.dhcpd6_pid): st.log("{} service is running which is not expected".format( config_params.dhcp6_service_name)) reset_module_config() st.report_fail("service_running_not_expected", config_params.dhcp6_service_name) basic_obj.service_operations(ssh_conn_obj, config_params.dhcp_service_name, "restart", "server") if not ztp_obj.verify_dhcpd_service_status(ssh_conn_obj, config_params.dhcpd_pid): st.log("{} service is not running ".format( config_params.dhcp_service_name)) reset_module_config() st.report_fail("service_running_not_expected", config_params.dhcp_service_name) st.wait(5) if not basic_obj.check_interface_status(vars.D1, ztp_params.oob_port, "up"): basic_obj.ifconfig_operation(vars.D1, ztp_params.oob_port, "up") intf_obj.enable_dhcp_on_interface(vars.D1, ztp_params.oob_port) if not ip_obj.ping(vars.D1, ztp_params.dhcp.static_ip): st.log( "Pinging to DHCP server failed from DUT, issue either with DUT or server" ) reset_module_config() st.report_fail("ping_fail", ztp_params.dhcp.static_ip) ztp_cfg = { "admin-mode": True, "restart-ztp-interval": 30, "feat-console-logging": feat_logging_console } ztp_obj.config_ztp_backdoor_options(vars.D1, ztp_cfg) lines = basic_obj.get_number_of_lines_in_file(ssh_conn_obj, ztp_params.dhcp.config_file) st.log("###########LINES -- {}##############".format(lines))
def dhcp_relay_config(dut, **kwargs): """ API for DHCP relay configuration Author Chaitanya Vella ([email protected]) :param dut: :param kwargs: :return: """ cli_type = st.get_ui_type(dut, **kwargs) interface = kwargs.get("vlan", kwargs.get("interface", None)) ip_address = make_list(kwargs.get('IP', [])) ip_addr_lst = " ".join(ip_address) ip_family = kwargs.get("family", "ipv4") skip_error_check = kwargs.get("skip_error_check", False) action = kwargs.get("action","add") if not interface: st.error("Required key 'interface' is not passed") return False command = "" if cli_type == "click": if ip_family == "ipv4": command = "config interface ip dhcp-relay {} {} {}".format(action, interface, ip_addr_lst) else: command = "config interface ipv6 dhcp-relay {} {} {}".format(action, interface, ip_addr_lst) if 'link_select' in kwargs: link_select = 'enable' command += " -link-select={}".format(link_select) if 'src_interface' in kwargs: src_interface = kwargs['src_interface'] command += " -src-intf={}".format(src_interface) if 'max_hop_count' in kwargs: max_hop_count = kwargs['max_hop_count'] command += " -max-hop-count={}".format(max_hop_count) if 'vrf_name' in kwargs and action == 'add': vrf_name = kwargs['vrf_name'] command += " -vrf-name={}".format(vrf_name) if 'vrf_select' in kwargs: vrf_select = kwargs['vrf_select'] command += " -vrf-select={}".format(vrf_select) elif cli_type == "klish": if ip_family not in ["ipv4", "ipv6"]: st.error("INVALID IP FAMILY -- {}".format(ip_family)) return False command = list() interface_data = get_interface_number_from_name(interface) command.append("interface {} {}".format(interface_data.get("type"), interface_data.get("number"))) no_form = "" if action == "add" else "no" ip_string = "ip" if ip_family == "ipv4" else "ipv6" if kwargs.get("link_select") and not kwargs.get("src_interface"): st.log("SRC INTF needed for LINK SELECT operation") return False if ip_addr_lst: cmd = "{} {} dhcp-relay {}".format(no_form, ip_string, ip_addr_lst) if 'vrf_name' in kwargs and action == 'add': cmd += " vrf-name {}".format(kwargs['vrf_name']) command.append(cmd) if 'src_interface' in kwargs: src_interface = kwargs['src_interface'] command.append("{} {} dhcp-relay source-interface {}".format(no_form, ip_string, src_interface)) if 'link_select' in kwargs: command.append("{} {} dhcp-relay link-select".format(no_form, ip_string)) if 'max_hop_count' in kwargs: max_hop_count = kwargs['max_hop_count'] command.append("{} {} dhcp-relay max-hop-count {}".format(no_form, ip_string, max_hop_count)) if 'vrf_select' in kwargs: vrf_select = kwargs['vrf_select'] command.append("{} {} dhcp-relay vrf-select {}".format(no_form, ip_string, vrf_select)) elif cli_type in ["rest-patch", "rest-put"]: if ip_family not in ["ipv4", "ipv6"]: st.error("INVALID IP FAMILY -- {}".format(ip_family)) return False ip_string = "" if ip_family == "ipv4" else "v6" if kwargs.get("link_select") and not kwargs.get("src_interface"): st.log("SRC INTF needed for LINK SELECT operation") return False config_data = {"openconfig-relay-agent:config": {"id": interface}} rest_urls = st.get_datastore(dut, 'rest_urls') if ip_address: if action == 'add': config_data["openconfig-relay-agent:config"].update({"helper-address": ip_address}) if kwargs.get('vrf_name'): config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:vrf": kwargs['vrf_name']}) else: for ip in ip_address: if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_address_config'.format(ip_string)].format(id=interface, helper_address=ip)): st.error("Failed to delete DHCP-Relay Helper-Address: {}".format(ip)) return False if 'src_interface' in kwargs: if action == 'add': config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:src-intf": kwargs['src_interface']}) else: if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_src_intf_config'.format(ip_string)].format(id=interface)): st.error("Failed to delete DHCP-Relay source-interface on interface: {}".format(interface)) return False if 'link_select' in kwargs: if action == 'add': config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:link-select": "ENABLE"}) else: if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_link_select_config'.format(ip_string)].format(id=interface)): st.error("Failed to delete DHCP-Relay link-select") return False if 'max_hop_count' in kwargs: if action == 'add': config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:max-hop-count": int(kwargs['max_hop_count'])}) else: if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_max_hop_count_config'.format(ip_string)].format(id=interface)): st.error("Failed to delete DHCP-Relay max-hop-count on interface: {}".format(interface)) return False if 'vrf_select' in kwargs: if action == 'add': config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:vrf-select": "ENABLE"}) else: if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_vrf_select_config'.format(ip_string)].format(id=interface)): st.error("Failed to delete DHCP-Relay vrf-select on interface: {}".format(interface)) return False if 'policy_action' in kwargs: if action == 'add': config_data["openconfig-relay-agent:config"].update({"openconfig-relay-agent-ext:policy-action": kwargs['policy_action'].upper()}) else: if not delete_rest(dut, rest_url=rest_urls['dhcp{}_relay_policy_action_config'.format(ip_string)].format(id=interface)): st.error("Failed to delete DHCP-Relay policy_action on interface: {}".format(interface)) return False if len(config_data["openconfig-relay-agent:config"]) > 1: if not config_rest(dut, rest_url=rest_urls['dhcp{}_relay_config'.format(ip_string)].format(id=interface), http_method=cli_type, json_data=config_data): st.error("Failed to configure DHCP-Relay parameters") return False else: st.error("Unsupported CLI_TYPE: {}".format(cli_type)) return False if command: st.debug("command is {}".format(command)) output = st.config(dut, command, skip_error_check=skip_error_check, type=cli_type) if "Error" in output: if skip_error_check: return True else: return False return True
def set_status(dut, portlist, status, cli_type=''): """ :param dut: :type dut: :param portlist: :type portlist: :param status: "shutdown" or "startup" :type status: string :return: :rtype: """ cli_type = st.get_ui_type(dut, cli_type=cli_type) if cli_type == "click": if '-' in portlist: st.config(dut, "config interface {} {}".format(status, portlist)) return # check if there is interface range support if _has_intf_range(dut): try: port = ",".join(portlist) return st.config(dut, "config interface {} {}".format(status, port)) except Exception: st.warn("Failed to execute {} command - try alternative".format(status)) for port in portlist: try: st.config(dut, "config interface {} {}".format(status, port)) except ValueError: st.warn("Failed to execute {} command - try alternative".format(status)) st.config(dut, "config interface {} {}".format(port, status)) elif cli_type == "klish": commands = list() if portlist: for intf in make_list(portlist): intf_details = get_interface_number_from_name(intf) if not intf_details: st.error("Interface data not found for {} ".format(intf)) else: commands.append("interface {} {}".format(intf_details["type"], intf_details["number"])) command = "shutdown" if status == "shutdown" else "no shutdown" commands.append(command) commands.append("exit") if commands: st.config(dut, commands, type=cli_type) return True return False elif cli_type in ["rest-patch", "rest-put"]: rest_urls = st.get_datastore(dut, "rest_urls") oper = False if status == 'shutdown' else True portlist = make_list(portlist) for port in portlist: url = rest_urls['per_interface_config'].format(port) intf_operation = {"openconfig-interfaces:config": {"enabled": oper}} if not config_rest(dut, http_method=cli_type, rest_url=url, json_data=intf_operation): return False return True else: st.log("Unsupported CLI TYPE {}".format(cli_type)) return False return ""
def apply_port_shaping_config(dut, shaper_data, **kwargs): """ API to configure Port-Level shaper :param dut: :type dut: :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 st.debug("Provided port-shaper configuration is: {}".format(shaper_data)) if not shaper_data.get("policy_name"): st.error("policy_name is not provided") return False if cli_type == 'click': policy_name = "{}@255".format(shaper_data["policy_name"]) json_data = {"PORT_QOS_MAP": {}, "SCHEDULER": {policy_name: {}}} if shaper_data.get("port"): ports = make_list(shaper_data["port"]) json_data["PORT_QOS_MAP"] = { port: { "scheduler": "{}".format(policy_name) } for port in ports } else: json_data.pop("PORT_QOS_MAP") if ("pir" in shaper_data) or ( "pbs" in shaper_data) or shaper_data.get("meter_type"): if shaper_data.get("meter_type"): json_data["SCHEDULER"][policy_name].update( meter_type=shaper_data['meter_type']) if "pir" in shaper_data: json_data["SCHEDULER"][policy_name].update( pir=str(shaper_data['pir'])) if "pbs" in shaper_data: json_data["SCHEDULER"][policy_name].update( pbs=str(shaper_data['pbs'])) else: json_data.pop("SCHEDULER") json_config = json.dumps(json_data) json.loads(json_config) st.apply_json2(dut, json_config) elif cli_type == 'klish': commands = list() if ("pir" in shaper_data) or ("pbs" in shaper_data): commands.append("qos scheduler-policy {}".format( shaper_data['policy_name'])) commands.append("port") if "pir" in shaper_data: commands.append("pir {}".format( get_klish_rate(shaper_data['pir']))) if "pbs" in shaper_data: commands.append("pbs {}".format(shaper_data['pbs'])) commands.extend(["exit", "exit"]) if shaper_data.get("port"): ports = make_list(shaper_data["port"]) for port in ports: intf_data = get_interface_number_from_name(port) commands.append("interface {} {}".format( intf_data['type'], intf_data['number'])) commands.append("scheduler-policy {}".format( shaper_data['policy_name'])) commands.append("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') if ("pir" in shaper_data) or ("pbs" in shaper_data): url = rest_urls['shaper_create_config'] params_config = dict() if "pir" in shaper_data: params_config.update( pir=str(get_rest_rate(shaper_data['pir']))) if "pbs" in shaper_data: params_config.update(be=int(shaper_data['pbs'])) config_data = { "openconfig-qos:scheduler-policies": { "scheduler-policy": [{ "name": shaper_data['policy_name'], "config": { "name": shaper_data['policy_name'] }, "schedulers": { "scheduler": [{ "sequence": 255, "config": { "sequence": 255 }, "two-rate-three-color": { "config": params_config } }] } }] } } if not config_rest( dut, rest_url=url, http_method=cli_type, json_data=config_data): st.error( "Failed to create port-level shaper with shaper-data: {}". format(shaper_data)) return False if shaper_data.get("port"): ports = make_list(shaper_data["port"]) for port in ports: url = rest_urls['apply_shaper_config'].format(port) config_data = { "openconfig-qos:config": { "name": shaper_data['policy_name'] } } if not config_rest(dut, rest_url=url, http_method=cli_type, json_data=config_data): st.error( "Failed to attach shaper configuration to port: {}". format(port)) return False else: st.error("Unsupported CLI Type: {}".format(cli_type)) return False return True
def get_interface_counters(dut, port, *counter, **kwargs): cli_type = kwargs.pop('cli_type', st.get_ui_type(dut,**kwargs)) output = get_interface_counters_all(dut, port=port, cli_type=cli_type) entries = filter_and_select(output, counter, {'iface': port}) return entries
def reset_queue_shaper_params(dut, policy_name, params_dict, **kwargs): """ API to reset Queue-Level shaper parameters :param dut: :type dut: :param policy_name: :type policy_name: :param params_dict: :type params_dict: :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) if cli_type == 'klish': commands = list() commands.append("qos scheduler-policy {}".format(policy_name)) for queue, params in params_dict.items(): parameters = make_list(params) commands.append("queue {}".format(queue)) commands.extend( ["no {}".format(param.lower()) for param in parameters]) commands.append("exit") commands.append("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 queue, params in params_dict.items(): parameters = make_list(params) for param in parameters: if param.lower() not in [ 'pir', 'pbs', 'cir', 'cbs', 'type', 'weight' ]: st.error( 'Invalid queue shaper/scheduler parameter: {}'.format( param)) return False if param.lower() == 'pir': url = rest_urls['shaper_pir_config'].format( policy_name, queue) if not delete_rest(dut, rest_url=url): st.error( "Failed to reset {} on Queue: {} for shaper profile: {}" .format(param, queue, policy_name)) return False if param.lower() == 'pbs': url = rest_urls['shaper_pbs_config'].format( policy_name, queue) if not delete_rest(dut, rest_url=url): st.error( "Failed to reset {} on Queue: {} for shaper profile: {}" .format(param, queue, policy_name)) return False if param.lower() == 'cir': url = rest_urls['shaper_cir_config'].format( policy_name, queue) if not delete_rest(dut, rest_url=url): st.error( "Failed to reset {} on Queue: {} for shaper profile: {}" .format(param, queue, policy_name)) return False if param.lower() == 'cbs': url = rest_urls['shaper_cbs_config'].format( policy_name, queue) if not delete_rest(dut, rest_url=url): st.error( "Failed to reset {} on Queue: {} for shaper profile: {}" .format(param, queue, policy_name)) return False if param.lower() == 'type': url = rest_urls['scheduler_type_config'].format( policy_name, queue) if not delete_rest(dut, rest_url=url): st.error( "Failed to reset {} on Queue: {} for shaper profile: {}" .format(param, queue, policy_name)) return False if param.lower() == 'weight': url = rest_urls['scheduler_weight_config'].format( policy_name, queue) if not delete_rest(dut, rest_url=url): st.error( "Failed to reset {} on Queue: {} for shaper profile: {}" .format(param, queue, policy_name)) return False else: st.error("Unsupported CLI Type: {}".format(cli_type)) return False return True
def show_config(dut, search_string="", cli_type=""): ''' API to show the configured radius parameters Author: Chaitanya Vella ([email protected]) :param dut: :return: {'globals': [{global_auth_type': 'pap (default)','global_source_ip': '10.25.36.25','global_passkey': 'abcd (default)', 'global_timeout': '5 (default)'}], 'servers': [{'auth_type': '', 'passkey': '', 'auth_port': '1815', 'priority': '1', 'timeout': '', 'address': '1.1.1.5'}, {'auth_type': '', 'passkey': '', 'auth_port': '1812', 'priority': '1', 'timeout': '', 'address': '1.1.1.1'}]} ''' cli_type = st.get_ui_type(dut, cli_type=cli_type) st.log("Showing radius configuration ...") result = {"globals": [], "servers": []} if cli_type == "klish": command = "show radius-server" output = st.show(dut, command, type=cli_type) global_out = dict() if not output: return result for k, v in output[0].items(): if "global" in k: global_out[k] = v if global_out: result["globals"].append(global_out) for d in output[0:]: server_out = dict() for k, v in d.items(): if not "global" in k: server_out[k] = v if server_out: result["servers"].append(server_out) elif cli_type == "click": command = "show radius | grep -w {}".format( search_string) if search_string else "show radius" output = st.show(dut, command, type=cli_type) for d in output: global_out = dict() server_out = dict() for k, v in d.items(): if "global" in k: global_out[k] = v else: server_out[k] = v if global_out and not utils.check_empty_values_in_dict(global_out): result["globals"].append(global_out) if server_out and not utils.check_empty_values_in_dict(server_out): result["servers"].append(server_out) elif cli_type in ["rest-patch", "rest-put"]: rest_urls = st.get_datastore(dut, "rest_urls") url = rest_urls['radius_server_show'].format("RADIUS") url1 = rest_urls['radius_server_config'].format("RADIUS") url2 = rest_urls['radius_nasip_retransmit_stasitics_config'].format( "RADIUS") server_output = get_rest(dut, rest_url=url) global_config = get_rest(dut, rest_url=url1) global_ext_data = get_rest(dut, rest_url=url2) result = process_radius_output(server_output['output'], global_config['output'], global_ext_data['output']) else: st.log("UNSUPPORTED CLI TYPE") return False return result