de96c189e59abf519823e7e06c95f334f3d2e991
[csit.git] / resources / libraries / python / IPv4NodeAddress.py
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:
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 """Robot framework variable file.
15
16 Create dictionary variable nodes_ipv4_addr of IPv4 addresses from
17 available networks.
18 """
19
20 from ipaddress import IPv4Network
21
22 from resources.libraries.python.topology import Topology
23
24 # Default list of IPv4 subnets
25 IPV4_NETWORKS = ['192.168.{}.0/24'.format(i) for i in range(1, 100)]
26
27
28 class IPv4NetworkGenerator(object):
29     """IPv4 network generator.
30
31     TODO: Conform to https://docs.python.org/2/library/stdtypes.html#typeiter
32     """
33
34     def __init__(self, networks):
35         """Populate internal list of valid networks.
36
37         :param networks: List of strings containing IPv4 subnet
38             with prefix length.
39         :type networks: list
40         :raise RuntimeError: If no IPv4 networks are added.
41         """
42         self._networks = []
43         for network in networks:
44             net = IPv4Network(unicode(network))
45             self._networks.append(net)
46         if not self._networks:
47             raise RuntimeError("No IPv4 networks")
48
49     def next_network(self):
50         """Pop and return network from internal list.
51
52         :returns: Next network in form (IPv4Network, subnet).
53         :raises StopIteration: If there are no more elements.
54         """
55         if self._networks:
56             return self._networks.pop()
57         else:
58             raise StopIteration()
59
60
61 def get_variables(nodes, networks=IPV4_NETWORKS[:]):
62     """Special robot framework method that returns dictionary nodes_ipv4_addr,
63     mapping of node and interface name to IPv4 address.
64
65     :param nodes: Nodes of the test topology.
66     :param networks: List of available IPv4 networks.
67     :type nodes: dict
68     :type networks: list
69
70     .. note::
71        Robot framework calls it automatically.
72     """
73     topo = Topology()
74     links = topo.get_links(nodes)
75
76     if len(links) > len(networks):
77         raise Exception('Not enough available IPv4 networks for topology.')
78
79     ip4_n = IPv4NetworkGenerator(networks)
80
81     nets = {}
82
83     for link in links:
84         ip4_net = ip4_n.next_network()
85         net_hosts = ip4_net.hosts()
86         port_idx = 0
87         ports = {}
88         for node in nodes.values():
89             if_key = topo.get_interface_by_link_name(node, link)
90             if_name = topo.get_interface_name(node, if_key)
91             if if_name is not None:
92                 port = {'addr': str(next(net_hosts)),
93                         'node': node['host'],
94                         'if': if_name}
95                 port_idx += 1
96                 port_id = 'port{0}'.format(port_idx)
97                 ports.update({port_id: port})
98         nets.update({link: {'net_addr': str(ip4_net.network_address),
99                             'prefix': ip4_net.prefixlen,
100                             'ports': ports}})
101
102     return {'DICT__nodes_ipv4_addr': nets}