make test: improve robustness and performance
[vpp.git] / test / vpp_pg_interface.py
1 import os
2 import time
3 from scapy.utils import wrpcap, rdpcap, PcapReader
4 from vpp_interface import VppInterface
5
6 from scapy.layers.l2 import Ether, ARP
7 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
8     ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr
9 from util import ppp, ppc
10
11
12 class VppPGInterface(VppInterface):
13     """
14     VPP packet-generator interface
15     """
16
17     @property
18     def pg_index(self):
19         """packet-generator interface index assigned by VPP"""
20         return self._pg_index
21
22     @property
23     def out_path(self):
24         """pcap file path - captured packets"""
25         return self._out_path
26
27     @property
28     def in_path(self):
29         """ pcap file path - injected packets"""
30         return self._in_path
31
32     @property
33     def capture_cli(self):
34         """CLI string to start capture on this interface"""
35         return self._capture_cli
36
37     @property
38     def cap_name(self):
39         """capture name for this interface"""
40         return self._cap_name
41
42     @property
43     def input_cli(self):
44         """CLI string to load the injected packets"""
45         return self._input_cli
46
47     @property
48     def in_history_counter(self):
49         """Self-incrementing counter used when renaming old pcap files"""
50         v = self._in_history_counter
51         self._in_history_counter += 1
52         return v
53
54     @property
55     def out_history_counter(self):
56         """Self-incrementing counter used when renaming old pcap files"""
57         v = self._out_history_counter
58         self._out_history_counter += 1
59         return v
60
61     def __init__(self, test, pg_index):
62         """ Create VPP packet-generator interface """
63         r = test.vapi.pg_create_interface(pg_index)
64         self._sw_if_index = r.sw_if_index
65
66         super(VppPGInterface, self).__init__(test)
67
68         self._in_history_counter = 0
69         self._out_history_counter = 0
70         self._pg_index = pg_index
71         self._out_file = "pg%u_out.pcap" % self.pg_index
72         self._out_path = self.test.tempdir + "/" + self._out_file
73         self._in_file = "pg%u_in.pcap" % self.pg_index
74         self._in_path = self.test.tempdir + "/" + self._in_file
75         self._capture_cli = "packet-generator capture pg%u pcap %s" % (
76             self.pg_index, self.out_path)
77         self._cap_name = "pcap%u" % self.sw_if_index
78         self._input_cli = "packet-generator new pcap %s source pg%u name %s" % (
79             self.in_path, self.pg_index, self.cap_name)
80
81     def enable_capture(self):
82         """ Enable capture on this packet-generator interface"""
83         try:
84             if os.path.isfile(self.out_path):
85                 os.rename(self.out_path,
86                           "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
87                           (self.test.tempdir,
88                            time.time(),
89                            self.name,
90                            self.out_history_counter,
91                            self._out_file))
92         except:
93             pass
94         # FIXME this should be an API, but no such exists atm
95         self.test.vapi.cli(self.capture_cli)
96         self._pcap_reader = None
97
98     def add_stream(self, pkts):
99         """
100         Add a stream of packets to this packet-generator
101
102         :param pkts: iterable packets
103
104         """
105         try:
106             if os.path.isfile(self.in_path):
107                 os.rename(self.in_path,
108                           "%s/history.[timestamp:%f].[%s-counter:%04d].%s" %
109                           (self.test.tempdir,
110                            time.time(),
111                            self.name,
112                            self.in_history_counter,
113                            self._in_file))
114         except:
115             pass
116         wrpcap(self.in_path, pkts)
117         self.test.register_capture(self.cap_name)
118         # FIXME this should be an API, but no such exists atm
119         self.test.vapi.cli(self.input_cli)
120
121     def get_capture(self, remark=None):
122         """
123         Get captured packets
124
125         :returns: iterable packets
126         """
127         try:
128             self.wait_for_capture_file()
129             output = rdpcap(self.out_path)
130         except IOError:  # TODO
131             self.test.logger.debug("File %s does not exist, probably because no"
132                                    " packets arrived" % self.out_path)
133             if remark:
134                 raise Exception("No packets captured on %s(%s)" %
135                                 (self.name, remark))
136             else:
137                 raise Exception("No packets captured on %s" % self.name)
138         return output
139
140     def assert_nothing_captured(self, remark=None):
141         if os.path.isfile(self.out_path):
142             try:
143                 capture = self.get_capture()
144                 self.test.logger.error(
145                     ppc("Unexpected packets captured:", capture))
146             except:
147                 pass
148             if remark:
149                 raise AssertionError(
150                     "Capture file present for interface %s(%s)" %
151                     (self.name, remark))
152             else:
153                 raise AssertionError("Capture file present for interface %s" %
154                                      self.name)
155
156     def wait_for_capture_file(self, timeout=1):
157         """
158         Wait until pcap capture file appears
159
160         :param timeout: How long to wait for the packet (default 1s)
161
162         :raises Exception: if the capture file does not appear within timeout
163         """
164         limit = time.time() + timeout
165         if not os.path.isfile(self.out_path):
166             self.test.logger.debug(
167                 "Waiting for capture file to appear, timeout is %ss", timeout)
168         else:
169             self.test.logger.debug("Capture file already exists")
170             return
171         while time.time() < limit:
172             if os.path.isfile(self.out_path):
173                 break
174             time.sleep(0)  # yield
175         if os.path.isfile(self.out_path):
176             self.test.logger.debug("Capture file appeared after %fs" %
177                                    (time.time() - (limit - timeout)))
178         else:
179             self.test.logger.debug("Timeout - capture file still nowhere")
180             raise Exception("Capture file did not appear within timeout")
181
182     def wait_for_packet(self, timeout):
183         """
184         Wait for next packet captured with a timeout
185
186         :param timeout: How long to wait for the packet
187
188         :returns: Captured packet if no packet arrived within timeout
189         :raises Exception: if no packet arrives within timeout
190         """
191         limit = time.time() + timeout
192         if self._pcap_reader is None:
193             self.wait_for_capture_file(timeout)
194             self._pcap_reader = PcapReader(self.out_path)
195
196         self.test.logger.debug("Waiting for packet")
197         while time.time() < limit:
198             p = self._pcap_reader.recv()
199             if p is not None:
200                 self.test.logger.debug("Packet received after %fs",
201                                        (time.time() - (limit - timeout)))
202                 return p
203             time.sleep(0)  # yield
204         self.test.logger.debug("Timeout - no packets received")
205         raise Exception("Packet didn't arrive within timeout")
206
207     def create_arp_req(self):
208         """Create ARP request applicable for this interface"""
209         return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
210                 ARP(op=ARP.who_has, pdst=self.local_ip4,
211                     psrc=self.remote_ip4, hwsrc=self.remote_mac))
212
213     def create_ndp_req(self):
214         """Create NDP - NS applicable for this interface"""
215         return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
216                 IPv6(src=self.remote_ip6, dst=self.local_ip6) /
217                 ICMPv6ND_NS(tgt=self.local_ip6) /
218                 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
219
220     def resolve_arp(self, pg_interface=None):
221         """Resolve ARP using provided packet-generator interface
222
223         :param pg_interface: interface used to resolve, if None then this
224             interface is used
225
226         """
227         if pg_interface is None:
228             pg_interface = self
229         self.test.logger.info("Sending ARP request for %s on port %s" %
230                               (self.local_ip4, pg_interface.name))
231         arp_req = self.create_arp_req()
232         pg_interface.add_stream(arp_req)
233         pg_interface.enable_capture()
234         self.test.pg_start()
235         self.test.logger.info(self.test.vapi.cli("show trace"))
236         try:
237             arp_reply = pg_interface.get_capture()
238         except:
239             self.test.logger.info("No ARP received on port %s" %
240                                   pg_interface.name)
241             return
242         arp_reply = arp_reply[0]
243         # Make Dot1AD packet content recognizable to scapy
244         if arp_reply.type == 0x88a8:
245             arp_reply.type = 0x8100
246             arp_reply = Ether(str(arp_reply))
247         try:
248             if arp_reply[ARP].op == ARP.is_at:
249                 self.test.logger.info("VPP %s MAC address is %s " %
250                                       (self.name, arp_reply[ARP].hwsrc))
251                 self._local_mac = arp_reply[ARP].hwsrc
252             else:
253                 self.test.logger.info(
254                     "No ARP received on port %s" %
255                     pg_interface.name)
256         except:
257             self.test.logger.error(
258                 ppp("Unexpected response to ARP request:", arp_reply))
259             raise
260
261     def resolve_ndp(self, pg_interface=None):
262         """Resolve NDP using provided packet-generator interface
263
264         :param pg_interface: interface used to resolve, if None then this
265             interface is used
266
267         """
268         if pg_interface is None:
269             pg_interface = self
270         self.test.logger.info("Sending NDP request for %s on port %s" %
271                               (self.local_ip6, pg_interface.name))
272         ndp_req = self.create_ndp_req()
273         pg_interface.add_stream(ndp_req)
274         pg_interface.enable_capture()
275         self.test.pg_start()
276         self.test.logger.info(self.test.vapi.cli("show trace"))
277         replies = pg_interface.get_capture()
278         if replies is None or len(replies) == 0:
279             self.test.logger.info(
280                 "No NDP received on port %s" %
281                 pg_interface.name)
282             return
283         # Enabling IPv6 on an interface can generate more than the
284         # ND reply we are looking for (namely MLD). So loop through
285         # the replies to look for want we want.
286         for ndp_reply in replies:
287             # Make Dot1AD packet content recognizable to scapy
288             if ndp_reply.type == 0x88a8:
289                 ndp_reply.type = 0x8100
290                 ndp_reply = Ether(str(ndp_reply))
291             try:
292                 ndp_na = ndp_reply[ICMPv6ND_NA]
293                 opt = ndp_na[ICMPv6NDOptDstLLAddr]
294                 self.test.logger.info("VPP %s MAC address is %s " %
295                                       (self.name, opt.lladdr))
296                 self._local_mac = opt.lladdr
297             except:
298                 self.test.logger.info(
299                     ppp("Unexpected response to NDP request:", ndp_reply))
300         # if no packets above provided the local MAC, then this failed.
301         if not hasattr(self, '_local_mac'):
302             raise