Пример #1
0
def _get_output_from_query_validators(output, query):
    # the function determines the type of query and returns the appropriate result
    ret_dict = {}
    # if it is a valid dq query than apply the query and return the output
    if Dq.query_validator(query):
        output = Dq.str_to_dq_query(output, query)
        ret_dict.update({
            'action_output': output,
            'query_type': 'dq_query',
            'operation': None,
            'expected_value': None
        })
    else:
        # check for the string query
        output = _string_query_validator(output, query)
        action_output = output['right_hand_value']
        operation = output['operation']
        value = output['left_hand_value']
        ret_dict.update({
            'action_output': action_output,
            'query_type': 'non_dq_query',
            'operation': operation,
            'expected_value': value
        })

    return ret_dict
Пример #2
0
def apply_dictionary_filter(self, output, filters=None):
    #filtering the action output
    if not filters or \
       not isinstance(output, dict) or \
       not Dq.query_validator(filters):
        return output

    return Dq.str_to_dq_query(output, filters)
Пример #3
0
def filter_variable(self, output, filters=None):
    #filtering the action output
    if not filters:
        return output

    if not isinstance(output, dict) or not Dq.query_validator(filters):
        return output

    return Dq.str_to_dq_query(output, filters)
Пример #4
0
def filter_variable(self, output, save=None):
    #filtering the action output
    if not save or 'filter' not in save:
        return output

    if not isinstance(output, dict):
        return output

    p = re.compile(r'(?P<function>[\S\s]+)\((?P<arguments>[\S\s]+)\)')
    try:
        dq_output = Dq(output)
    except Exception as e:
        log.errored(
            'Issue creating filtering object, as the output is not as expected, {}'
            .format(str(e)))

    filters = save.get('filter')
    filters_list = filters.split('.')
    for filter in filters_list:
        # Will never go in the first time, as dq_output is created above
        # If subsequent aren't a Dq object, than fail
        if not isinstance(dq_output, Dq):
            raise Exception(
                'The output of the previous function does not'
                ' provide the appropriate input for the next function ==> {}'.
                format(previous_filter))

        m = p.match(filter)
        if m:
            function = m.groupdict()['function']
            # Finding the *args and **kwargs with the help of ast.parse
            tree = ast.parse("f({})".format(m.groupdict()['arguments']))
            funccall = tree.body[0].value
            args = [ast.literal_eval(arg) for arg in funccall.args]
            kwargs = {
                arg.arg: ast.literal_eval(arg.value)
                for arg in funccall.keywords
            }

            # Calling the function
            dq_output = getattr(dq_output, function)(*args, **kwargs)

        previous_filter = filter
    return dq_output.reconstruct() if isinstance(dq_output, Dq) \
        else dq_output
