예제 #1
0
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]
예제 #2
0
    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))
예제 #3
0
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
예제 #4
0
def _get_msdp_device(vrf):
    '''Get device which has msdp from learned LTS in common_setup

    Can be controlled via sections parameters which is provided by the
    triggers/verification datafile

    Args:
      Mandatory:
        vrf (`str`) : vrf information that want the feaure on

    Returns:
        AETEST results


    Raises:
        None

    '''
    # check if uut has msdp feature
    if not vrf:
        vrf = '(?P<vrf>.*)'

    reqs = [[
        'ops.msdp.msdp.Msdp', '(?P<dev>.*)', 'info', 'vrf', vrf, 'peer',
        '(?P<peer>.*)', 'session_state', 'established'
    ]]
    rs = [R(r) for r in reqs]
    return rs
예제 #5
0
def _get_static_rp_device(vrf):
    '''Get device which has static_rp from learned LTS in common_setup

    Can be controlled via sections parameters which is provided by the
    triggers/verification datafile

    Args:
      Mandatory:
        vrf (`str`) : vrf information that want the feaure on

    Returns:
        AETEST results


    Raises:
        None

    '''
    # check if uut has bsr_rp feature
    if not vrf:
        vrf = '(?P<vrf>^(?!default)\w+$)'

    reqs = [[
        'ops.pim.pim.Pim', 'vrf', vrf, 'address_family', '(.*)', 'rp',
        'static_rp', '(?P<static_rp>.*)'
    ]]
    rs = [R(r) for r in reqs]
    return rs
예제 #6
0
def _get_auto_rp_interface_device(vrf):
    '''Get device which has auto-rp 'up' interface from learned LTS in common_setup

    Can be controlled via sections parameters which is provided by the
    triggers/verification datafile

    Args:
      Mandatory:
        vrf (`str`) : vrf information that want the feaure on

    Returns:
        AETEST results


    Raises:
        None

    '''
    # check if uut has auto_rp feature
    if not vrf:
        vrf = '(?P<vrf>^(?!default)\w+$)'

    reqs = [[
        'conf.pim.Pim', '(?P<dev>.*)', 'device_attr', '(?P<dev>.*)',
        '_vrf_attr', vrf, '_address_family_attr', 'ipv4',
        'send_rp_announce_intf', '(?P<intf>.*)'
    ]]

    rs = [R(r) for r in reqs]
    return rs
예제 #7
0
파일: get.py 프로젝트: fehuapaya/genielibs
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]
예제 #8
0
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
예제 #9
0
파일: get.py 프로젝트: fehuapaya/genielibs
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 {}
예제 #10
0
파일: get.py 프로젝트: fehuapaya/genielibs
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
예제 #11
0
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
예제 #12
0
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))
예제 #13
0
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
예제 #14
0
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
예제 #15
0
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
예제 #16
0
 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])
예제 #17
0
    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))
예제 #18
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
예제 #19
0
    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]
예제 #20
0
    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))
예제 #21
0
    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))
예제 #22
0
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)
예제 #23
0
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
예제 #24
0
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
예제 #25
0
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
예제 #26
0
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))
예제 #27
0
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
예제 #28
0
def verify_clear_callable(ops, uut, pre_time, verify_func, mapping, **kwargs):

    # If no verify attribute
    if not kwargs.get('verify_func_args', None):
        return

    # in case of inherit, introduce local var
    # for holding class glob vars
    verify_func_args = kwargs['verify_func_args'].copy()
    
    # populate r_object path
    reqs = []
    if 'r_obj' in verify_func_args:
        reqs.extend(mapping._path_population(verify_func_args['r_obj'], uut))

    # store the populate path back to self.verify_func_args as R object
    extra_args = {}
    if reqs:
        verify_func_args['r_obj'] = []
        for req in reqs:
            verify_func_args['r_obj'].append(R(req))

    # diff the pre and post time to compare the uptime
    # + 1 is fuzzy time that may diff from routers timing and script
    compare_time = int(time.time() - pre_time + 1)

    # update the mapping extra_args with variables
    for key, value in verify_func_args.items():
        if isinstance(value, str):
            # get the value from the inital ops to compare
            if value.startswith('(?P'):
                value = mapping._populate_path([[value]], ops.device, mapping.keys)
                verify_func_args[key] = value[0][0]
            else:
                if locals().get(value) or locals().get(value) == 0:
                    verify_func_args[key] = locals().get(value)
                else:
                    verify_func_args[key] = value

    # compare the attributes that may changed as expected
    if 'r_obj' in verify_func_args:
        back_up = verify_func_args['r_obj'].copy()
        for r in back_up:
            verify_func_args['r_obj'] = [r]
            verify_func(**verify_func_args)
예제 #29
0
    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]))
예제 #30
0
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']