1 # Copyright (c) 2018 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:
6 # http://www.apache.org/licenses/LICENSE-2.0
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.
14 """Common IP utilities library."""
18 from ipaddress import IPv4Network, ip_address
20 from resources.libraries.python.ssh import SSH
21 from resources.libraries.python.constants import Constants
22 from resources.libraries.python.ssh import exec_cmd_no_error, exec_cmd
23 from resources.libraries.python.topology import Topology
27 """Common IP utilities"""
30 def ip_to_int(ip_str):
31 """Convert IP address from string format (e.g. 10.0.0.1) to integer
32 representation (167772161).
34 :param ip_str: IP address in string representation.
36 :returns: Integer representation of IP address.
39 return int(ip_address(unicode(ip_str)))
42 def int_to_ip(ip_int):
43 """Convert IP address from integer representation (e.g. 167772161) to
44 string format (10.0.0.1).
46 :param ip_int: IP address in integer representation.
48 :returns: String representation of IP address.
51 return str(ip_address(ip_int))
54 def vpp_ip_probe(node, interface, addr, if_type="key"):
55 """Run ip probe on VPP node.
57 :param node: VPP node.
58 :param interface: Interface key or name.
59 :param addr: IPv4/IPv6 address.
60 :param if_type: Interface type
65 :raises ValueError: If the if_type is unknown.
66 :raises Exception: If vpp probe fails.
72 iface_name = Topology.get_interface_name(node, interface)
73 elif if_type == "name":
74 iface_name = interface
76 raise ValueError("if_type unknown: {0}".format(if_type))
78 cmd = "{c}".format(c=Constants.VAT_BIN_NAME)
79 cmd_input = 'exec ip probe {dev} {ip}'.format(dev=iface_name, ip=addr)
80 (ret_code, _, _) = ssh.exec_command_sudo(cmd, cmd_input)
81 if int(ret_code) != 0:
82 raise Exception('VPP ip probe {dev} {ip} failed on {h}'.format(
83 dev=iface_name, ip=addr, h=node['host']))
86 def ip_addresses_should_be_equal(ip1, ip2):
87 """Fails if the given IP addresses are unequal.
89 :param ip1: IPv4 or IPv6 address.
90 :param ip2: IPv4 or IPv6 address.
95 addr1 = ip_address(unicode(ip1))
96 addr2 = ip_address(unicode(ip2))
99 raise AssertionError('IP addresses are not equal: {0} != {1}'.
103 def setup_network_namespace(node, namespace_name, interface_name,
105 """Setup namespace on given node and attach interface and IP to
106 this namespace. Applicable also on TG node.
108 :param node: Node to set namespace on.
109 :param namespace_name: Namespace name.
110 :param interface_name: Interface name.
111 :param ip_addr: IP address of namespace's interface.
112 :param prefix: IP address prefix length.
114 :type namespace_name: str
119 cmd = ('ip netns add {0}'.format(namespace_name))
120 exec_cmd_no_error(node, cmd, sudo=True)
122 cmd = ('ip link set dev {0} up netns {1}'.format(interface_name,
124 exec_cmd_no_error(node, cmd, sudo=True)
126 cmd = ('ip netns exec {0} ip addr add {1}/{2} dev {3}'.format(
127 namespace_name, ip_addr, prefix, interface_name))
128 exec_cmd_no_error(node, cmd, sudo=True)
131 def linux_enable_forwarding(node, ip_ver='ipv4'):
132 """Enable forwarding on a Linux node, e.g. VM.
134 :param node: Node to enable forwarding on.
135 :param ip_ver: IP version, 'ipv4' or 'ipv6'.
139 cmd = 'sysctl -w net.{0}.ip_forward=1'.format(ip_ver)
140 exec_cmd_no_error(node, cmd, sudo=True)
143 def get_linux_interface_name(node, pci_addr):
144 """Get the interface name.
146 :param node: Node where to execute command.
147 :param pci_addr: PCI address
150 :returns: Interface name
152 :raises RuntimeError: If cannot get the information about interfaces.
155 regex_intf_info = r"pci@" \
156 r"([0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}.[0-9a-f])\s*" \
157 r"([a-zA-Z0-9]*)\s*network"
159 cmd = "lshw -class network -businfo"
160 ret_code, stdout, stderr = exec_cmd(node, cmd, timeout=30, sudo=True)
162 raise RuntimeError('Could not get information about interfaces, '
163 'reason:{0}'.format(stderr))
165 for line in stdout.splitlines()[2:]:
167 if re.search(regex_intf_info, line).group(1) == pci_addr:
168 return re.search(regex_intf_info, line).group(2)
169 except AttributeError:
174 def set_linux_interface_up(node, interface):
175 """Set the specified interface up.
177 :param node: Node where to execute command.
178 :param interface: Interface in namespace.
181 :raises RuntimeError: If the interface could not be set up.
184 cmd = "ip link set {0} up".format(interface)
185 ret_code, _, stderr = exec_cmd(node, cmd, timeout=30, sudo=True)
187 raise RuntimeError('Could not set the interface up, reason:{0}'.
191 def set_linux_interface_ip(node, interface, ip_addr, prefix,
193 """Set IP address to interface in linux.
195 :param node: Node where to execute command.
196 :param interface: Interface in namespace.
197 :param ip_addr: IP to be set on interface.
198 :param prefix: IP prefix.
199 :param namespace: Execute command in namespace. Optional
205 :raises RuntimeError: IP could not be set.
207 if namespace is not None:
208 cmd = 'ip netns exec {} ip addr add {}/{} dev {}'.format(
209 namespace, ip_addr, prefix, interface)
211 cmd = 'ip addr add {}/{} dev {}'.format(ip_addr, prefix, interface)
212 (ret_code, _, stderr) = exec_cmd(node, cmd, timeout=5, sudo=True)
215 'Could not set IP for interface, reason:{}'.format(stderr))
218 def set_linux_interface_route(node, interface, route, namespace=None):
219 """Set route via interface in linux.
221 :param node: Node where to execute command.
222 :param interface: Interface in namespace.
223 :param route: Route to be added via interface.
224 :param namespace: Execute command in namespace. Optional parameter.
230 if namespace is not None:
231 cmd = 'ip netns exec {} ip route add {} dev {}'.format(
232 namespace, route, interface)
234 cmd = 'ip route add {} dev {}'.format(route, interface)
235 exec_cmd_no_error(node, cmd, sudo=True)
238 def convert_ipv4_netmask_prefix(network):
239 """Convert network mask to equivalent network prefix length or vice versa.
241 Example: mask 255.255.0.0 -> prefix length 16
242 :param network: Network mask or network prefix length.
243 :type network: str or int
244 :returns: Network mask or network prefix length.
247 temp_address = "0.0.0.0"
248 net = IPv4Network(u"{0}/{1}".format(temp_address, network), False)
250 if isinstance(network, int) and (0 < network < 33):
251 return str(net.netmask)
252 elif isinstance(network, basestring):
253 return int(net.prefixlen)
255 raise Exception("Value {0} is not a valid ipv4 netmask or network"
256 " prefix length".format(network))