Пример #5
0
def verify_bgp_peer_as(device,
                       peer_address,
                       expected_peer_as,
                       max_time=60,
                       check_interval=10):
    """
    Verify bgp peer AS number

    Args:
        device('obj'): device to use
        peer_address('str'): Peer interface
        expected_peer_as ('int'): Expected peer AS number
        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": [
    #             {
    #                 "local-address": "10.189.5.252",
    #                 "local-as": "65171",
    #                 "peer-address": "10.49.216.179",
    #                 "peer-as": "65171", <-----------------------

    while timeout.iterate():
        try:
            out = device.parse('show bgp neighbor')
        except SchemaEmptyParserError:
            timeout.sleep()
            continue

        peers_list = out.q.get_values("bgp-peer")

        for peer in peers_list:
            addr = peer.get('peer-address')
            peer_as = Dq(peer).get_values('peer-as', 0)

            # 20.0.0.3+63208
            addr = addr.split('+')[0]
            if addr == peer_address.split('/')[0] and int(
                    peer_as) == expected_peer_as:
                return True

        timeout.sleep()
    return False
Пример #6
0
def verify_bgp_peer_import_value(
    device: object,
    peer_address: str,
    expected_import_value: str,
    max_time: int = 60,
    check_interval: int = 10
) -> bool:
    """Verifies BGP peer import value

    Args:
        device (object): Device object
        peer_address (str): Peer address
        expected_import_value (str): Expected import value to check against
        max_time (int, optional): Maximum timeout time. Defaults to 60.
        check_interval (int, optional): Check interval. Defaults to 10.

    Returns:
        bool: True/False
    """

    timeout = Timeout(max_time, check_interval)
    while timeout.iterate():
        try:
            out = device.parse('show bgp neighbor')
        except SchemaEmptyParserError:
            timeout.sleep()
            continue

        # Example dict
        # "bgp-information": {
        #     "bgp-peer": [
        #         {
        #             "bgp-option-information": {
        #                 "import-policy": str,

        for peer in out.q.get_values('bgp-peer'):
            peer_interface_ = peer.get('peer-address')

            # 20.0.0.3+63208
            if '+' in peer_interface_:
                peer_interface_ = peer_interface_.split('+')[0]

            # 20.0.0.2/24
            if '/' in peer_address:
                peer_address = peer_address.split('/')[0]

            if peer_interface_ != peer_address:
                continue

            if Dq(peer).get_values('import-policy', 0) == expected_import_value:
                return True

        timeout.sleep()
    return False
Пример #7
0
    def dq_query(self, data, filters):
        ''' Search dictionary using Dq filters

        Examples:

        .. code:: robotframework

            dq query    data=${data}   filters=contains('lc').not_contains('2').get_values('slot/world_wide_name')

        :param data: dictionary with data
        :param filters: Dq filter specification
        :return: dictionary, list, str or int

        '''
        if not isinstance(data, dict):
            raise GenieRobotException('Invalid data, dictionary expected, got %s' % type(data))
        if not Dq.query_validator(filters):
            raise GenieRobotException('Invalid filter')

        return Dq.str_to_dq_query(data, filters)
Пример #8
0
def _get_output_from_query_validators(output, query):
    """the function determines the type of query and
       returns the appropriate result"""

    ret_dict = {}
    # if it is a valid dq query than apply the query and return the output
    if Dq.query_validator(query):
        output = Dq.str_to_dq_query(output, query)
        ret_dict.update({
            'action_output': output,
            'query_type': 'dq_query',
            'operation': None,
            'expected_value': None
        })
    # if the query is itself a dictionary
    elif isinstance(query, (dict, list)):
        # output could of of type dict/QDict
        # NOTE: QDict is the type of the parser output
        if isinstance(output, QDict):
            output = dict(output)

        ret_dict.update({
            'action_output': output,
            'query_type': 'non_dq_query',
            'operation': '',
            'expected_value': query
        })
    else:
        # check for the string query
        output = _string_query_validator(output, query)
        action_output = output['right_hand_value']
        operation = output['operation']
        value = output['left_hand_value']
        ret_dict.update({
            'action_output': action_output,
            'query_type': 'non_dq_query',
            'operation': operation,
            'expected_value': value
        })

    return ret_dict
Пример #9
0
def verify_bgp_holdtime(device,
                        expected_holdtime,
                        interface,
                        max_time=60,
                        check_interval=10):
    """
    Verify bgp holdtimer with peer {interface}

    Args:
        device('obj'): device to use
        interface('str'): Peer interface   
        expected_holdtime('str'): Expected 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('holdtime|peer-address',
                                       regex=True).reconstruct()

        # {'bgp-information': {
        #     'bgp-peer': [
        #         {'bgp-option-information': {
        #                 'holdtime': '30'},
        #          'peer-address': '20.0.0.3+179'},
        #         {'bgp-option-information': {
        #                 'holdtime': '10'},
        #          'peer-address': '2001:20::3+179'}]}}

        peer_list = filter_output.get('bgp-information').get('bgp-peer')

        for peer in peer_list:

            # 20.0.0.3+63208
            peer_address = peer.get('peer-address').split('+')[0]

            if peer_address == interface and\
                    Dq(peer).get_values('holdtime')[0] == str(expected_holdtime):
                return True

        timeout.sleep()
    return False
Пример #10
0
def verify_bgp_peer_option(device,
                           interface,
                           protocol,
                           expected_bgp_option,
                           invert=False,
                           max_time=60,
                           check_interval=10):
    """
    Verify bgp peer's bgp option

    Args:
        device('obj'): device to use
        interface('str'): Peer interface
        protocol('str'): protocol name
        expected_bgp_option('str') : Expected peer bgp-option flag
        invert (bool, optional): True if output does not contain expected_bgp_option. Defaults to False.
        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
    """
    op = operator.contains
    if invert:
        op = lambda data, check: operator.not_(operator.contains(data, check))

    timeout = Timeout(max_time, check_interval)

    # show commands: "show bgp neighbor"

    # {'bgp-information': {'bgp-peer': [{
    #                                 'peer-address': '20.0.0.3+63208',
    #                                 'peer-state': 'Established',
    #                                  {'bgp-option-information': {
    #                                       "bgp-options": "Confed",
    #                                   .

    # 20.0.0.2/24
    interface = interface.split('/')[0]

    while timeout.iterate():
        try:
            out = device.parse(
                'show {protocol} neighbor'.format(protocol=protocol))
        except SchemaEmptyParserError:
            timeout.sleep()
            continue

        peers_list = out.q.get_values("bgp-peer")

        for peer in peers_list:
            peer_interface = peer.get('peer-address')
            peer_bgp_option = Dq(peer).get_values('bgp-options')

            # 20.0.0.3+63208
            peer_interface = peer_interface.split('+')[0]
            if peer_interface == interface and op(''.join(peer_bgp_option),
                                                  expected_bgp_option):
                return True

        timeout.sleep()
    return False
