summaryrefslogtreecommitdiffstats
path: root/src/vppinfra/lb_hash_hash.h
blob: fb251591eebc3c2a775ab932dc717c3b3ec308c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
 * Copyright (c) 2018 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __included_lb_hash_hash_h__
#define __included_lb_hash_hash_h__

#include <vppinfra/crc32.h>
#include <vppinfra/xxhash.h>

#if defined(clib_crc32c_uses_intrinsics) && !defined (__i386__)
static_always_inline u32
lb_hash_hash (u64 k0, u64 k1, u64 k2, u64 k3, u64 k4)
{
  u64 val = 0;
  val = crc32_u64 (val, k0);
  val = crc32_u64 (val, k1);
  val = crc32_u64 (val, k2);
  val = crc32_u64 (val, k3);
  val = crc32_u64 (val, k4);
  return (u32) val;
}

/* Note: k0 is u64 and k1 is u32 */
static_always_inline u32
lb_hash_hash_2_tuples (u64 k0, u32 k1)
{
  u64 val = 0;
  val = crc32_u64 (val, k0);
  val = crc32_u32 (val, k1);
  return (u32) val;
}
#else
static_always_inline u32
lb_hash_hash (u64 k0, u64 k1, u64 k2, u64 k3, u64 k4)
{
  u64 tmp = k0 ^ k1 ^ k2 ^ k3 ^ k4;
  return (u32) clib_xxhash (tmp);
}

/* Note: k0 is u64 and k1 is u32 */
static_always_inline u32
lb_hash_hash_2_tuples (u64 k0, u32 k1)
{
  u64 tmp = k0 ^ k1;
  return (u32) clib_xxhash (tmp);
}
#endif

