CSIT-778: Add mac-ip binding acl l2bd perf test
[csit.git] / resources / libraries / python / IPUtil.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Common IP utilities library."""
15
16 from ipaddress import IPv4Network, ip_address
17
18 from resources.libraries.python.ssh import SSH
19 from resources.libraries.python.constants import Constants
20 from resources.libraries.python.ssh import exec_cmd_no_error, exec_cmd
21 from resources.libraries.python.topology import Topology
22
23
24 class IPUtil(object):
25     """Common IP utilities"""
26
27     @staticmethod
28     def ip_to_int(ip_str):
29         """Convert IP address from string format (e.g. 10.0.0.1) to integer
30         representation (167772161).
31
32         :param ip_str: IP address in string representation.
33         :type ip_str: str
34         :returns: Integer representation of IP address.
35         :rtype: int
36         """
37         return int(ip_address(unicode(ip_str)))
38
39     @staticmethod
40     def int_to_ip(ip_int):
41         """Convert IP address from integer representation (e.g. 167772161) to
42         string format (10.0.0.1).
43
44         :param ip_int: IP address in integer representation.
45         :type ip_int: int
46         :returns: String representation of IP address.
47         :rtype: str
48         """
49         return str(ip_address(ip_int))
50
51     @staticmethod
52     def vpp_ip_probe(node, interface, addr, if_type="key"):
53         """Run ip probe on VPP node.
54
55         :param node: VPP node.
56         :param interface: Interface key or name.
57         :param addr: IPv4/IPv6 address.
58         :param if_type: Interface type
59         :type node: dict
60         :type interface: str
61         :type addr: str
62         :type if_type: str
63         :raises ValueError: If the if_type is unknown.
64         :raises Exception: If vpp probe fails.
65         """
66         ssh = SSH()
67         ssh.connect(node)
68
69         if if_type == "key":
70             iface_name = Topology.get_interface_name(node, interface)
71         elif if_type == "name":
72             iface_name = interface
73         else:
74             raise ValueError("if_type unknown: {0}".format(if_type))
75
76         cmd = "{c}".format(c=Constants.VAT_BIN_NAME)
77         cmd_input = 'exec ip probe {dev} {ip}'.format(dev=iface_name, ip=addr)
78         (ret_code, _, _) = ssh.exec_command_sudo(cmd, cmd_input)
79         if int(ret_code) != 0:
80             raise Exception('VPP ip probe {dev} {ip} failed on {h}'.format(
81                 dev=iface_name, ip=addr, h=node['host']))
82
83     @staticmethod
84     def ip_addresses_should_be_equal(ip1, ip2):
85         """Fails if the given IP addresses are unequal.
86
87         :param ip1: IPv4 or IPv6 address.
88         :param ip2: IPv4 or IPv6 address.
89         :type ip1: str
90         :type ip2: str
91         """
92
93         addr1 = ip_address(unicode(ip1))
94         addr2 = ip_address(unicode(ip2))
95
96         if addr1 != addr2:
97             raise AssertionError('IP addresses are not equal: {0} != {1}'.
98                                  format(ip1, ip2))
99
100     @staticmethod
101     def setup_network_namespace(node, namespace_name, interface_name,
102                                 ip_addr, prefix):
103         """Setup namespace on given node and attach interface and IP to
104         this namespace. Applicable also on TG node.
105
106         :param node: Node to set namespace on.
107         :param namespace_name: Namespace name.
108         :param interface_name: Interface name.
109         :param ip_addr: IP address of namespace's interface.
110         :param prefix: IP address prefix length.
111         :type node: dict
112         :type namespace_name: str
113         :type vhost_if: str
114         :type ip_addr: str
115         :type prefix: int
116         """
117         cmd = ('ip netns add {0}'.format(namespace_name))
118         exec_cmd_no_error(node, cmd, sudo=True)
119
120         cmd = ('ip link set dev {0} up netns {1}'.format(interface_name,
121                                                          namespace_name))
122         exec_cmd_no_error(node, cmd, sudo=True)
123
124         cmd = ('ip netns exec {0} ip addr add {1}/{2} dev {3}'.format(
125             namespace_name, ip_addr, prefix, interface_name))
126         exec_cmd_no_error(node, cmd, sudo=True)
127
128     @staticmethod
129     def linux_enable_forwarding(node, ip_ver='ipv4'):
130         """Enable forwarding on a Linux node, e.g. VM.
131
132         :param node: Node to enable forwarding on.
133         :param ip_ver: IP version, 'ipv4' or 'ipv6'.
134         :type node: dict
135         :type ip_ver: str
136         """
137         cmd = 'sysctl -w net.{0}.ip_forward=1'.format(ip_ver)
138         exec_cmd_no_error(node, cmd, sudo=True)
139
140     @staticmethod
141     def set_linux_interface_ip(node, interface, ip_addr, prefix,
142                                namespace=None):
143         """Set IP address to interface in linux.
144
145         :param node: Node where to execute command.
146         :param interface: Interface in namespace.
147         :param ip_addr: IP to be set on interface.
148         :param prefix: IP prefix.
149         :param namespace: Execute command in namespace. Optional
150         :type node: dict
151         :type interface: str
152         :type ip_addr: str
153         :type prefix: int
154         :type namespace: str
155         :raises RuntimeError: IP could not be set.
156         """
157         if namespace is not None:
158             cmd = 'ip netns exec {} ip addr add {}/{} dev {}'.format(
159                 namespace, ip_addr, prefix, interface)
160         else:
161             cmd = 'ip addr add {}/{} dev {}'.format(ip_addr, prefix, interface)
162         (ret_code, _, stderr) = exec_cmd(node, cmd, timeout=5, sudo=True)
163         if ret_code != 0:
164             raise RuntimeError(
165                 'Could not set IP for interface, reason:{}'.format(stderr))
166
167     @staticmethod
168     def set_linux_interface_route(node, interface, route, namespace=None):
169         """Set route via interface in linux.
170
171         :param node: Node where to execute command.
172         :param interface: Interface in namespace.
173         :param route: Route to be added via interface.
174         :param namespace: Execute command in namespace. Optional parameter.
175         :type node: dict
176         :type interface: str
177         :type route: str
178         :type namespace: str
179         """
180         if namespace is not None:
181             cmd = 'ip netns exec {} ip route add {} dev {}'.format(
182                 namespace, route, interface)
183         else:
184             cmd = 'ip route add {} dev {}'.format(route, interface)
185         exec_cmd_no_error(node, cmd, sudo=True)
186
187
188 def convert_ipv4_netmask_prefix(network):
189     """Convert network mask to equivalent network prefix length or vice versa.
190
191     Example: mask 255.255.0.0 -> prefix length 16
192     :param network: Network mask or network prefix length.
193     :type network: str or int
194     :returns: Network mask or network prefix length.
195     :rtype: str or int
196     """
197     temp_address = "0.0.0.0"
198     net = IPv4Network(u"{0}/{1}".format(temp_address, network), False)
199
200     if isinstance(network, int) and (0 < network < 33):
201         return str(net.netmask)
202     elif isinstance(network, basestring):
203         return int(net.prefixlen)
204     else:
205         raise Exception("Value {0} is not a valid ipv4 netmask or network"
206                         " prefix length".format(network))