def get_ospf_segment_routing_lb_srlb_base_and_range(device, process_id, router_id): """ Gets 'SRLB Base' and 'SRLB Range' values Args: device ('obj'): Device to use process_id ('str'): Ospf process_id router_id ('str'): Which router_id entry to use Returns: if can filter down to one result: (('int'): SRLB Base value, ('dict'): Output from parser) Raises: None """ try: output = device.parse("show ip ospf segment-routing local-block") except SchemaEmptyParserError: return None, None reqs_base = R([ "instance", process_id, "areas", "(?P<area>.*)", "router_id", router_id, "srlb_base", "(?P<srlb_base>.*)", ]) found_base = find(output, reqs_base, filter_=False, all_keys=True) if not found_base: return None, None reqs_range = R([ "instance", process_id, "areas", "(?P<area>.*)", "router_id", router_id, "srlb_range", "(?P<srlb_range>.*)", ]) found_range = find(output, reqs_range, filter_=False, all_keys=True) if not found_range: return None, None return found_base[0][0], found_range[0][0]
def get_mpls_outgoing_label(device, label): """ Get mpls outgoing label using 'show mpls forwarding-table labels {label}' Args: device ('obj'): Device object label ('str'): Local label Returns: out_label ('str'): Outgoing label """ cmd = 'show mpls forwarding-table labels {label}'.format(label=label) try: out = device.parse(cmd) except Exception as e: log.error("Failed to parse '{cmd}': {e}".format(cmd=cmd, e=e)) return None reqs = R([ 'vrf', '(.*)', 'local_label', '(?P<local_label>.*)', 'outgoing_label_or_vc', '(?P<outgoing_label>.*)', '(.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) if found: return found[0][1][-1] else: return None
def verify_isis_neighbor_in_state(device, interfaces, state='up', max_time=60, check_interval=20): ''' Verify ISIS neighbor state Args: device (`obj`): Device object interfaces (`list`): ISIS neighbor interfaces state (`str`): Expected state max_time (`int`): Max time check_interval (`int`): Check interval Returns: result (`bool`): Verified result ''' cmd = 'show isis neighbors' timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse(cmd) except Exception as e: log.error("Failed to parse '{}':\n{}".format(cmd, e)) timeout.sleep() continue result = True intfs = '|'.join(interfaces) reqs = R([ 'isis', '(.*)', 'vrf', '(.*)', 'interfaces', '(?P<interface>' + intfs + ')', 'neighbors', '(?P<neighbor>.*)', 'state', '(?P<state>.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) if found and len(found) == len(interfaces): keys = GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found, all_keys=True) else: log.error( "Failed to find required ISIS neighbor interface: {}".format( interfaces)) timeout.sleep() continue for intf_dict in keys: log.info("Interface {} status is {}, expected value is {}".format( intf_dict['interface'], intf_dict['state'].lower(), state)) if intf_dict['state'].lower() != state.lower(): result = False if result: return True timeout.sleep() return False
def _verify_finds_root_interface(ops, requirements, **kwargs): '''Triggers in this file specified verify method. This is to check only 1 interface change to root after change the priority to highest ''' log.info(banner("check only One interface change to root for each vlan")) ret = find([ops], R(requirements), filter_=False) if not ret: raise Exception( 'There is no Root interfaces after changing the priority') group_keys = GroupKeys.group_keys(reqs=[requirements], ret_num={}, source=ret) vlan_dict = {} for item in group_keys: vlan_dict.setdefault(item['vlan'], {}).setdefault(item['interface'], {}) for vlan in vlan_dict: if len(vlan_dict[vlan].keys()) != 1: raise Exception( 'Expect ONE Root interface for vlan {v} but got {i}'.format( v=vlan, i=list(vlan_dict[vlan].keys()))) else: log.info('Find ONE ROOT interface {i} for vlan {v}'.format(i=list( vlan_dict[vlan].keys())[0], v=vlan))
def verify_no_isis_neighbor(device, max_time=60, check_interval=20): ''' Verify ISIS neighbors not found Args: device (`obj`): Device object Returns: result (`bool`): Verified result ''' cmd = 'show isis neighbors' timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse(cmd) except Exception: return True reqs = R(['isis', '(.*)', 'vrf', '(.*)', '(?P<interface>.*)']) found = find([out], reqs, filter_=False, all_keys=True) if found and not found[0][0]: return True timeout.sleep() return True
def get_ospf_process_id_on_interface(device, interface): """ Get ospf interface process id Args: device ('obj'): device object interface ('str'): interface name Returns: ospf_id ('str'): ospf process id """ log.info( "Getting ospf interface {intf} process id from device {dev}".format( intf=interface, dev=device.name)) cmd = 'show ospf vrf all-inclusive interface {intf}'.format(intf=interface) try: out = device.parse(cmd) except Exception as e: log.error("Failed to parse '{cmd}': {e}".format(cmd=cmd, e=e)) return None reqs = R([ 'vrf', '(?P<vrf>.*)', 'address_family', '(?P<af>.*)', 'instance', '(?P<instance>.*)', 'areas', '(?P<area>.*)', 'interfaces', interface, 'process_id', '(?P<pid>.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) if found: return found[0][0] else: return None
def get_mpls_forwarding_table_key_value_pairs(device, ip): """ Gets all key:value pairs from the mpls forwarding table Args: device (`obj`): Device object ip (`str`): IP address Returns: result (`bool`): Verified result Raises: N/A """ try: out = device.parse('show mpls forwarding-table {}'.format(ip)) except SchemaEmptyParserError: log.info("Device output is empty.") return {} reqs = R([ 'vrf', '(.*)', 'local_label', '(?P<local_label>.*)', 'outgoing_label_or_vc', '(?P<outgoing_label>.*)', 'prefix_or_tunnel_id', '(?P<prefix>.*)', 'outgoing_interface', '(?P<interface>.*)', 'next_hop', '(?P<next_hop>.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) if found: return GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found, all_keys=True) return {}
def get_mpls_label_stack(device, label): """ Get mpls Label Stack using 'show mpls forwarding-table labels {label} detail' Args: device ('obj'): Device object label ('str'): Local label Returns: stack ('list'): Label stack """ stack = [] cmd = 'show mpls forwarding-table labels {label} detail'.format( label=label) try: out = device.parse(cmd) except Exception as e: log.error("Failed to parse '{cmd}': {e}".format(cmd=cmd, e=e)) return stack reqs = R([ 'vrf', '(.*)', 'local_label', '(?P<local_label>.*)', 'outgoing_label_or_vc', '(?P<outgoing_label>.*)', 'prefix_or_tunnel_id', '(.*)', 'outgoing_interface', '(.*)', 'label_stack', '(?P<label_stack>.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) if found: stack = found[0][0].split() return [int(label) for label in stack]
def verify_interface_ip_route_connected( device, interface, ip_address, prefix, vrf, max_time=60, check_interval=10, flag=True, ): """Verify interface IP address route is present in - show ip route connected Args: device (`obj`): Device object interface (`str`): Interface name ip_address (`str`): Interface ip address prefix (`int`): prefix length vrf (`str`): vrf name flag (`bool`): True if verify present False if verify not present max_time (`int`): max time check_interval (`int`): check interval Returns: result(`bool`): verify result """ timeout = Timeout(max_time, check_interval) if prefix: ip_address = "{ip}/{prefix}".format(ip=ip_address, prefix=prefix) reqs = R([ "vrf", "(?P<vrf>.*)", "address_family", "ipv4", "routes", ip_address, "next_hop", "outgoing_interface", interface, "outgoing_interface", interface, ]) while timeout.iterate(): try: out = device.parse("show ip route connected") except Exception as e: log.info(e) timeout.sleep() continue found = find([out], reqs, filter_=False, all_keys=True) if flag == bool(found): return True timeout.sleep() return False
def verify_cef_labels(device, route, expected_first_label, expected_last_label=None, max_time=90, check_interval=10): """ Verify first and last label on route Args: device ('obj'): Device object route ('str'): Route address expected_first_label ('str'): Expected first label expected_last_label ('str'): Expected last label max_time ('int'): Max time in seconds checking output check_interval ('int'): Interval in seconds of each checking Return: True/False Raises: None """ reqs = R([ 'vrf', '(.*)', 'address_family', '(.*)', 'prefix', '(.*{}.*)'.format(route), 'nexthop', '(.*)', 'outgoing_interface', '(.*)', '(?P<val>.*)' ]) timeout = Timeout(max_time, check_interval) while timeout.iterate(): result = True out = None try: out = device.parse('show ip cef {}'.format(route)) except SchemaEmptyParserError: out = None if not out: result = False log.info( 'Could not get information about show ip cef {}'.format(route)) timeout.sleep() continue found = find([out], reqs, filter_=False, all_keys=True) if found: keys = GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found) for item in keys: first_label = item.get('val', {}).get('outgoing_label', None) if first_label and str(expected_first_label) not in str( first_label): result = False if expected_last_label: sid = item.get('val', {}).get('sid', None) if str(expected_last_label) != str(sid): result = False if result: return True timeout.sleep() return False
def _check_parsed_key(device, key, command, max_time, check_interval, step): keys = str_to_list(key) reqs = R(list(keys)) max_time_ratio = device.custom.get('max_time_ratio', None) if max_time and max_time_ratio: try: max_time = int(max_time * float(max_time_ratio)) except ValueError: log.error( 'The max_time_ratio ({m}) value is not of type float'.format( m=max_time_ratio)) check_interval_ratio = device.custom.get('check_interval_ratio', None) if check_interval and check_interval_ratio: try: check_interval = int(check_interval * float(check_interval_ratio)) except ValueError: log.error( 'The check_interval_ratio ({c}) value is not of type float'. format(c=check_interval_ratio)) with step.start( "Verify that '{k}' is in the output".format(k=key)) as step: if max_time and check_interval: timeout = Timeout(max_time, check_interval) while timeout.iterate(): output = device.parse(command) found = find([output], reqs, filter_=False, all_keys=True) if found: break timeout.sleep() if not found: step.failed("Could not find '{k}'".format(k=key)) else: log.info("Found {f}".format(f=found)) else: output = device.parse(command) found = find([output], reqs, filter_=False, all_keys=True) if not found: step.failed("Could not find '{k}'".format(k=key)) else: log.info("Found {f}".format(f=found))
def verify_mpls_forwarding_table_has_prefix_in_subnet_range(device, subnet, max_time=30, check_interval=10): """ Verifies local label for entries with a prefix inside subnet Args: device ('obj'): Device to use subnet ('str'): Subnet to verify inside max_time ('int'): Max time to check check_interval ('int'): How often to check returns: True/False raises: N/A """ log.info('Checking atleast one entry has a prefix in subnet {subnet} range' .format(subnet=subnet)) try: subnet = IPNetwork(subnet) except Exception: log.info('Bad subnet provided') return False timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse('show mpls forwarding-table') except SchemaEmptyParserError: log.info('Parser output is empty') timeout.sleep() continue reqs = R(['vrf', '(.*)', 'local_label', '(?P<local_label>.*)', 'outgoing_label_or_vc', '(.*)', 'prefix_or_tunnel_id', '(?P<prefix>.*)', 'outgoing_interface', '(.*)', ]) found = find([out], reqs, filter_=False, all_keys=True) if found: keys = GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found, all_keys=True) for key in keys: try: prefix = IPNetwork(key['prefix']) except Exception: continue if prefix in subnet: return True return False
def check_issu_state(cls, device, slot, expected_state, attempt=3, sleep=5): ''' Check if the ISSU state is in the expected state Args: device (`obj`): Device Object. expected_state (`str`): Acceptable ISSU states are: - loadversion - runversion - acceptversion - commitversion slot (`str`): Slot for which we need to check ISSU state attempt (`int`): Attempt numbers when learn the feature. sleep (`int`): The sleep time. Returns: None Raises: AssertionError: 'expected_state' is not as expected Exception: Cannot parse 'show issu state detail' output No output form 'show issu state detail' Unable to execute 'show issu state detail' Example: >>> check_issu_state(device=uut, slot='R1', expected_state='commitversion') ''' assert expected_state in [ 'loadversion', 'runversion', 'acceptversion', 'commitversion' ] lookup = Lookup.from_device(device) for i in range(attempt): try: issu_dict = lookup.parser.show_issu.\ ShowIssuStateDetail(device=device).parse() rs = R(['slot', slot, 'last_operation', expected_state]) ret = find([issu_dict], rs, filter_=False, all_keys=True) if ret: break except SchemaEmptyParserError as e: raise Exception( "No output or unable to parse 'show issu state " "detail'", from_exception=e) except Exception as e: raise Exception("Unable to execute 'show issu state detail'", from_exception=e) time.sleep(sleep) else: raise AssertionError("FAIL: ISSU state not '{}' - this is " "unexpected".format(expected_state))
def _modify_ops_snapshot(original, current, path): # First does path exists in original, except the value r = R(path[:-1] + ['(.*)']) ret = find([original], r, filter_=False) if not ret: raise ValueError( "'{p}' does not exist on original snapshot " "as per the original trigger requirement".format(p=path)) _modify_value(current, path[:-1], ret[0][0])
def verify_segment_routing_dynamic_metric_type(device, policy, expected_type='TE', max_time=30, check_interval=10): """ Verify segment-routing metric type under dynamic path with active state using 'show segment-routing traffic-eng policy name {policy}' Args: device (`obj`): Device object policy (`str`): Policy name expected_type (`str`): Expected metric type max_time (`int`): Max time, default: 30 check_interval (`int`): Check interval, default: 10 Returns result (`bool`): Verified result """ cmd = 'show segment-routing traffic-eng policy name {policy}'.format( policy=policy) timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse(cmd) except Exception as e: log.error("Failed to parse '{cmd}': {e}".format(cmd=cmd, e=e)) timeout.sleep() continue reqs = R([ policy, 'candidate_paths', 'preference', '(?P<preference>.*)', 'path_type', 'dynamic', '(?P<path>.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) for item in found: if item[0]['status'].lower() == 'active': metric_type = item[0]['metric_type'] break else: log.error("Failed to find a dynamic path in active state") timeout.sleep() continue log.info("Policy {policy} active dynamic path's metric_type is " "{metric_type}, expected type is {expected_type}".format( policy=policy, metric_type=metric_type, expected_type=expected_type)) if (metric_type.lower() == expected_type.lower()): return True timeout.sleep() return False
def _find_objects(self, *rs, iterable=None, count=None, cls=None, **kwargs): """Base function for find_<object> Please refer to the actual implementation on how to use it. Part of Testbed, Device and Links. """ assert iterable is not None # Make sure count is positive if count is not None and count < 0: raise TypeError('count can only be a positive number. {c} ' 'is not positive.'.format(c=count)) if cls is None: raise TypeError('cls must be provided') if not rs: rs = rs = [R(**kwargs)] kwargs = {} elif kwargs: # Merge kwargs with all the existing R new_kwargs = {} for r in rs: for k in kwargs: if k not in r.kwargs: r.kwargs[k] = kwargs[k] continue log.warning('{k} already in the requirements ' 'of {r}'.format(k=k, r=r)) new_kwargs[k] = kwargs[k] kwargs = new_kwargs return_objs = find(iterable, *rs, type_=cls, **kwargs)[:count] # If a particular number of items were requested, make sure # we return this exact number, otherwise raises an exception if count is not None and count > len(return_objs): raise CountError( '{count} {type}s were requested but only {lreturn}' ' were found. The requirements for the type of ' '{type} were rs={rs} and kwargs={kwargs}'.format( lreturn=len(return_objs), type=cls.__name__, rs=rs, kwargs=kwargs, count=count)) # Return the specified amount return return_objs[:count]
def check_feature_status(cls, device, expect, feature_name, abstract, attempt=3, sleep=5): ''' Check if the feature is disabled/enabled Args: device (`obj`): Device Object. abstract (`obj`): Abstract Lookup Object. expect (`str`): Feature status. Only accept 'disabled' and 'enabled' feature_name (`str`): Feature namne. sleep_time (`int`): The sleep time. attempt (`int`): Attempt numbers when learn the feature. Returns: None Raises: AssertionError: 'expect' is not 'disabled' or 'enabled' Or the status is not same as expect value SyntaxError: Cannot parse show feature output Example: >>> check_feature_status(device=uut, expect='disabled', feature_name='bgp',abstract=abstract) ''' assert expect in ['disabled', 'enabled'] for i in range(attempt): try: ret = abstract.parser.show_feature.ShowFeature(device=device) ret = ret.parse() except Exception as e: raise SyntaxError("Cannot parse command 'show " "feature'") from e ret = find([ret], R([ 'feature', feature_name, 'instance', '(.*)', 'state', expect ]), filter_=False) if ret: break time.sleep(sleep) else: raise AssertionError('{n} is failed to {s}'.format(n=feature_name, s=expect))
def verify_ntp_synchronized_alias(self, device, alias=None): '''Verify that NTP is synchronized on this device verify NTP is synchronized on device "<device>" ''' ops = self.genie_ops_on_device_alias('ntp', device, alias) rs = [R(['info', 'clock_state', 'system_status', 'associations_address', '(?P<neighbors>.*)'])] output = find([ops], *rs, filter_=False, all_keys=True) if not output: self.builtin.fail("{} does not have NTP synchronized".format(device))
def get_ospf_interfaces_with_neighbor(ops, neighbor): '''Get OSPF interfaces by given neighbor''' # find the neighbors on uut connected to the helper device reqs = [[ 'info', 'vrf', '(?P<vrf>.*)', 'address_family', '(?P<af>.*)', 'instance', '(?P<instance>.*)', 'areas', '(?P<areas>.*)', 'interfaces', '(?P<interfaces>.*)', 'neighbors', neighbor, '(?P<neighbors_info>.*)' ]] rs_uut = [R(i) for i in reqs] ret_uut = find([ops], *rs_uut, filter_=False) return GroupKeys.group_keys(ret_num={}, source=ret_uut, reqs=reqs)
def verify_bgp_l2vpn_evpn_neighbor_in_state(device, neighbor, state='established', max_time=60, check_interval=20): ''' Verify BGP l2vpn evpn neighbor state Args: device (`obj`): Device object neighbor (`str`): Neighbor IP state (`str`): Expected state max_time (`int`): Max time check_interval (`int`): Check interval Returns: result (`bool`): Verified result ''' cmd = 'show bgp l2vpn evpn neighbors {}'.format(neighbor) timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse(cmd) except Exception as e: log.error("Failed to parse '{}':\n{}".format(cmd, e)) timeout.sleep() continue reqs = R([ 'instance', '(.*)', 'vrf', '(.*)', 'neighbor', neighbor, 'session_state', '(?P<state>.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) if found: session_state = found[0][0].lower() else: log.error("Failed to get neighbor {} BGP state".format(neighbor)) timeout.sleep() continue log.info("Neighbor {} BGP state is {}, expected value is {}".format( neighbor, session_state, state)) if session_state == state.lower(): return True timeout.sleep() return False
def verify_count_alias(self, number, structure, device, alias=None): '''Verify that a specific number of <...> is <...> on a device using a specific alias verify count "<number>" "bgp neighbors" on device "<device>" verify count "<number>" "bgp routes" on device "<device>" verify count "<number>" "ospf neighbors" on device "<device>" verify count "<number>" "interfaces neighbors" on device "<device>" ''' # First word of action is the protocol # Last word is the expected value # the rest is the structure. protocol, structure = structure.split(' ', 1) # Make sure we support this protocol count = 0 if protocol == 'bgp': # Load bgp if structure == 'neighbors': # then count the number of neighbor ops = self.genie_ops_on_device_alias('bgp', device, alias) rs = [R(['info', 'instance', '(?P<instance>.*)', 'vrf', '(?P<vrf>.*)', 'neighbor', '(?P<neighbor>.*)', 'session_state', '([e|E]stablished)'])] elif structure == 'routes': # then count the number of routes ops = self.genie_ops_on_device_alias('bgp', device, alias) rs = [R(['table', 'instance', '(?P<instance>.*)', 'vrf', '(?P<vrf>.*)', 'address_family', '(?P<af>.*)', 'prefixes', '(?P<routes>.*)', '(?P<rest>.*)'])] elif protocol == 'ospf': # Load ospf if structure == 'neighbors': # then count the number of neighbor ops = self.genie_ops_on_device_alias('ospf', device, alias) rs = [R(['info', 'vrf', '(?P<vrf>.*)', 'address_family', '(?P<af>.*)', 'instance', '(?P<instance>.*)', 'areas', '(?P<areas>.*)', '(?P<mode>.*)', '(?P<interface>.*)', 'neighbors', '(?P<neighbors>.*)', 'state', '([f|F]ull)'])] elif protocol == 'interface': if structure == 'up': # then count the number of interface ops = self.genie_ops_on_device_alias('interface', device, alias) rs = [R(['info', '(?P<interface>.*)', 'oper_status', '([u|U]p)'])] count = len(find([ops], *rs, filter_=False, all_keys=True)) if count != int(number): self.builtin.fail("Expected '{e}', but found '{f}'".format(e=number, f=count))
def verify_segment_routing_operation(device, loopback_interface, label_min, prefix_sid_index, max_time=60, check_interval=20): ''' Verify Segment routing operation Args: device (`obj`): Device object loopback_interface (`str`): Loopback interface label_min (`int`): Segment routing global block start prefix_sid_index (`int`): Prefix-sid index max_time (`int`): Max time check_interval (`int`): Check interval Returns: result (`bool`): Verified result ''' timeout = Timeout(max_time, check_interval) while timeout.iterate(): result = True try: out = device.parse('show isis segment-routing label table') except SchemaEmptyParserError: log.info("Device output is empty.") result = False timeout.sleep() continue reqs = R(['instance', '(?P<segment_routing>.*)', 'label', '(?P<label>.*)', 'prefix_interface', '(?P<prefix_interface>.*)']) found = find([out], reqs, filter_=False, all_keys=True) if found: for item in found: if item[0] == loopback_interface: if item[1][3] == label_min+prefix_sid_index: result = True else: log.error("Could not find any mpls route") result = False if result is True: return result timeout.sleep() return result
def verify_route_known_via(device, route, known_via, ipv6=False, max_time=90, check_interval=10): """ Verify route known via Args: device ('obj'): Device object route ('str'): Route address known_via ('str'): Known via value max_time ('int'): Max time in seconds checking output check_interval ('int'): Interval in seconds of each checking Return: True/False Raises: None """ reqs = R([ 'entry', '(.*)', 'known_via', '(.*{}.*)'.format(known_via), ]) timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: if ipv6: out = device.parse('show ipv6 route {}'.format(route)) else: out = device.parse('show ip route {}'.format(route)) except Exception: timeout.sleep() continue if not out: log.info('Could not get information about show ip route {}'.format( route)) timeout.sleep() continue found = find([out], reqs, filter_=False, all_keys=True) if found: return True timeout.sleep() return False
def get_ntp_outgoing_interface(device, system_peer, vrf=None): """ Get the interface which is used to communicate with NTP system peer Args: device (`obj`): Device object system_peer (`str`): System peer ip Returns: interface (`str`): Interface name """ if vrf: cmd = "show ip cef vrf {vrf} {ip}".format(vrf=vrf, ip=system_peer) else: cmd = "show ip cef {ip}".format(ip=system_peer) try: out = device.parse(cmd) except Exception as e: log.error("Failed to parse cmd {cmd}: {e}".format(cmd=cmd, e=e)) return None reqs = R([ "vrf", "(?P<vrf>.*)", "address_family", "(?P<af>.*)", "prefix", "(?P<ip>.*)", "nexthop", "(?P<nexthop>.*)", "outgoing_interface", "(?P<intf>.*)", "(?:.*)", ]) found = find([out], reqs, filter_=False, all_keys=True) if found: keys = GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found, all_keys=True) else: log.error("No interface was found") return None interface = keys[0]["intf"] return interface
def verify_ntp_synchronized_server_alias(self, server, device, alias=None): '''Verify that a specific server is the synchronized ntp server verify "1.1.1.1" is synchronized ntp server on device "<device>" ''' ops = self.genie_ops_on_device_alias('ntp', device, alias) rs = [R(['info', 'clock_state', 'system_status', 'associations_address', '(?P<neighbors>.*)'])] output = find([ops], *rs, filter_=False, all_keys=True) if not output: self.builtin.fail("No synchronized server could be found! Was " "expected '{}' to be synchronized".format(server)) if not output[0][0] == server: self.builtin.fail("Expected synchronized server to be '{}', but " "found '{}'".format(server, output[0][0]))
def is_issu_in_state(device, slot, expected_state, max_time=1200, interval=30): """ Verify if ISSU is in state for a specific slot Args: device ('obj'): Device object slot ('str'): Slot for which we need to check ISSU state expected_state ('str'): Acceptable ISSU states are: - loadversion - runversion - acceptversion - commitversion max_time ('int'): Max time checking issu state interval ('int': Interval checking Raise: None Return True False """ assert expected_state in [ "loadversion", "runversion", "acceptversion", "commitversion", ] rs = R(["slot", slot, "last_operation", expected_state]) timeout = Timeout(max_time=max_time, interval=interval) while timeout.iterate(): try: output = device.parse("show issu state detail") except SchemaEmptyParserError: timeout.sleep() continue ret = find([output], rs, filter_=False, all_keys=True) if ret: return True timeout.sleep() return False
def get_interface_ip_address(device, interface, address_family): """ Get interface ip_address from device Args: interface('str'): Interface to get address device ('obj'): Device object address_family ('str'): Address family Returns: None ip_address ('str'): If has multiple addresses will return the first one. Raises: None """ if address_family not in ["ipv4", "ipv6", "inet", "inet6"]: log.info( 'Must provide one of the following address families: "ipv4", "ipv6", "inet", "inet6"' ) return if address_family == "ipv4": address_family = "inet" elif address_family == "ipv6": address_family = "inet6" try: out = device.parse( 'show interfaces {interface} terse'.format(interface=interface)) except SchemaEmptyParserError: return reqs = R([ interface, 'protocol', address_family, '(.*)', 'local', '(?P<local>.*)' ]) found = find([out], reqs, filter_=False, all_keys=True) if found: keys = GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found, all_keys=True) return keys[0]['local']
def get_bgp_last_reset_list(device): """ Get last reset list from - show ip bgp all neighbors Args: device(`obj`): Device object Returns: key_list(`list`): result list table(`obj`): table to display Raises: SchemaEmptyParserError """ try: out = device.parse("show ip bgp all neighbors") except SchemaEmptyParserError: log.info("Command has not returned any results") return [], None reqs = R([ "vrf", "(?P<vrf>.*)", "neighbor", "(?P<ip>.*)", "bgp_session_transport", "connection", "last_reset", "(?P<reset>.*)", ]) found = find([out], reqs, filter_=False, all_keys=True) if not found: return [], None key_list = GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found, all_keys=True) # display in table table = PrettyTable() table.field_names = ["Vrf", "Neighbor", "Reset Count"] for key in key_list: table.add_row([key["vrf"], key["ip"], key["reset"]]) return key_list, table
def get_ntp_outgoing_interface(device, system_peer): """ Get the interface which is used to communicate with NTP system peer Args: device (`obj`): Device object system_peer (`str`): System peer ip Returns: interface (`str`): Interface name """ try: out = device.parse("show ip cef {}".format(system_peer)) except SchemaEmptyParserError as e: log.error("Command 'show ip cef {}' " "did not return any results".format(system_peer)) return None reqs = R([ "vrf", "(?P<vrf>.*)", "address_family", "(?P<af>.*)", "prefix", "(?P<ip>.*)", "nexthop", "(?P<nexthop>.*)", "outgoing_interface", "(?P<intf>.*)", "(?:.*)", ]) found = find([out], reqs, filter_=False, all_keys=True) if found: keys = GroupKeys.group_keys(reqs=reqs.args, ret_num={}, source=found, all_keys=True) else: log.error("No interface was found") return None interface = keys[0]["intf"] return interface
def get_interface_qlimit_bytes(device, interface): """ Get interface qlimit in bytes Args: device (`obj`): Device object interface (`str`): Interface name Returns: None qlimit_bytes (`int`): Interface qlimit_bytes Raises: None """ try: out = device.parse( "show platform hardware qfp active infrastructure bqs " "queue output default interface {interface}".format( interface=interface ) ) except SchemaEmptyParserError: return reqs = R( [ interface, "index", "(?P<index>.*)", "software_control_info", "qlimit_bytes", "(?P<qlimit>.*)", ] ) found = find([out], reqs, filter_=False, all_keys=True) if found: keys = GroupKeys.group_keys( reqs=reqs.args, ret_num={}, source=found, all_keys=True ) return keys[0]["qlimit"] else: return