Find PDR using binary search
[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 from ipaddress import IPv4Network
16
17 from resources.libraries.python.ssh import SSH
18 from resources.libraries.python.constants import Constants
19
20
21 class IPUtil(object):
22     """Common IP utilities"""
23
24     @staticmethod
25     def vpp_ip_probe(node, interface, addr):
26         """Run ip probe on VPP node.
27
28         :param node: VPP node.
29         :param interface: Interface name.
30         :param addr: IPv4/IPv6 address.
31         :type node: dict
32         :type interface: str
33         :type addr: str
34         """
35         ssh = SSH()
36         ssh.connect(node)
37
38         cmd = "{c}".format(c=Constants.VAT_BIN_NAME)
39         cmd_input = 'exec ip probe {dev} {ip}'.format(dev=interface, ip=addr)
40         (ret_code, _, _) = ssh.exec_command_sudo(cmd, cmd_input)
41         if int(ret_code) != 0:
42             raise Exception('VPP ip probe {dev} {ip} failed on {h}'.format(
43                 dev=interface, ip=addr, h=node['host']))
44
45
46 def convert_ipv4_netmask_prefix(network):
47     """Convert network mask to equivalent network prefix length or vice versa.
48
49     Example: mask 255.255.0.0 -> prefix length 16
50     :param network: Network mask or network prefix length.
51     :type network: str or int
52     :return: Network mask or network prefix length.
53     :rtype: str or int
54     """
55     temp_address = "0.0.0.0"
56     net = IPv4Network(u"{0}/{1}".format(temp_address, network), False)
57
58     if isinstance(network, int) and (0 < network < 33):
59         return net.netmask
60     elif isinstance(network, basestring):
61         return net.prefixlen
62     else:
63         raise Exception("Value {0} is not a valid ipv4 netmask or network"
64                         " prefix length".format(network))