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
41 :returns: Network mask.
45 bits = 0xffffffff ^ (1 << 32 - prefix_length) - 1
46 return inet_ntoa(pack('>I', bits))
49 def set_ip(self, interface, address, prefix_length):
50 """Configure IPv4 address on interface.
52 :param interface: Interface name.
53 :param address: IPv4 address.
54 :param prefix_length: IPv4 prefix length.
57 :type prefix_length: int
63 def set_route(self, network, prefix_length, gateway, interface):
64 """Configure IPv4 route.
66 :param network: Network IPv4 address.
67 :param prefix_length: IPv4 prefix length.
68 :param gateway: IPv4 address of the gateway.
69 :param interface: Interface name.
71 :type prefix_length: int
79 def unset_route(self, network, prefix_length, gateway, interface):
80 """Remove specified IPv4 route.
82 :param network: Network IPv4 address.
83 :param prefix_length: IPv4 prefix length.
84 :param gateway: IPv4 address of the gateway.
85 :param interface: Interface name.
87 :type prefix_length: int
95 def flush_ip_addresses(self, interface):
96 """Flush all IPv4 addresses from specified interface.
98 :param interface: Interface name.
105 def ping(self, destination_address, source_interface):
106 """Send an ICMP request to destination node.
108 :param destination_address: Address to send the ICMP request.
109 :param source_interface: Source interface name.
110 :type destination_address: str
111 :type source_interface: str
118 """Traffic generator node"""
119 def __init__(self, node_info):
120 super(Tg, self).__init__(node_info)
122 def _execute(self, cmd):
123 """Executes the specified command on TG using SSH.
125 :param cmd: Command to be executed.
127 :returns: Content of stdout and stderr returned by command.
130 return exec_cmd_no_error(self.node_info, cmd)
132 def _sudo_execute(self, cmd):
133 """Executes the specified command with sudo on TG using SSH.
135 :param cmd: Command to be executed.
137 :returns: Content of stdout and stderr returned by command.
140 return exec_cmd_no_error(self.node_info, cmd, sudo=True)
142 def set_ip(self, interface, address, prefix_length):
143 cmd = 'ip -4 addr flush dev {}'.format(interface)
144 self._sudo_execute(cmd)
145 cmd = 'ip addr add {}/{} dev {}'.format(address, prefix_length,
147 self._sudo_execute(cmd)
149 def set_route(self, network, prefix_length, gateway, interface):
150 netmask = self._get_netmask(prefix_length)
151 cmd = 'route add -net {} netmask {} gw {}'.\
152 format(network, netmask, gateway)
153 self._sudo_execute(cmd)
155 def unset_route(self, network, prefix_length, gateway, interface):
156 self._sudo_execute('ip route delete {}/{}'.
157 format(network, prefix_length))
159 def arp_ping(self, destination_address, source_interface):
160 """Execute 'arping' command to send one ARP packet from the TG node.
162 :param destination_address: Destination IP address for the ARP packet.
163 :param source_interface: Name of an interface to send ARP packet from.
164 :type destination_address: str
165 :type source_interface: str
167 self._sudo_execute('arping -c 1 -I {} {}'.format(source_interface,
168 destination_address))
170 def ping(self, destination_address, source_interface):
171 self._execute('ping -c 1 -w 5 -I {} {}'.format(source_interface,
172 destination_address))
174 def flush_ip_addresses(self, interface):
175 self._sudo_execute('ip addr flush dev {}'.format(interface))
179 """Device under test"""
180 def __init__(self, node_info):
181 super(Dut, self).__init__(node_info)
183 def get_sw_if_index(self, interface):
184 """Get sw_if_index of specified interface from current node.
186 :param interface: Interface name.
188 :returns: sw_if_index of the interface or None.
191 return Topology().get_interface_sw_index(self.node_info, interface)
193 def exec_vat(self, script, **args):
194 """Wrapper for VAT executor.
196 :param script: Script to execute.
197 :param args: Parameters to the script.
202 # TODO: check return value
203 VatExecutor.cmd_from_template(self.node_info, script, **args)
205 def set_arp(self, iface_key, ip_address, mac_address):
206 """Set entry in ARP cache.
208 :param iface_key: Interface key.
209 :param ip_address: IP address.
210 :param mac_address: MAC address.
212 :type ip_address: str
213 :type mac_address: str
215 self.exec_vat('add_ip_neighbor.vat',
216 sw_if_index=self.get_sw_if_index(iface_key),
217 ip_address=ip_address, mac_address=mac_address)
219 def set_ip(self, interface, address, prefix_length):
220 self.exec_vat('add_ip_address.vat',
221 sw_if_index=self.get_sw_if_index(interface),
222 address=address, prefix_length=prefix_length)
224 def set_route(self, network, prefix_length, gateway, interface, count=1):
225 Routing.vpp_route_add(self.node_info,
226 network=network, prefix_len=prefix_length,
227 gateway=gateway, interface=interface, count=count)
229 def unset_route(self, network, prefix_length, gateway, interface):
230 self.exec_vat('del_route.vat', network=network,
231 prefix_length=prefix_length, gateway=gateway,
232 sw_if_index=self.get_sw_if_index(interface))
234 def arp_ping(self, destination_address, source_interface):
238 def flush_ip_addresses(self, interface):
239 self.exec_vat('flush_ip_addresses.vat',
240 sw_if_index=self.get_sw_if_index(interface))
242 def ping(self, destination_address, source_interface):
246 def get_node(node_info):
247 """Creates a class instance derived from Node based on type.
249 :param node_info: Dictionary containing information on nodes in topology.
250 :type node_info: dict
251 :returns: Class instance that is derived from Node.
253 if node_info['type'] == NodeType.TG:
255 elif node_info['type'] == NodeType.DUT:
256 return Dut(node_info)
258 raise NotImplementedError('Node type "{}" unsupported!'.
259 format(node_info['type']))
262 class IPv4Setup(object):
263 """IPv4 setup in topology."""
266 def vpp_nodes_set_ipv4_addresses(nodes, nodes_addr):
267 """Set IPv4 addresses on all VPP nodes in topology.
269 :param nodes: Nodes of the test topology.
270 :param nodes_addr: Available nodes IPv4 addresses.
272 :type nodes_addr: dict
273 :returns: Affected interfaces as list of (node, interface) tuples.
277 for net in nodes_addr.values():
278 for port in net['ports'].values():
279 host = port.get('node')
283 node = topo.get_node_by_hostname(nodes, host)
286 if node['type'] != NodeType.DUT:
288 iface_key = topo.get_interface_by_name(node, port['if'])
289 get_node(node).set_ip(iface_key, port['addr'], net['prefix'])
290 interfaces.append((node, port['if']))
295 @keyword('Get IPv4 address of node "${node}" interface "${port}" '
296 'from "${nodes_addr}"')
297 def get_ip_addr(node, iface_key, nodes_addr):
298 """Return IPv4 address of the node port.
300 :param node: Node in the topology.
301 :param iface_key: Interface key of the node.
302 :param nodes_addr: Nodes IPv4 addresses.
305 :type nodes_addr: dict
306 :returns: IPv4 address.
309 interface = Topology.get_interface_name(node, iface_key)
310 for net in nodes_addr.values():
311 for port in net['ports'].values():
312 host = port.get('node')
314 if host == node['host'] and dev == interface:
315 ip_addr = port.get('addr')
316 if ip_addr is not None:
320 'Node {n} port {p} IPv4 address is not set'.format(
321 n=node['host'], p=interface))
323 raise Exception('Node {n} port {p} IPv4 address not found.'.format(
324 n=node['host'], p=interface))
327 def setup_arp_on_all_duts(nodes_info, nodes_addr):
328 """For all DUT nodes extract MAC and IP addresses of adjacent
329 interfaces from topology and use them to setup ARP entries.
331 :param nodes_info: Dictionary containing information on all nodes
333 :param nodes_addr: Nodes IPv4 addresses.
334 :type nodes_info: dict
335 :type nodes_addr: dict
337 for node in nodes_info.values():
338 if node['type'] == NodeType.TG:
340 for iface_key in node['interfaces'].keys():
341 adj_node, adj_int = Topology.\
342 get_adjacent_node_and_interface(nodes_info, node, iface_key)
343 ip_address = IPv4Setup.get_ip_addr(adj_node, adj_int,
345 mac_address = Topology.get_interface_mac(adj_node, adj_int)
346 get_node(node).set_arp(iface_key, ip_address, mac_address)
349 def add_arp_on_dut(node, iface_key, ip_address, mac_address):
350 """Set ARP cache entree on DUT node.
352 :param node: VPP Node in the topology.
353 :param iface_key: Interface key.
354 :param ip_address: IP address of the interface.
355 :param mac_address: MAC address of the interface.
358 :type ip_address: str
359 :type mac_address: str
361 get_node(node).set_arp(iface_key, ip_address, mac_address)