def verify_ospf3_route_nexthop(device, route, expected_nexthop, max_time=90, check_interval=10): """ Verifies nexthop of ospf3 route Args: device (`obj`): device to use route (`str`): target route expected_nexthop (`str`): expected nexthop of ospf3 route max_time (`int`): Maximum time to keep checking Default to 90 secs check_interval (`int`): How often to check Default to 10 secs Returns: True/False Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse('show ospf3 route {route}'.format(route=route)) except SchemaEmptyParserError: timeout.sleep() continue # example of out # { # "ospf3-route-information": { # "ospf-topology-route-table": { # "ospf3-route": { # "ospf3-route-entry": { # "address-prefix": "2001:30::/64", # "interface-cost": "2", # "next-hop-type": "IP", # "ospf-next-hop": { # "next-hop-address": { # "interface-address": "fe80::250:56ff:fe8d:351d" # <----- # }, # "next-hop-name": { # "interface-name": "ge-0/0/4.0" # } # }, if expected_nexthop in out.q.get_values('interface-address'): return True else: timeout.sleep() return False
def verify_ospf3_metric(device, interface, metric, max_time=60, check_interval=10): """Verify the OSPF3 metric Args: device (obj): Device object interface (str): Interface name metric (str): OSPF3 metric Returns: True/False Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse('show ospf3 interface extensive') except SchemaEmptyParserError: timeout.sleep() continue # Example dictionary # "ospf3-interface": [ # { # "interface-cost": "5", # "interface-name": "ge-0/0/0.0", # }, ospf3_interface_list = out.q.get_values('ospf3-interface') for ospf3_interface_dict in ospf3_interface_list: #{'interface-name': 'ge-0/0/1.0'} interface_ = ospf3_interface_dict.get('interface-name') #{'interface-cost': '5'} metric_ = ospf3_interface_dict.get('interface-cost') if interface_.lower() == interface.lower() and str(metric_) == str( metric): return True return False
def verify_device_tracking_policies(device, policy_name, vlan=None, iface=None, feature='Device-tracking', max_time=20, check_interval=10): """ Verify device tracking policies Args: device('obj'): device object policy_name('str'): policy name vlan('str'): vlan target iface('str'): interface target feature('str'): sisf features. Default "Device-tracking" max_time('int',optional): max check time. Defaults to 20 check_interval('int',optional): check intervals. Defaults to 10 Returns: Bool Raises: None """ target = None if vlan: target = "vlan " + vlan elif iface: target = iface else: log.error('No Target provide') return False timeout = Timeout(max_time, check_interval) while timeout.iterate(): output = device.parse('show device-tracking policies') if output['policies']: policies = output['policies'] for i in range(1, len(policies) + 1): if (policies[i]['policy_name'] == policy_name and policies[i]['target'] == target and policies[i]['feature'] == feature): log.debug('Target policy found on expected target') return True timeout.sleep() log.debug('Target policy not found') return False
def verify_ospf_neighbors_not_found(device, extensive=False, max_time=90, check_interval=10, expected_interface=None): """ Verifies ospf neighbors values don't exist Args: device ('obj'): device to use extensive ('str'): If to check with extensive command. Defaults to False max_time ('int'): Maximum time to keep checking. Defaults to 90 check_interval ('int'): How often to check. Defaults to 10 expected_interface ('str'): Interface to check for. Defaults to None Returns: True/False Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: if extensive: out = device.parse('show ospf neighbor extensive') else: out = device.parse('show ospf neighbor') except SchemaEmptyParserError: return True ospf_neighbors = out.q.get_values('ospf-neighbor') if expected_interface: if len([ neighbor for neighbor in ospf_neighbors \ if neighbor.get('interface-name') == expected_interface ]) == 0: return True else: timeout.sleep() continue if len(ospf_neighbors) == 0: return True timeout.sleep() return False
def verify_bfd_session(device, session_address, expected_session_state=None, expected_session_multiplier=None, max_time=60, check_interval=10, expected_interface=None): """ Verifiy the session state Args: device (obj): Device object session_address (str): Session address expected_session_state (str): Expected session state expected_session_multiplier (str): Expected session multiplier max_time (int, optional): Maximum timeout time. Defaults to 60. check_interval (int, optional): Check interval. Defaults to 10. expected_interface (str, optional): Expected interface to check Returns: Boolean Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse('show bfd session') except SchemaEmptyParserError: timeout.sleep() continue sessions_ = out.q.get_values('bfd-session') for session in sessions_: if session.get('session-neighbor') == session_address: if expected_session_multiplier and \ session.get('session-adaptive-multiplier') != str(expected_session_multiplier): continue if expected_session_state and \ session.get('session-state').lower() != expected_session_state.lower(): continue if expected_interface and session.get('session-interface') != expected_interface: continue return True timeout.sleep() return False
def is_logging_ospf_spf_logged(device, expected_spf_delay=None, ospf_trace_log=None, max_time=60, check_interval=10): """ Verify SPF change log Args: device('obj'): device to use expected_spf_delay('int'): SPF change value ospf_trace_log('str') : OSPF trace log max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check Returns: Boolean Raises: N/A """ timeout = Timeout(max_time, check_interval) # show commands: "show log {ospf_trace_log}" while timeout.iterate(): try: output = device.parse('show log {ospf_trace_log}'.format( ospf_trace_log=ospf_trace_log)) except SchemaEmptyParserError: timeout.sleep() continue file_content_list = output['file-content'] # log message: # Jun 12 03:32:19.068983 OSPF SPF scheduled for topology default in 8s p = ( '.*OSPF SPF scheduled for topology default in (?P<spf_change>\d+)s' ) for i in file_content_list: m = re.match(p, i) if m: if int(m.groupdict()['spf_change']) == expected_spf_delay: return True timeout.sleep() return False
def verify_neighbor_state_went_down(device, interface, realm, fail_reason, max_time=60, check_interval=10): """ Verifies message in log Args: device ('obj'): device to use interface ('str'): Interface that went down realm ('str'): ospf/ospf3 realm fail_reason ('str'): Reason state changed from full to down max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check Returns: True/False Raises: N/A """ regex_string1 = 'area +0.0.0.0\)) +state +'\ 'changed +from +Full +to +Down +due +to +(?P<asdf>' regex_string2 = '[\s\S]+)$' temp = ('^(?P<ignored_portion>[\s\S]+)realm +(?P<interface>' '{realm} {interface} {regex_string1}{fail_reason}{regex_string2}'. format( realm=realm, interface=interface, regex_string1=regex_string1, regex_string2=regex_string2, fail_reason=fail_reason)) timeout = Timeout(max_time, check_interval) while timeout.iterate(): output = device.execute('show log messages') for line in output.splitlines(): line = line.strip() m = re.match(temp, line) if m: return True timeout.sleep() return False
def verify_l2route_mac_route_flag(device, expected_flag, mac_address=None, max_time=30, check_interval=10): """ Verify for route flags for the corresponding mac (if given) Args: device ('obj'): device to use expected_flag ('str'): flags mac_address ('str'): Mac max_time ('int', optional): maximum time to wait in seconds, default is 30 check_interval ('int', optional): how often to check in seconds, default is 10 Returns: result ('bool'): verified result Raises: None """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): received_flags = device.api.get_l2route_mac_route_flags( device=device, mac_address=mac_address, ) if received_flags and mac_address: if expected_flag in received_flags.values(): return True elif received_flags: actual_flags = [] for i in received_flags.values(): actual_flags.extend(i) # Checking whether expected flag exists if expected_flag in actual_flags: return True else: timeout.sleep() if not received_flags: log.error("Could not get mac route flags along with mac_address") else: log.error('Expected flag is "{expected_flag}",and actual flag is ' '"{received_flags}"'.format(expected_flag=expected_flag, received_flags=received_flags)) return False
def verify_interface_port_channel_status_bundled( device, port_channel, max_time, check_interval, bundled_count, down_count ): """ Verify bundled interfaces mode Args: device (`obj`): Device object port_channel (`str`): Port channel interface max_time ('int'): maximum time to check check_interval ('int'): how often to check Returns: result(`bool`): verify result """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = device.parse("show etherchannel summary") if ( out and "interfaces" in out and port_channel.capitalize() in out["interfaces"] and "members" in out["interfaces"][port_channel.capitalize()] ): bundled_count = 0 down_count = 0 for intf in out["interfaces"][port_channel.capitalize()][ "members" ]: if out["interfaces"][port_channel.capitalize()]["members"][ intf ]["bundled"]: bundled_count += 1 elif ( "D" in out["interfaces"][port_channel.capitalize()]["members"][ intf ]["flags"] ): down_count += 1 if bundled_count == 3 and down_count == 1: return True timeout.sleep() return False
def verify_interface_hold_time(device, interface, expected_hold_time='0', position='up', max_time=60, check_interval=10): """ Verify the hold time of an interface Args: device ('obj'): Device object interface('str'): Interface name expected_hold_time ('str'): Hold time to check for position ('str'): Position to check for. Options are 'up' or 'down' max_time (`int`, Optional): Max time, default: 60 seconds check_interval (`int`, Optional): Check interval, default: 10 seconds Returns: Boolean Raises: None """ expected_hold_time = str(expected_hold_time) position = str(position).lower() if position not in ['up', 'down']: raise ValueError('Acceptable positions are either "up" or "down"') timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse('show interfaces extensive {interface}'.format( interface=interface.split('.')[0])) except SchemaEmptyParserError as e: timeout.sleep() continue # {'interface-information': { # 'physical-interface': [{ # 'down-hold-time': '0', # 'up-hold-time': '0'}]}} if out.q.get_values('{}-hold-time'.format(position), 0) == expected_hold_time: return True timeout.sleep() return False
def verify_missing_ipv6_source_guard_configuration(device, policy_name, trusted=False, validate_prefix=False, permit=False, deny=False, max_time=20, check_interval=10): """ Verify missing ipv6 source guard configurations Args: device('obj'): device object policy_name('str'): policy name trusted_port('bool', optional): trusted port. Defaults to False validate_prefix('bool', optional): validate prefix. Defaults to False permit('bool', optional): permit traffic. Defaults to False deny('bool', optional): deny traffic. Defaults to False max_time('int', optional): max check time. Defaults to 20 check_interval('int', optional): check intervals. Defaults to 10 Returns: True False Raises: None """ config_dict = { "trusted": trusted, "validate_prefix": validate_prefix, "permit": permit, "deny": deny, } timeout = Timeout(max_time, check_interval) while timeout.iterate(): output = device.parse('show ipv6 source-guard policy {policy}'.format( policy=policy_name)) if output['configuration']: target_configs = output['configuration'] if _verify_missing_policy_configurations(target_configs, config_dict): log.info('Correct configurations are missing on target') return True else: return False timeout.sleep() return False
def verify_ppm_transmissions(device, destination, expected_distributed_values=None, max_time=60, check_interval=10, expected_interface=None): """ Verifiy the session state Args: device (obj): Device object destination (str): route address expected_distributed_values (list): list of boolean values describing transmission distributed max_time (int, optional): Maximum timeout time. Defaults to 60. check_interval (int, optional): Check interval. Defaults to 10. expected_interface (str, optional): Expected interface to check """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse('show ppm transmissions protocol bfd detail') except SchemaEmptyParserError: timeout.sleep() continue #{'transmission-data': # [{'protocol': 'BFD', # 'transmission-destination': '27.85.194.102', # 'transmission-distributed': 'TRUE', # 'transmission-interface-index': '783', # 'transmission-interval': '300', # 'transmission-pfe-addr': 'fpc9', # 'transmission-pfe-handle': '6918' # }] #} transmission_data = out.q.get_values('transmission-data') for item in transmission_data: if item.get('transmission-destination') == destination: if item.get('transmission-distributed').lower( ) in expected_distributed_values: 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_bfd_session_destination_detail_no_output( device, address, ipv6=False, max_time=60, check_interval=10, ): """ Verifies bfd session destination has no output Args: device ('obj'): device to use address_family ('str'): Address family value address ('str'): IP address for command ipv6 ('bool'): Run ipv6 show command. Default to false expected_session_state ('str'): Session state to verify max_time ('int'): Max time to retry. Default to 60 check_interval ('int'): Number of check in interval. Default to 10 Returns: True False Raises: None """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: if ipv6: out = device.parse( "show bfd ipv6 session destination {address} detail".format( address=address ) ) else: out = device.parse( "show bfd session destination {address} detail".format( address=address ) ) except SchemaEmptyParserError: return True timeout.sleep() return False
def verify_hello_interval_holdtime( device, expected_hello_interval, expected_hold_time, interface, max_time=60, check_interval=10, ): """Verifies ldp session exists Args: device (obj): device object expected_hello_interval (int): Expected Hello interval expected_hold_time(int): Expected Holdtime interface(str): Address that passed in show command max_time (int, optional): Maximum timeout time. Default to 60 check_interval (int, optional): Interval to check. Default to 10 """ # {'ldp-interface-information': {'ldp-interface': {'interface-name': 'ge-0/0/0.0', # 'ldp-hello-interval': '5', # 'ldp-holdtime': '15', # 'ldp-interface-local-address': '10.18.14.15', # 'ldp-label-space-id': '10.17.10.24:0', # 'ldp-neighbor-count': '1', # 'ldp-next-hello': '3', # 'ldp-transport-address': '10.17.14.24'}}} timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse("show ldp interface {interface} detail".format( interface=interface)) except SchemaEmptyParserError: timeout.sleep() continue ldp_hello_interval = int(out.q.get_values('ldp-hello-interval', 0)) ldp_holdtime = int(out.q.get_values('ldp-holdtime', 0)) if ldp_hello_interval == expected_hello_interval and ldp_holdtime == expected_hold_time: return True timeout.sleep() return False
def verify_lldp_in_state(device, max_time=60, check_interval=10): """ Verify that lldp is enabled on the device Args: device = device to check status on returns: True if lldp is enabled, false in all other cases """ timeout = Timeout(max_time, check_interval, True) while timeout.iterate(): try: device.parse('show lldp neighbors detail') return True except Exception: timeout.sleep() return False
def verify_bgp_active_holdtime(device, expected_holdtime, interface, max_time=60, check_interval=10): """ Verify bgp active holdtimer with peer {interface} Args: device('obj'): device to use interface('str'): Peer interface expected_holdtime('str'): Expected active holdtime max_time ('int', optional): Maximum time to keep checking. Default to 60 seconds check_interval ('int', optional): How often to check. Default to 10 seconds Returns: Boolean Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse('show bgp neighbor') except SchemaEmptyParserError: timeout.sleep() continue filter_output = out.q.contains( 'active-holdtime|peer-address', regex=True).reconstruct() # {'bgp-information': {'bgp-peer': [{'peer-address': '20.0.0.3+179', # 'active-holdtime': '30'}, # {'peer-address': '2001:20::3+179', # 'active-holdtime': '60'}]}} peer_list = filter_output.get('bgp-information').get('bgp-peer') for peer in peer_list: peer_address = peer.get('peer-address').split('+')[0] if peer_address == interface and\ Dq(peer).get_values('active-holdtime', 0) == str(expected_holdtime): return True timeout.sleep() return False
def verify_ospf_neighbor_state(device, expected_state, interface, extensive=False, max_time=60, check_interval=10): """ Verifies state of ospf neighbor Args: device ('obj'): device to use expected_state ('str'): OSPF adjacency state that is expected interface ('str'): Name of interface extensive ('bool'): If ospf command is extensive max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check Returns: True/False Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: if extensive: output = device.parse('show ospf neighbor extensive') else: output = device.parse('show ospf neighbor') except SchemaEmptyParserError: timeout.sleep() continue #{'ospf-neighbor-information': {'ospf-neighbor': [{}]}} neighbors = output.q.get_values('ospf-neighbor') for neighbor in neighbors: #'interface-name': 'ge-0/0/0.0' #'ospf-neighbor-state': 'Full' if neighbor.get('interface-name',[]) == interface and \ neighbor.get('ospf-neighbor-state',[]).lower() == expected_state.lower(): return True timeout.sleep() return False
def verify_no_ospf_neigbor_output(device, expected_interface=None, extensive=False, max_time=60, check_interval=10): """ Verifies ospf neighbor doesn't exists Args: device ('obj'): device to use expected_interface ('str'): Interface being searched for extensive ('bool'): If ospf command is extensive max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check Returns: True/False Raises: N/A """ timeout = Timeout(max_time, check_interval) exists = False while timeout.iterate(): if extensive: try: output = device.parse('show ospf neighbor extensive') except SchemaEmptyParserError: output = None timeout.sleep() continue else: try: output = device.parse('show ospf neighbor') except SchemaEmptyParserError: output = None timeout.sleep() continue for neighbor in Dq(output).get_values('ospf-neighbor'): if neighbor.get('interface-name') == expected_interface: exists = True timeout.sleep() break else: exists = False timeout.sleep() if not output or not exists: return True else: return False
def verify_firewall_filter( device: object, expected_filter: str, max_time: int = 60, check_interval: int = 10, invert: bool = False, ) -> bool: """Verify firewall filter exists Args: device (object): Device object expected_filter (str): Filter to check for max_time (int, optional): Maximum timeout time. Defaults to 60. check_interval (int, optional): Check interval. Defaults to 10. invert (bool, optional): Invert function. Defaults to False. Returns: bool: True/False """ op = operator.contains if invert: op = lambda filters, ex_filter: operator.not_( operator.contains(filters, ex_filter)) timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: out = device.parse('show firewall') except SchemaEmptyParserError: timeout.sleep() continue # Example dict # "firewall-information": { # "filter-information": [ # { # "filter-name": str, filters_ = out.q.get_values('filter-name') if op(filters_, expected_filter): return True timeout.sleep() return False
def verify_log_exists(device, file_name, expected_log, max_time=60, check_interval=10, invert=False): """ Verify log exists Args: device('obj'): device to use file_name('str') : File name to check log expected_log ('str'): Expected log message max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check invert ('bool', 'optional'): Inverts to check if it doesn't exist Returns: Boolean Raises: N/A """ op = operator.truth if invert: op = lambda val: operator.not_(operator.truth(val)) timeout = Timeout(max_time, check_interval) # show commands: "show log {file_name}" while timeout.iterate(): try: log_output = device.parse( 'show log {file_name}'.format(file_name=file_name)) except SchemaEmptyParserError: timeout.sleep() continue log_found = log_output.q.contains('.*{}.*'.format(expected_log), regex=True) if op(log_found): return True timeout.sleep() return False
def verify_snmp_target( device, expected_target, max_time=30, check_interval=10, ): """ Verify snmp target Args: device (`obj`): Device object expected_target (`str`): Expected target IP max_time (`int`): Max time, default: 60 seconds check_interval (`int`): Check interval, default: 10 seconds Returns: result (`bool`): Verified result Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: output = device.parse('show configuration snmp') except SchemaEmptyParserError: timeout.sleep() continue # Example output # "configuration": { # "snmp": { # "trap-group": { # "targets": [ # { # "name": "125.53.99.32" # }, targets = output.q.get_values('targets') if [ target for target in targets if target.get('name', None) == expected_target ]: return True timeout.sleep() return False
def verify_chassis_fpc_slot_state(device, expected_slot, expected_state, max_time=60, check_interval=10): """ Verifies slot state via show chassis fpc Args: device (obj): Device object expected_slot (bool): Expected slot to check. expected_state (str): Expected state of that slot. max_time (int, optional): Maximum timeout time. Defaults to 60. check_interval (int, optional): Check interval. Defaults to 10. Returns: True/False """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse('show chassis fpc') except SchemaEmptyParserError: timeout.sleep() continue # Example dict # 'fpc-information': { # 'fpc': [{'slot': '0', # 'state': 'Offline'}] # object_types_ = out.q.get_values("cos-object-type") fpc_list = out.q.contains('slot|state', regex=True).get_values('fpc') for fpc in fpc_list: slot = fpc.get('slot') state = fpc.get('state') if slot == expected_slot and state == expected_state: return True timeout.sleep() return False
def verify_flow_exporter_records_added_and_sent_are_equal( device, exporter, max_time=30, check_interval=10): """ Verifies that flow exporter records added and sent are equal Args: device ('obj'): Device to use exporter ('str'): Exporter name max_time ('int'): Max time to keep checking check_interval ('int'): How often to check Raises: N/A Returns: True/False """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: output = device.parse( "show flow exporter {exporter} statistics".format( exporter=exporter)) except SchemaEmptyParserError: return False for client in (output.get("flow_exporter", {}).get(exporter, {}).get("client_send_stats", {})): if exporter in client: added = (output["flow_exporter"][exporter]["client_send_stats"] [client].get("records_added", {}).get("total")) sent = (output["flow_exporter"][exporter]["client_send_stats"] [client].get("records_added", {}).get("sent")) log.info( "Records added is: {added}. Records sent is {sent}".format( added=added, sent=sent)) if 0 < added == sent > 0: return True timeout.sleep() return False
def verify_coherentDSP_in_state(device, dsp, controller_state='up', derived_state='in service', max_time=60, check_interval=20): ''' Verify coherentDSP state Args: device (`obj`): Device object dsp (`str`): CoherentDSP port controller_state (`str`): Expected controller state derived_state (`str`): Expected derived state max_time (`int`): Max time check_interval (`int`): Check interval Returns: result (`bool`): Verified result ''' cmd = 'show controllers coherentDSP {}'.format(dsp) 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 cs = out.get(dsp, {}).get('controller_state', '').lower() ds = out.get(dsp, {}).get('derived_state', '').lower() log.info("CoherentDSP {} controller state is {}, expected value is {}". format(dsp, cs, controller_state)) log.info( "CoherentDSP {} derived state is {}, expected value is {}".format( dsp, ds, derived_state)) if cs == controller_state.lower() and ds == derived_state.lower(): return True timeout.sleep() return False
def verify_ntp_mode( device, expected_mode, expected_peer=None, max_time=30, check_interval=10, ): """ Verify a peer has expected ntp mode Args: device (`obj`): Device object expected_mode (`str`): Expected mode expected_peer (`str`): Expected peer IP max_time (`int`): Max time, default: 60 seconds check_interval (`int`): Check interval, default: 10 seconds Returns: result (`bool`): Verified result Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): try: output = device.parse('show ntp associations') except SchemaEmptyParserError: timeout.sleep() continue # Example output # 'peer': { # Any(): { # 'local_mode': { # Any(): { # 'remote': str, # 'mode': str, if expected_peer: return expected_peer in output.q.contains_key_value( 'mode', expected_mode).get_values('peer') elif expected_mode in output.q.get_values('mode'): return True timeout.sleep() return False
def verify_ospf_two_router_id(device, ipaddress, expected_id_1, expected_id_2, max_time=60, check_interval=10): """Verify 'show ospf database lsa-id ipaddress detail' contains expected_id_1 and expected_id_2 Args: device ('obj'): device to use expected_id_1 ('str'): expected router id expected_id_2 ('str'): expected router id ipaddress ('str'): address to use in show command max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check Raise: None Returns: Boolean """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse( 'show ospf database lsa-id {ipaddress} detail'.format( ipaddress=ipaddress)) except SchemaEmptyParserError: timeout.sleep() continue attached_router_list = out.q.get_values("attached-router") if (expected_id_1 in attached_router_list) and (expected_id_2 in attached_router_list): return True else: timeout.sleep() continue return False
def verify_ospf3_interface_type(device, interface, interface_type, max_time=60, check_interval=10): """ Verifies ospf3 interface type Args: device ('obj'): device to use interface ('str'): Interface to use interface_type ('str'): Interface type max_time ('int'): Maximum time to keep checking check_interval ('int'): How often to check Returns: True/False Raises: N/A """ timeout = Timeout(max_time, check_interval) while timeout.iterate(): out = None try: out = device.parse('show ospf3 interface extensive') except SchemaEmptyParserError: timeout.sleep() continue #{'ospf-interface': [{'interface-name': 'ge-0/0/1.0'}]} for ospf_interface in out.q.get_values('ospf3-interface'): #{'interface-name': 'ge-0/0/1.0'} intf = ospf_interface.get('interface-name', None) #{'interface-type': 'LAN'} intf_type = ospf_interface.get('interface-type', None) if intf == interface and intf_type == interface_type: return True timeout.sleep() return False
def verify_bgp_all_neighbor_status(device, expected_state, max_time=60, check_interval=10): """ Verify all bgp peer states Args: device('obj'): device to use expected_state('str') : Expected peer state max_time ('int', optional): Maximum time to keep checking. Default to 60 seconds check_interval ('int', optional): How often to check. Default to 10 seconds Returns: Boolean Raises: N/A """ timeout = Timeout(max_time, check_interval) # show commands: "show bgp neighbor" # {'bgp-information': {'bgp-peer': [{ # 'flap-count': '0', # 'peer-address': '20.0.0.3+63208', # 'peer-state': 'Established', # . # . # . while timeout.iterate(): try: out = device.parse('show bgp neighbor') except SchemaEmptyParserError: timeout.sleep() continue status_set = set(out.q.get_values('peer-state')) if len(status_set) == 1 and expected_state in status_set: return True timeout.sleep() return False
def reconnect_device(device, max_time=300, interval=30, sleep_disconnect=30, via=None): """ Reconnect device Args: device ('obj'): Device object max_time ('int'): Max time in seconds trying to connect to device interval ('int'): Interval in seconds of checking connection sleep_disconnect ('int'): Waiting time after device disconnection Raise: ConnectionError Returns: N/A """ destroy_connection(device=device) time.sleep(sleep_disconnect) timeout = Timeout(max_time=max_time, interval=interval) while timeout.iterate(): try: if via: device.connect(via=via) else: device.connect() _error_patterns(device=device) except Exception as e: log.info("Device {dev} is not connected".format(dev=device.name)) destroy_connection(device=device) timeout.sleep() continue if device.is_connected(): break timeout.sleep() if not device.is_connected(): raise ConnectionError( "Could not reconnect to device {dev}".format(dev=device.name)) log.info("Reconnected to device {dev}".format(dev=device.name))