Пример #11
0
def verify_bgp_peer_prefixes_match(device: object,
                                   peer_address: str,
                                   active: bool = True,
                                   received: bool = True,
                                   accepted: bool = True,
                                   max_time: int = 60,
                                   check_interval: int = 10) -> bool:
    """Verifies whether BGP peer prefixes match or not

    Args:
        device (object): Device object
        peer_address (str): Peer address
        active (bool, optional): Check active prefix. Defaults to True.
        received (bool, optional): Check received prefix. Defaults to True.
        accepted (bool, optional): Check accepted prefix. Defaults to True.
        max_time (int, optional): Maximum timeout time. Defaults to 60.
        check_interval (int, optional): Check interval. Defaults to 10.

    Returns:
        bool: True/False
    """

    timeout = Timeout(max_time, check_interval)
    while timeout.iterate():
        try:
            out = device.parse('show bgp neighbor')
        except SchemaEmptyParserError:
            timeout.sleep()
            continue

        # Example dict
        # "bgp-information": {
        #     "bgp-peer": [
        #         {
        #             "bgp-rib": [
        #                 {
        #                     "accepted-prefix-count": str,
        #                     "active-prefix-count": str,
        #                     "received-prefix-count": str,

        for peer in out.q.get_values('bgp-peer'):
            peer_interface_ = peer.get('peer-address')

            # 20.0.0.3+63208
            if '+' in peer_interface_:
                peer_interface_ = peer_interface_.split('+')[0]

            # 20.0.0.2/24
            if '/' in peer_address:
                peer_address = peer_address.split('/')[0]

            if peer_interface_ != peer_address:
                continue

            prefix_list_ = list()

            if active:
                prefix_list_.append(
                    Dq(peer).get_values('active-prefix-count', 0))
            if accepted:
                prefix_list_.append(
                    Dq(peer).get_values('accepted-prefix-count', 0))
            if received:
                prefix_list_.append(
                    Dq(peer).get_values('received-prefix-count', 0))

            if len(set(prefix_list_)) == 1:
                return True

        timeout.sleep()
    return False
Пример #12
0
def verify_bgp_error_message(device,
                             interface,
                             expected_message,
                             expected_error_message,
                             max_time=60,
                             check_interval=10):
    """
    Verify bgp last error

    Args:
        device('obj'): device to use
        interface('str'): Peer interface   
        expected_message('str'): Expected message
        expected_error_message('str') : Expected error message
        max_time ('int', optional): Maximum time to keep checking. Default to 60
        check_interval ('int', optional): How often to check. Default to 10

    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-restart-flags-received": 'Notification',
    #                                 "bgp-error": [
    #                                 {
    #                                     "name": "Hold Timer Expired " "Error",
    #                                     "receive-count": "40",
    #                                     "send-count": "27",
    #                                 },
    #                                 {"name": "Cease", "receive-count": "0", "send-count": "16"},
    #                             ],
    #                                   .
    #                                   .
    #                                   .

    while timeout.iterate():
        try:
            out = device.parse('show bgp neighbor')
        except SchemaEmptyParserError:
            timeout.sleep()
            continue

        peers_list = out.q.get_values("bgp-peer")

        for peer in peers_list:

            peer_interface = peer.get('peer-address')

            # 20.0.0.3+63208
            if '+' in peer_interface:
                peer_interface = peer_interface.split('+')[0]

            notification_message = Dq(peer).get_values(
                "peer-restart-flags-received", 0)

            error_message_dict = Dq(peer).get_values("bgp-error", 0)

            if len(notification_message) > 0 and error_message_dict:
                if peer_interface == interface and notification_message == expected_message and error_message_dict.get(
                        'name') == expected_error_message:
                    return True

        timeout.sleep()
    return False