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:
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."""
16 from ipaddress import IPv4Network, ip_address
18 from resources.libraries.python.ssh import SSH
19 from resources.libraries.python.constants import Constants
21 from resources.libraries.python.topology import Topology
25 """Common IP utilities"""
28 def vpp_ip_probe(node, interface, addr, if_type="key"):
29 """Run ip probe on VPP node.
31 :param node: VPP node.
32 :param interface: Interface key or name.
33 :param addr: IPv4/IPv6 address.
34 :param if_type: Interface type
39 :raises ValueError: If the if_type is unknown.
40 :raises Exception: If vpp probe fails.
46 iface_name = Topology.get_interface_name(node, interface)
47 elif if_type == "name":
48 iface_name = interface
50 raise ValueError("if_type unknown: {0}".format(if_type))
52 cmd = "{c}".format(c=Constants.VAT_BIN_NAME)
53 cmd_input = 'exec ip probe {dev} {ip}'.format(dev=iface_name, ip=addr)
54 (ret_code, _, _) = ssh.exec_command_sudo(cmd, cmd_input)
55 if int(ret_code) != 0:
56 raise Exception('VPP ip probe {dev} {ip} failed on {h}'.format(
57 dev=iface_name, ip=addr, h=node['host']))
60 def ip_addresses_should_be_equal(ip1, ip2):
61 """Fails if the given IP addresses are unequal.
63 :param ip1: IPv4 or IPv6 address.
64 :param ip2: IPv4 or IPv6 address.
69 addr1 = ip_address(unicode(ip1))
70 addr2 = ip_address(unicode(ip2))
73 raise AssertionError('IP addresses are not equal: {0} != {1}'.
77 def convert_ipv4_netmask_prefix(network):
78 """Convert network mask to equivalent network prefix length or vice versa.
80 Example: mask 255.255.0.0 -> prefix length 16
81 :param network: Network mask or network prefix length.
82 :type network: str or int
83 :return: Network mask or network prefix length.
86 temp_address = "0.0.0.0"
87 net = IPv4Network(u"{0}/{1}".format(temp_address, network), False)
89 if isinstance(network, int) and (0 < network < 33):
90 return str(net.netmask)
91 elif isinstance(network, basestring):
92 return int(net.prefixlen)
94 raise Exception("Value {0} is not a valid ipv4 netmask or network"
95 " prefix length".format(network))