#endif /* __included_lb_hash_hash_h__ */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
p { color: #75715e } /* Comment.Preproc */ .highlight .cpf { color: #75715e } /* Comment.PreprocFile */ .highlight .c1 { color: #75715e } /* Comment.Single */ .highlight .cs { color: #75715e } /* Comment.Special */ .highlight .gd { color: #f92672 } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gi { color: #a6e22e } /* Generic.Inserted */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #75715e } /* Generic.Subheading */ .highlight .kc { color: #66d9ef } /* Keyword.Constant */ .highlight .kd { color: #66d9ef } /* Keyword.Declaration */ .highlight .kn { color: #f92672 } /* Keyword.Namespace */ .highlight .kp { color: #66d9ef } /* Keyword.Pseudo */ .highlight .kr { color: #66d9ef } /* Keyword.Reserved */ .highlight .kt { color: #66d9ef } /* Keyword.Type */ .highlight .ld { color: #e6db74 } /* Literal.Date */ .highlight .m { color: #ae81ff } /* Literal.Number */ .highlight .s { color: #e6db74 } /* Literal.String */ .highlight .na { color: #a6e22e } /* Name.Attribute */ .highlight .nb { color: #f8f8f2 } /* Name.Builtin */ .highlight .nc { color: #a6e22e } /* Name.Class */ .highlight .no { color: #66d9ef } /* Name.Constant */ .highlight .nd { color: #a6e22e } /* Name.Decorator */ .highlight .ni { color: #f8f8f2 } /* Name.Entity */ .highlight .ne { color: #a6e22e } /* Name.Exception */ .highlight .nf { color: #a6e22e } /* Name.Function */ .highlight .nl { color: #f8f8f2 } /* Name.Label */ .highlight .nn { color: #f8f8f2 } /* Name.Namespace */ .highlight .nx { color: #a6e22e } /* Name.Other */ .highlight .py { color: #f8f8f2 } /* Name.Property */ .highlight .nt { color: #f92672 } /* Name.Tag */ .highlight .nv { color: #f8f8f2 } /* Name.Variable */ .highlight .ow { color: #f92672 } /* Operator.Word */ .highlight .w { color: #f8f8f2 } /* Text.Whitespace */ .highlight .mb { color: #ae81ff } /* Literal.Number.Bin */ .highlight .mf { color: #ae81ff } /* Literal.Number.Float */ .highlight .mh { color: #ae81ff } /* Literal.Number.Hex */ .highlight .mi { color: #ae81ff } /* Literal.Number.Integer */ .highlight .mo { color: #ae81ff } /* Literal.Number.Oct */ .highlight .sa { color: #e6db74 } /* Literal.String.Affix */ .highlight .sb { color: #e6db74 } /* Literal.String.Backtick */ .highlight .sc { color: #e6db74 } /* Literal.String.Char */ .highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */ .highlight .sd { color: #e6db74 } /* Literal.String.Doc */ .highlight .s2 { color: #e6db74 } /* Literal.String.Double */ .highlight .se { color: #ae81ff } /* Literal.String.Escape */ .highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */ .highlight .si { color: #e6db74 } /* Literal.String.Interpol */ .highlight .sx { color: #e6db74 } /* Literal.String.Other */ .highlight .sr { color: #e6db74 } /* Literal.String.Regex */ .highlight .s1 { color: #e6db74 } /* Literal.String.Single */ .highlight .ss { color: #e6db74 } /* Literal.String.Symbol */ .highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #a6e22e } /* Name.Function.Magic */ .highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */ .highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */ .highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */ .highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */ .highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */ } @media (prefers-color-scheme: light) { .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ }
# Copyright (c) 2016 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""IPv4 setup library"""

from socket import inet_ntoa
from struct import pack
from abc import ABCMeta, abstractmethod

from robot.api.deco import keyword

from resources.libraries.python.ssh import exec_cmd_no_error
from resources.libraries.python.Routing import Routing
from resources.libraries.python.topology import NodeType, Topology
from resources.libraries.python.VatExecutor import VatExecutor


class IPv4Node(object):
    """Abstract class of a node in a topology."""
    __metaclass__ = ABCMeta

    def __init__(self, node_info):
        self.node_info = node_info

    @staticmethod
    def _get_netmask(prefix_length):
        bits = 0xffffffff ^ (1 << 32 - prefix_length) - 1
        return inet_ntoa(pack('>I', bits))

    @abstractmethod
    def set_ip(self, interface, address, prefix_length):
        """Configure IPv4 address on interface.

        :param interface: Interface name.
        :param address: IPv4 address.
        :param prefix_length: IPv4 prefix length.
        :type interface: str
        :type address: str
        :type prefix_length: int
        :return: nothing
        """
        pass

    @abstractmethod
    def set_route(self, network, prefix_length, gateway, interface):
        """Configure IPv4 route.

        :param network: Network IPv4 address.
        :param prefix_length: IPv4 prefix length.
        :param gateway: IPv4 address of the gateway.
        :param interface: Interface name.
        :type network: str
        :type prefix_length: int
        :type gateway: str
        :type interface: str
        :return: nothing
        """
        pass

    @abstractmethod
    def unset_route(self, network, prefix_length, gateway, interface):
        """Remove specified IPv4 route.

        :param network: Network IPv4 address.
        :param prefix_length: IPv4 prefix length.
        :param gateway: IPv4 address of the gateway.
        :param interface: Interface name.
        :type network: str
        :type prefix_length: int
        :type gateway: str
        :type interface: str
        :return: nothing
        """
        pass

    @abstractmethod
    def flush_ip_addresses(self, interface):
        """Flush all IPv4 addresses from specified interface.

        :param interface: Interface name.
        :type interface: str
        :return: nothing
        """
        pass

    @abstractmethod
    def ping(self, destination_address, source_interface):
        """Send an ICMP request to destination node.

        :param destination_address: Address to send the ICMP request.
        :param source_interface: Source interface name.
        :type destination_address: str
        :type source_interface: str
        :return: nothing
        """
        pass


class Tg(IPv4Node):
    """Traffic generator node"""
    def __init__(self, node_info):
        super(Tg, self).__init__(node_info)

    def _execute(self, cmd):
        return exec_cmd_no_error(self.node_info, cmd)

    def _sudo_execute(self, cmd):
        return exec_cmd_no_error(self.node_info, cmd, sudo=True)

    def set_ip(self, interface, address, prefix_length):
        cmd = 'ip -4 addr flush dev {}'.format(interface)
        self._sudo_execute(cmd)
        cmd = 'ip addr add {}/{} dev {}'.format(address, prefix_length,
                                                interface)
        self._sudo_execute(cmd)

    def set_route(self, network, prefix_length, gateway, interface):
        netmask = self._get_netmask(prefix_length)
        cmd = 'route add -net {} netmask {} gw {}'.\
            format(network, netmask, gateway)
        self._sudo_execute(cmd)

    def unset_route(self, network, prefix_length, gateway, interface):
        self._sudo_execute('ip route delete {}/{}'.
                           format(network, prefix_length))

    def arp_ping(self, destination_address, source_interface):
        self._sudo_execute('arping -c 1 -I {} {}'.format(source_interface,
                                                         destination_address))

    def ping(self, destination_address, source_interface):
        self._execute('ping -c 1 -w 5 -I {} {}'.format(source_interface,
                                                       destination_address))

    def flush_ip_addresses(self, interface):
        self._sudo_execute('ip addr flush dev {}'.format(interface))


class Dut(IPv4Node):
    """Device under test"""
    def __init__(self, node_info):
        super(Dut, self).__init__(node_info)

    def get_sw_if_index(self, interface):
        """Get sw_if_index of specified interface from current node.

        :param interface: Interface name.
        :type interface: str
        :return: sw_if_index of the interface or None.
        :rtype: int
        """
        return Topology().get_interface_sw_index(self.node_info, interface)

    def exec_vat(self, script, **args):
        """Wrapper for VAT executor.

        :param script: Script to execute.
        :param args: Parameters to the script.
        :type script: str
        :type args: dict
        :return: nothing
        """
        # TODO: check return value
        VatExecutor.cmd_from_template(self.node_info, script, **args)

    def set_arp(self, iface_key, ip_address, mac_address):
        """Set entry in ARP cache.

        :param iface_key: Interface key.
        :param ip_address: IP address.
        :param mac_address: MAC address.
        :type iface_key: str
        :type ip_address: str
        :type mac_address: str
        """
        self.exec_vat('add_ip_neighbor.vat',
                      sw_if_index=self.get_sw_if_index(iface_key),
                      ip_address=ip_address, mac_address=mac_address)

    def set_ip(self, interface, address, prefix_length):
        self.exec_vat('add_ip_address.vat',
                      sw_if_index=self.get_sw_if_index(interface),
                      address=address, prefix_length=prefix_length)

    def set_route(self, network, prefix_length, gateway, interface):
        Routing.vpp_route_add(self.node_info,
                              network=network, prefix_len=prefix_length,
                              gateway=gateway, interface=interface)

    def unset_route(self, network, prefix_length, gateway, interface):
        self.exec_vat('del_route.vat', network=network,
                      prefix_length=prefix_length, gateway=gateway,
                      sw_if_index=self.get_sw_if_index(interface))

    def arp_ping(self, destination_address, source_interface):
        pass

    def flush_ip_addresses(self, interface):
        self.exec_vat('flush_ip_addresses.vat',
                      sw_if_index=self.get_sw_if_index(interface))

    def ping(self, destination_address, source_interface):
        pass


def get_node(node_info):
    """Creates a class instance derived from Node based on type.

    :param node_info: Dictionary containing information on nodes in topology.
    :type node_info: dict
    :return: Class instance that is derived from Node.
    """
    if node_info['type'] == NodeType.TG:
        return Tg(node_info)
    elif node_info['type'] == NodeType.DUT:
        return Dut(node_info)
    else:
        raise NotImplementedError('Node type "{}" unsupported!'.
                                  format(node_info['type']))


class IPv4Setup(object):
    """IPv4 setup in topology."""

    @staticmethod
    def vpp_nodes_set_ipv4_addresses(nodes, nodes_addr):
        """Set IPv4 addresses on all VPP nodes in topology.

        :param nodes: Nodes of the test topology.
        :param nodes_addr: Available nodes IPv4 addresses.
        :type nodes: dict
        :type nodes_addr: dict
        :return: Affected interfaces as list of (node, interface) tuples.
        :rtype: list
        """
        interfaces = []
        for net in nodes_addr.values():
            for port in net['ports'].values():
                host = port.get('node')
                if host is None:
                    continue
                topo = Topology()
                node = topo.get_node_by_hostname(nodes, host)
                if node is None:
                    continue
                if node['type'] != NodeType.DUT:
                    continue
                iface_key = topo.get_interface_by_name(node, port['if'])
                get_node(node).set_ip(iface_key, port['addr'], net['prefix'])
                interfaces.append((node, port['if']))

        return interfaces

    @staticmethod
    @keyword('Get IPv4 address of node "${node}" interface "${port}" '
             'from "${nodes_addr}"')
    def get_ip_addr(node, iface_key, nodes_addr):
        """Return IPv4 address of the node port.

        :param node: Node in the topology.
        :param iface_key: Interface key of the node.
        :param nodes_addr: Nodes IPv4 addresses.
        :type node: dict
        :type iface_key: str
        :type nodes_addr: dict
        :return: IPv4 address.
        :rtype: str
        """
        interface = Topology.get_interface_name(node, iface_key)
        for net in nodes_addr.values():
            for port in net['ports'].values():
                host = port.get('node')
                dev = port.get('if')
                if host == node['host'] and dev == interface:
                    ip = port.get('addr')
                    if ip is not None:
                        return ip
                    else:
                        raise Exception(
                            'Node {n} port {p} IPv4 address is not set'.format(
                                n=node['host'], p=interface))

        raise Exception('Node {n} port {p} IPv4 address not found.'.format(
            n=node['host'], p=interface))

    @staticmethod
    def setup_arp_on_all_duts(nodes_info, nodes_addr):
        """For all DUT nodes extract MAC and IP addresses of adjacent
        interfaces from topology and use them to setup ARP entries.

        :param nodes_info: Dictionary containing information on all nodes
        in topology.
        :param nodes_addr: Nodes IPv4 addresses.
        :type nodes_info: dict
        :type nodes_addr: dict
        """
        for node in nodes_info.values():
            if node['type'] == NodeType.TG:
                continue
            for iface_key in node['interfaces'].keys():
                adj_node, adj_int = Topology.\
                    get_adjacent_node_and_interface(nodes_info, node, iface_key)
                ip_address = IPv4Setup.get_ip_addr(adj_node, adj_int,
                                                   nodes_addr)
                mac_address = Topology.get_interface_mac(adj_node, adj_int)
                get_node(node).set_arp(iface_key, ip_address, mac_address)

    @staticmethod
    def add_arp_on_dut(node, iface_key, ip_address, mac_address):
        """Set ARP cache entree on DUT node.

        :param node: VPP Node in the topology.
        :param iface_key: Interface key.
        :param ip_address: IP address of the interface.
        :param mac_address: MAC address of the interface.
        :type node: dict
        :type iface_key: str
        :type ip_address: str
        :type mac_address: str
        """
        get_node(node).set_arp(iface_key, ip_address, mac_address)