Honeycomb setup and utils
[csit.git] / resources / libraries / python / IPv6Setup.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 """Library to set up IPv6 in topology."""
15
16 from ssh import SSH
17 from ipaddress import IPv6Network
18 from topology import NodeType, Topology
19 from constants import Constants
20 from VatExecutor import VatTerminal, VatExecutor
21 from robot.api import logger
22
23
24 class IPv6Networks(object):
25     """IPv6 network iterator.
26
27        :param networks: List of the available IPv6 networks.
28        :type networks: list
29     """
30     def __init__(self, networks):
31         self._networks = list()
32         for network in networks:
33             net = IPv6Network(unicode(network))
34             self._networks.append(net)
35         num = len(self._networks)
36         if num == 0:
37             raise Exception('No IPv6 networks')
38
39     def next_network(self):
40         """Get the next elemnt of the iterator.
41
42            :return: IPv6 network.
43            :rtype: IPv6Network object
44            :raises: StopIteration if there is no more elements.
45         """
46         if len(self._networks):
47             return self._networks.pop()
48         else:
49             raise StopIteration()
50
51
52 class IPv6Setup(object):
53     """IPv6 setup in topology."""
54
55     def __init__(self):
56         pass
57
58     def nodes_set_ipv6_addresses(self, nodes, nodes_addr):
59         """Set IPv6 addresses on all VPP nodes in topology.
60
61            :param nodes: Nodes of the test topology.
62            :param nodes_addr: Available nodes IPv6 adresses.
63            :type nodes: dict
64            :type nodes_addr: dict
65            :return: affected interfaces as list of (node, interface) tuples
66            :rtype: list
67         """
68
69         interfaces = []
70
71         for net in nodes_addr.values():
72             for port in net['ports'].values():
73                 host = port.get('node')
74                 if host is None:
75                     continue
76                 topo = Topology()
77                 node = topo.get_node_by_hostname(nodes, host)
78                 if node is None:
79                     continue
80                 if node['type'] == NodeType.DUT:
81                     self.vpp_set_if_ipv6_addr(node, port['if'], port['addr'],
82                                               net['prefix'])
83
84                     interfaces.append((node, port['if']))
85
86         return interfaces
87     def nodes_clear_ipv6_addresses(self, nodes, nodes_addr):
88         """Remove IPv6 addresses from all VPP nodes in topology.
89
90            :param nodes: Nodes of the test topology.
91            :param nodes_addr: Available nodes IPv6 adresses.
92            :type nodes: dict
93            :type nodes_addr: dict
94          """
95         for net in nodes_addr.values():
96             for port in net['ports'].values():
97                 host = port.get('node')
98                 if host is None:
99                     continue
100                 topo = Topology()
101                 node = topo.get_node_by_hostname(nodes, host)
102                 if node is None:
103                     continue
104                 if node['type'] == NodeType.DUT:
105                     self.vpp_del_if_ipv6_addr(node, port['if'], port['addr'],
106                                               net['prefix'])
107
108     @staticmethod
109     def linux_set_if_ipv6_addr(node, interface, addr, prefix):
110         """Set IPv6 address on linux host.
111
112            :param node: Linux node.
113            :param interface: Node interface.
114            :param addr: IPv6 address.
115            :param prefix: IPv6 address prefix.
116            :type node: dict
117            :type interface: str
118            :type addr: str
119            :type prefix: str
120         """
121         ssh = SSH()
122         ssh.connect(node)
123
124         cmd = "ifconfig {dev} inet6 add {ip}/{p} up".format(dev=interface,
125                                                             ip=addr, p=prefix)
126         (ret_code, _, _) = ssh.exec_command_sudo(cmd)
127         if int(ret_code) != 0:
128             raise Exception('TG ifconfig failed')
129
130     @staticmethod
131     def linux_del_if_ipv6_addr(node, interface, addr, prefix):
132         """Delete IPv6 address on linux host.
133
134            :param node: Linux node.
135            :param interface: Node interface.
136            :param addr: IPv6 address.
137            :param prefix: IPv6 address prefix.
138            :type node: dict
139            :type interface: str
140            :type addr: str
141            :type prefix: str
142         """
143         ssh = SSH()
144         ssh.connect(node)
145
146         cmd = "ifconfig {dev} inet6 del {ip}/{p}".format(dev=interface,
147                                                          ip=addr,
148                                                          p=prefix)
149         (ret_code, _, _) = ssh.exec_command_sudo(cmd)
150         if int(ret_code) != 0:
151             raise Exception('TG ifconfig failed')
152
153         cmd = "ifconfig {dev} down".format(dev=interface)
154         (ret_code, _, _) = ssh.exec_command_sudo(cmd)
155         if int(ret_code) != 0:
156             raise Exception('TG ifconfig failed')
157
158     @staticmethod
159     def vpp_set_if_ipv6_addr(node, interface, addr, prefix):
160         """Set IPv6 address on VPP.
161
162            :param node: VPP node.
163            :param interface: Node interface.
164            :param addr: IPv6 address.
165            :param prefix: IPv6 address prefix.
166            :type node: dict
167            :type interface: str
168            :type addr: str
169            :type prefix: str
170         """
171         sw_if_index = Topology.get_interface_sw_index(node, interface)
172         with VatTerminal(node) as vat:
173             vat.vat_terminal_exec_cmd_from_template('add_ip_address.vat',
174                                                     sw_if_index=sw_if_index,
175                                                     address=addr,
176                                                     prefix_length=prefix)
177             vat.vat_terminal_exec_cmd_from_template('set_if_state.vat',
178                                                     sw_if_index=sw_if_index,
179                                                     state='admin-up')
180
181         ssh = SSH()
182         ssh.connect(node)
183         cmd_input = 'exec show int'
184         (ret_code, stdout, stderr) = ssh.exec_command_sudo(
185             Constants.VAT_BIN_NAME, cmd_input)
186         logger.debug('ret: {0}'.format(ret_code))
187         logger.debug('stdout: {0}'.format(stdout))
188         logger.debug('stderr: {0}'.format(stderr))
189
190     @staticmethod
191     def vpp_del_if_ipv6_addr(node, interface, addr, prefix):
192         """Delete IPv6 address on VPP.
193
194            :param node: VPP node.
195            :param interface: Node interface.
196            :param addr: IPv6 address.
197            :param prefix: IPv6 address prefix.
198            :type node: dict
199            :type interface: str
200            :type addr: str
201            :type prefix: str
202         """
203         sw_if_index = Topology.get_interface_sw_index(node, interface)
204         with VatTerminal(node) as vat:
205             vat.vat_terminal_exec_cmd_from_template('del_ip_address.vat',
206                                                     sw_if_index=sw_if_index,
207                                                     address=addr,
208                                                     prefix_length=prefix)
209             vat.vat_terminal_exec_cmd_from_template('set_if_state.vat',
210                                                     sw_if_index=sw_if_index,
211                                                     state='admin-down')
212
213     @staticmethod
214     def vpp_ra_supress_link_layer(node, interface):
215         """Supress ICMPv6 router advertisement message for link scope address
216
217            :param node: VPP node.
218            :param interface: Interface name.
219            :type node: dict
220            :type interface: str
221         """
222         sw_if_index = Topology.get_interface_sw_index(node, interface)
223         VatExecutor.cmd_from_template(node,
224                                       'sw_interface_ip6nd_ra_config.vat',
225                                       sw_if_id=sw_if_index,
226                                       param='surpress')
227
228     def vpp_all_ra_supress_link_layer(self, nodes):
229         """Supress ICMPv6 router advertisement message for link scope address
230            on all VPP nodes in the topology
231
232            :param nodes: Nodes of the test topology.
233            :type nodes: dict
234         """
235         for node in nodes.values():
236             if node['type'] == NodeType.TG:
237                 continue
238             for port_k, port_v in node['interfaces'].items():
239                 if port_k == 'mgmt':
240                     continue
241                 if_name = port_v.get('name')
242                 if if_name is None:
243                     continue
244                 self.vpp_ra_supress_link_layer(node, if_name)
245
246     @staticmethod
247     def get_link_address(link, nodes_addr):
248         """Get link IPv6 address.
249
250         :param link: Link name.
251         :param nodes_addr: Available nodes IPv6 adresses.
252         :type link: str
253         :type nodes_addr: dict
254         :return: Link IPv6 address.
255         :rtype: str
256         """
257         net = nodes_addr.get(link)
258         if net is None:
259             raise ValueError('Link "{0}" address not found'.format(link))
260         return net.get('net_addr')
261
262     @staticmethod
263     def get_link_prefix(link, nodes_addr):
264         """Get link IPv6 address prefix.
265
266         :param link: Link name.
267         :param nodes_addr: Available nodes IPv6 adresses.
268         :type link: str
269         :type nodes_addr: dict
270         :return: Link IPv6 address prefix.
271         :rtype: int
272         """
273         net = nodes_addr.get(link)
274         if net is None:
275             raise ValueError('Link "{0}" address not found'.format(link))
276         return net.get('prefix')