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 """IPv4 setup library"""
16 from socket import inet_ntoa
17 from struct import pack
18 from abc import ABCMeta, abstractmethod
20 from robot.api.deco import keyword
22 from resources.libraries.python.ssh import exec_cmd_no_error
23 from resources.libraries.python.Routing import Routing
24 from resources.libraries.python.topology import NodeType, Topology
25 from resources.libraries.python.VatExecutor import VatExecutor
28 class IPv4Node(object):
29 """Abstract class of a node in a topology."""
30 __metaclass__ = ABCMeta
32 def __init__(self, node_info):
33 self.node_info = node_info
36 def _get_netmask(prefix_length):
37 """Convert IPv4 network prefix length into IPV4 network mask.
39 :param prefix_length: Length of network prefix.
40 :type prefix_length: int
42 :return: Network mask.
46 bits = 0xffffffff ^ (1 << 32 - prefix_length) - 1
47 return inet_ntoa(pack('>I', bits))
50 def set_ip(self, interface, address, prefix_length):
51 """Configure IPv4 address on interface.
53 :param interface: Interface name.
54 :param address: IPv4 address.
55 :param prefix_length: IPv4 prefix length.
58 :type prefix_length: int
64 def set_route(self, network, prefix_length, gateway, interface):
65 """Configure IPv4 route.
67 :param network: Network IPv4 address.
68 :param prefix_length: IPv4 prefix length.
69 :param gateway: IPv4 address of the gateway.
70 :param interface: Interface name.
72 :type prefix_length: int
80 def unset_route(self, network, prefix_length, gateway, interface):
81 """Remove specified IPv4 route.
83 :param network: Network IPv4 address.
84 :param prefix_length: IPv4 prefix length.
85 :param gateway: IPv4 address of the gateway.
86 :param interface: Interface name.
88 :type prefix_length: int
96 def flush_ip_addresses(self, interface):
97 """Flush all IPv4 addresses from specified interface.
99 :param interface: Interface name.
106 def ping(self, destination_address, source_interface):
107 """Send an ICMP request to destination node.
109 :param destination_address: Address to send the ICMP request.
110 :param source_interface: Source interface name.
111 :type destination_address: str
112 :type source_interface: str
119 """Traffic generator node"""
120 def __init__(self, node_info):
121 super(Tg, self).__init__(node_info)
123 def _execute(self, cmd):
124 """Executes the specified command on TG using SSH.
126 :param cmd: Command to be executed.
129 :return: Content of stdout and stderr returned by command.
132 return exec_cmd_no_error(self.node_info, cmd)
134 def _sudo_execute(self, cmd):
135 """Executes the specified command with sudo on TG using SSH.
137 :param cmd: Command to be executed.
140 :return: Content of stdout and stderr returned by command.
143 return exec_cmd_no_error(self.node_info, cmd, sudo=True)
145 def set_ip(self, interface, address, prefix_length):
146 cmd = 'ip -4 addr flush dev {}'.format(interface)
147 self._sudo_execute(cmd)
148 cmd = 'ip addr add {}/{} dev {}'.format(address, prefix_length,
150 self._sudo_execute(cmd)
152 def set_route(self, network, prefix_length, gateway, interface):
153 netmask = self._get_netmask(prefix_length)
154 cmd = 'route add -net {} netmask {} gw {}'.\
155 format(network, netmask, gateway)
156 self._sudo_execute(cmd)
158 def unset_route(self, network, prefix_length, gateway, interface):
159 self._sudo_execute('ip route delete {}/{}'.
160 format(network, prefix_length))
162 def arp_ping(self, destination_address, source_interface):
163 """Execute 'arping' command to send one ARP packet from the TG node.
165 :param destination_address: Destination IP address for the ARP packet.
166 :param source_interface: Name of an interface to send ARP packet from.
167 :type destination_address: str
168 :type source_interface: str
170 self._sudo_execute('arping -c 1 -I {} {}'.format(source_interface,
171 destination_address))
173 def ping(self, destination_address, source_interface):
174 self._execute('ping -c 1 -w 5 -I {} {}'.format(source_interface,
175 destination_address))
177 def flush_ip_addresses(self, interface):
178 self._sudo_execute('ip addr flush dev {}'.format(interface))
182 """Device under test"""
183 def __init__(self, node_info):
184 super(Dut, self).__init__(node_info)
186 def get_sw_if_index(self, interface):
187 """Get sw_if_index of specified interface from current node.
189 :param interface: Interface name.
191 :return: sw_if_index of the interface or None.
194 return Topology().get_interface_sw_index(self.node_info, interface)
196 def exec_vat(self, script, **args):
197 """Wrapper for VAT executor.
199 :param script: Script to execute.
200 :param args: Parameters to the script.
205 # TODO: check return value
206 VatExecutor.cmd_from_template(self.node_info, script, **args)
208 def set_arp(self, iface_key, ip_address, mac_address, vrf=None):
209 """Set entry in ARP cache.
211 :param iface_key: Interface key.
212 :param ip_address: IP address.
213 :param mac_address: MAC address.
214 :param vrf: VRF table ID (Optional).
216 :type ip_address: str
217 :type mac_address: str
220 vrf = "vrf {}".format(vrf) if vrf else ''
221 self.exec_vat('add_ip_neighbor.vat',
222 sw_if_index=self.get_sw_if_index(iface_key),
223 ip_address=ip_address, mac_address=mac_address,
226 def set_ip(self, interface, address, prefix_length):
227 self.exec_vat('add_ip_address.vat',
228 sw_if_index=self.get_sw_if_index(interface),
229 address=address, prefix_length=prefix_length)
231 def set_route(self, network, prefix_length, gateway, interface, count=1):
232 Routing.vpp_route_add(self.node_info,
233 network=network, prefix_len=prefix_length,
234 gateway=gateway, interface=interface, count=count)
236 def unset_route(self, network, prefix_length, gateway, interface):
237 self.exec_vat('del_route.vat', network=network,
238 prefix_length=prefix_length, gateway=gateway,
239 sw_if_index=self.get_sw_if_index(interface))
241 def arp_ping(self, destination_address, source_interface):
245 def flush_ip_addresses(self, interface):
246 self.exec_vat('flush_ip_addresses.vat',
247 sw_if_index=self.get_sw_if_index(interface))
249 def ping(self, destination_address, source_interface):
253 def get_node(node_info):
254 """Creates a class instance derived from Node based on type.
256 :param node_info: Dictionary containing information on nodes in topology.
257 :type node_info: dict
258 :return: Class instance that is derived from Node.
260 if node_info['type'] == NodeType.TG:
262 elif node_info['type'] == NodeType.DUT:
263 return Dut(node_info)
265 raise NotImplementedError('Node type "{}" unsupported!'.
266 format(node_info['type']))
269 class IPv4Setup(object):
270 """IPv4 setup in topology."""
273 def vpp_nodes_set_ipv4_addresses(nodes, nodes_addr):
274 """Set IPv4 addresses on all VPP nodes in topology.
276 :param nodes: Nodes of the test topology.
277 :param nodes_addr: Available nodes IPv4 addresses.
279 :type nodes_addr: dict
280 :return: Affected interfaces as list of (node, interface) tuples.
284 for net in nodes_addr.values():
285 for port in net['ports'].values():
286 host = port.get('node')
290 node = topo.get_node_by_hostname(nodes, host)
293 if node['type'] != NodeType.DUT:
295 iface_key = topo.get_interface_by_name(node, port['if'])
296 get_node(node).set_ip(iface_key, port['addr'], net['prefix'])
297 interfaces.append((node, port['if']))
302 @keyword('Get IPv4 address of node "${node}" interface "${port}" '
303 'from "${nodes_addr}"')
304 def get_ip_addr(node, iface_key, nodes_addr):
305 """Return IPv4 address of the node port.
307 :param node: Node in the topology.
308 :param iface_key: Interface key of the node.
309 :param nodes_addr: Nodes IPv4 addresses.
312 :type nodes_addr: dict
313 :return: IPv4 address.
316 interface = Topology.get_interface_name(node, iface_key)
317 for net in nodes_addr.values():
318 for port in net['ports'].values():
319 host = port.get('node')
321 if host == node['host'] and dev == interface:
322 ip_addr = port.get('addr')
323 if ip_addr is not None:
327 'Node {n} port {p} IPv4 address is not set'.format(
328 n=node['host'], p=interface))
330 raise Exception('Node {n} port {p} IPv4 address not found.'.format(
331 n=node['host'], p=interface))
334 def setup_arp_on_all_duts(nodes_info, nodes_addr):
335 """For all DUT nodes extract MAC and IP addresses of adjacent
336 interfaces from topology and use them to setup ARP entries.
338 :param nodes_info: Dictionary containing information on all nodes
340 :param nodes_addr: Nodes IPv4 addresses.
341 :type nodes_info: dict
342 :type nodes_addr: dict
344 for node in nodes_info.values():
345 if node['type'] == NodeType.TG:
347 for iface_key in node['interfaces'].keys():
348 adj_node, adj_int = Topology.\
349 get_adjacent_node_and_interface(nodes_info, node, iface_key)
350 ip_address = IPv4Setup.get_ip_addr(adj_node, adj_int,
352 mac_address = Topology.get_interface_mac(adj_node, adj_int)
353 get_node(node).set_arp(iface_key, ip_address, mac_address)
356 def add_arp_on_dut(node, iface_key, ip_address, mac_address, vrf=None):
357 """Set ARP cache entree on DUT node.
359 :param node: VPP Node in the topology.
360 :param iface_key: Interface key.
361 :param ip_address: IP address of the interface.
362 :param mac_address: MAC address of the interface.
363 :param vrf: VRF table ID (Optional).
366 :type ip_address: str
367 :type mac_address: str
370 get_node(node).set_arp(iface_key, ip_address, mac_address, vrf)