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, vrf=None):
206 """Set entry in ARP cache.
208 :param iface_key: Interface key.
209 :param ip_address: IP address.
210 :param mac_address: MAC address.
211 :param vrf: VRF table ID (Optional).
213 :type ip_address: str
214 :type mac_address: str
217 vrf = "vrf {}".format(vrf) if vrf else ''
218 self.exec_vat('add_ip_neighbor.vat',
219 sw_if_index=self.get_sw_if_index(iface_key),
220 ip_address=ip_address, mac_address=mac_address,
223 def set_ip(self, interface, address, prefix_length):
224 self.exec_vat('add_ip_address.vat',
225 sw_if_index=self.get_sw_if_index(interface),
226 address=address, prefix_length=prefix_length)
228 def set_route(self, network, prefix_length, gateway, interface, count=1):
229 Routing.vpp_route_add(self.node_info,
230 network=network, prefix_len=prefix_length,
231 gateway=gateway, interface=interface, count=count)
233 def unset_route(self, network, prefix_length, gateway, interface):
234 self.exec_vat('del_route.vat', network=network,
235 prefix_length=prefix_length, gateway=gateway,
236 sw_if_index=self.get_sw_if_index(interface))
238 def arp_ping(self, destination_address, source_interface):
242 def flush_ip_addresses(self, interface):
243 self.exec_vat('flush_ip_addresses.vat',
244 sw_if_index=self.get_sw_if_index(interface))
246 def ping(self, destination_address, source_interface):
250 def get_node(node_info):
251 """Creates a class instance derived from Node based on type.
253 :param node_info: Dictionary containing information on nodes in topology.
254 :type node_info: dict
255 :returns: Class instance that is derived from Node.
257 if node_info['type'] == NodeType.TG:
259 elif node_info['type'] == NodeType.DUT:
260 return Dut(node_info)
262 raise NotImplementedError('Node type "{}" unsupported!'.
263 format(node_info['type']))
266 class IPv4Setup(object):
267 """IPv4 setup in topology."""
270 def vpp_nodes_set_ipv4_addresses(nodes, nodes_addr):
271 """Set IPv4 addresses on all VPP nodes in topology.
273 :param nodes: Nodes of the test topology.
274 :param nodes_addr: Available nodes IPv4 addresses.
276 :type nodes_addr: dict
277 :returns: Affected interfaces as list of (node, interface) tuples.
281 for net in nodes_addr.values():
282 for port in net['ports'].values():
283 host = port.get('node')
287 node = topo.get_node_by_hostname(nodes, host)
290 if node['type'] != NodeType.DUT:
292 iface_key = topo.get_interface_by_name(node, port['if'])
293 get_node(node).set_ip(iface_key, port['addr'], net['prefix'])
294 interfaces.append((node, port['if']))
299 @keyword('Get IPv4 address of node "${node}" interface "${port}" '
300 'from "${nodes_addr}"')
301 def get_ip_addr(node, iface_key, nodes_addr):
302 """Return IPv4 address of the node port.
304 :param node: Node in the topology.
305 :param iface_key: Interface key of the node.
306 :param nodes_addr: Nodes IPv4 addresses.
309 :type nodes_addr: dict
310 :returns: IPv4 address.
313 interface = Topology.get_interface_name(node, iface_key)
314 for net in nodes_addr.values():
315 for port in net['ports'].values():
316 host = port.get('node')
318 if host == node['host'] and dev == interface:
319 ip_addr = port.get('addr')
320 if ip_addr is not None:
324 'Node {n} port {p} IPv4 address is not set'.format(
325 n=node['host'], p=interface))
327 raise Exception('Node {n} port {p} IPv4 address not found.'.format(
328 n=node['host'], p=interface))
331 def setup_arp_on_all_duts(nodes_info, nodes_addr):
332 """For all DUT nodes extract MAC and IP addresses of adjacent
333 interfaces from topology and use them to setup ARP entries.
335 :param nodes_info: Dictionary containing information on all nodes
337 :param nodes_addr: Nodes IPv4 addresses.
338 :type nodes_info: dict
339 :type nodes_addr: dict
341 for node in nodes_info.values():
342 if node['type'] == NodeType.TG:
344 for iface_key in node['interfaces'].keys():
345 adj_node, adj_int = Topology.\
346 get_adjacent_node_and_interface(nodes_info, node, iface_key)
347 ip_address = IPv4Setup.get_ip_addr(adj_node, adj_int,
349 mac_address = Topology.get_interface_mac(adj_node, adj_int)
350 get_node(node).set_arp(iface_key, ip_address, mac_address)
353 def add_arp_on_dut(node, iface_key, ip_address, mac_address, vrf=None):
354 """Set ARP cache entree on DUT node.
356 :param node: VPP Node in the topology.
357 :param iface_key: Interface key.
358 :param ip_address: IP address of the interface.
359 :param mac_address: MAC address of the interface.
360 :param vrf: VRF table ID (Optional).
363 :type ip_address: str
364 :type mac_address: str
367 get_node(node).set_arp(iface_key, ip_address, mac_address, vrf)