lb: remove api boilerplate
[vpp.git] / test / vpp_pg_interface.py
1 import os
2 import time
3 import socket
4 import struct
5 from traceback import format_exc, format_stack
6
7 import scapy.compat
8 from scapy.utils import wrpcap, rdpcap, PcapReader
9 from scapy.plist import PacketList
10 from vpp_interface import VppInterface
11
12 from scapy.layers.l2 import Ether, ARP
13 from scapy.layers.inet6 import IPv6, ICMPv6ND_NS, ICMPv6ND_NA,\
14     ICMPv6NDOptSrcLLAddr, ICMPv6NDOptDstLLAddr, ICMPv6ND_RA, RouterAlert, \
15     IPv6ExtHdrHopByHop
16 from util import ppp, ppc
17 from scapy.utils6 import in6_getnsma, in6_getnsmac, in6_ismaddr
18 from scapy.utils import inet_pton, inet_ntop
19
20
21 class CaptureTimeoutError(Exception):
22     """ Exception raised if capture or packet doesn't appear within timeout """
23     pass
24
25
26 def is_ipv6_misc(p):
27     """ Is packet one of uninteresting IPv6 broadcasts? """
28     if p.haslayer(ICMPv6ND_RA):
29         if in6_ismaddr(p[IPv6].dst):
30             return True
31     if p.haslayer(IPv6ExtHdrHopByHop):
32         for o in p[IPv6ExtHdrHopByHop].options:
33             if isinstance(o, RouterAlert):
34                 return True
35     return False
36
37
38 class VppPGInterface(VppInterface):
39     """
40     VPP packet-generator interface
41     """
42
43     @property
44     def pg_index(self):
45         """packet-generator interface index assigned by VPP"""
46         return self._pg_index
47
48     @property
49     def gso_enabled(self):
50         """gso enabled on packet-generator interface"""
51         if self._gso_enabled == 0:
52             return "gso-disabled"
53         return "gso-enabled"
54
55     @property
56     def gso_size(self):
57         """gso size on packet-generator interface"""
58         return self._gso_size
59
60     @property
61     def out_path(self):
62         """pcap file path - captured packets"""
63         return self._out_path
64
65     @property
66     def in_path(self):
67         """ pcap file path - injected packets"""
68         return self._in_path
69
70     @property
71     def capture_cli(self):
72         """CLI string to start capture on this interface"""
73         return self._capture_cli
74
75     @property
76     def cap_name(self):
77         """capture name for this interface"""
78         return self._cap_name
79
80     @property
81     def input_cli(self):
82         """CLI string to load the injected packets"""
83         if self._nb_replays is not None:
84             return "%s limit %d" % (self._input_cli, self._nb_replays)
85         if self._worker is not None:
86             return "%s worker %d" % (self._input_cli, self._worker)
87         return self._input_cli
88
89     @property
90     def in_history_counter(self):
91         """Self-incrementing counter used when renaming old pcap files"""
92         v = self._in_history_counter
93         self._in_history_counter += 1
94         return v
95
96     @property
97     def out_history_counter(self):
98         """Self-incrementing counter used when renaming old pcap files"""
99         v = self._out_history_counter
100         self._out_history_counter += 1
101         return v
102
103     def __init__(self, test, pg_index, gso, gso_size):
104         """ Create VPP packet-generator interface """
105         super(VppPGInterface, self).__init__(test)
106
107         r = test.vapi.pg_create_interface(pg_index, gso, gso_size)
108         self.set_sw_if_index(r.sw_if_index)
109
110         self._in_history_counter = 0
111         self._out_history_counter = 0
112         self._out_assert_counter = 0
113         self._pg_index = pg_index
114         self._gso_enabled = gso
115         self._gso_size = gso_size
116         self._out_file = "pg%u_out.pcap" % self.pg_index
117         self._out_path = self.test.tempdir + "/" + self._out_file
118         self._in_file = "pg%u_in.pcap" % self.pg_index
119         self._in_path = self.test.tempdir + "/" + self._in_file
120         self._capture_cli = "packet-generator capture pg%u pcap %s" % (
121             self.pg_index, self.out_path)
122         self._cap_name = "pcap%u-sw_if_index-%s" % (
123             self.pg_index, self.sw_if_index)
124         self._input_cli = \
125             "packet-generator new pcap %s source pg%u name %s" % (
126                 self.in_path, self.pg_index, self.cap_name)
127         self._nb_replays = None
128
129     def _rename_previous_capture_file(self, path, counter, file):
130         # if a file from a previous capture exists, rename it.
131         try:
132             if os.path.isfile(path):
133                 name = "%s/history.[timestamp:%f].[%s-counter:%04d].%s" % \
134                     (self.test.tempdir,
135                      time.time(),
136                      self.name,
137                      counter,
138                      file)
139                 self.test.logger.debug("Renaming %s->%s" %
140                                        (path, name))
141                 os.rename(path, name)
142         except OSError:
143             self.test.logger.debug("OSError: Could not rename %s %s" %
144                                    (path, file))
145
146     def enable_capture(self):
147         """ Enable capture on this packet-generator interface
148             of at most n packets.
149             If n < 0, this is no limit
150         """
151         # disable the capture to flush the capture
152         self.disable_capture()
153         self._rename_previous_capture_file(self.out_path,
154                                            self.out_history_counter,
155                                            self._out_file)
156         # FIXME this should be an API, but no such exists atm
157         self.test.vapi.cli(self.capture_cli)
158         self._pcap_reader = None
159
160     def disable_capture(self):
161         self.test.vapi.cli("%s disable" % self.capture_cli)
162
163     def add_stream(self, pkts, nb_replays=None, worker=None):
164         """
165         Add a stream of packets to this packet-generator
166
167         :param pkts: iterable packets
168
169         """
170         self._worker = worker
171         self._nb_replays = nb_replays
172         self._rename_previous_capture_file(self.in_path,
173                                            self.in_history_counter,
174                                            self._in_file)
175         wrpcap(self.in_path, pkts)
176         self.test.register_capture(self.cap_name)
177         # FIXME this should be an API, but no such exists atm
178         self.test.vapi.cli(self.input_cli)
179
180     def generate_debug_aid(self, kind):
181         """ Create a hardlink to the out file with a counter and a file
182         containing stack trace to ease debugging in case of multiple capture
183         files present. """
184         self.test.logger.debug("Generating debug aid for %s on %s" %
185                                (kind, self._name))
186         link_path, stack_path = ["%s/debug_%s_%s_%s.%s" %
187                                  (self.test.tempdir, self._name,
188                                   self._out_assert_counter, kind, suffix)
189                                  for suffix in ["pcap", "stack"]
190                                  ]
191         os.link(self.out_path, link_path)
192         with open(stack_path, "w") as f:
193             f.writelines(format_stack())
194         self._out_assert_counter += 1
195
196     def _get_capture(self, timeout, filter_out_fn=is_ipv6_misc):
197         """ Helper method to get capture and filter it """
198         try:
199             if not self.wait_for_capture_file(timeout):
200                 return None
201             output = rdpcap(self.out_path)
202             self.test.logger.debug("Capture has %s packets" % len(output.res))
203         except:
204             self.test.logger.debug("Exception in scapy.rdpcap (%s): %s" %
205                                    (self.out_path, format_exc()))
206             return None
207         before = len(output.res)
208         if filter_out_fn:
209             output.res = [p for p in output.res if not filter_out_fn(p)]
210         removed = before - len(output.res)
211         if removed:
212             self.test.logger.debug(
213                 "Filtered out %s packets from capture (returning %s)" %
214                 (removed, len(output.res)))
215         return output
216
217     def get_capture(self, expected_count=None, remark=None, timeout=1,
218                     filter_out_fn=is_ipv6_misc):
219         """ Get captured packets
220
221         :param expected_count: expected number of packets to capture, if None,
222                                then self.test.packet_count_for_dst_pg_idx is
223                                used to lookup the expected count
224         :param remark: remark printed into debug logs
225         :param timeout: how long to wait for packets
226         :param filter_out_fn: filter applied to each packet, packets for which
227                               the filter returns True are removed from capture
228         :returns: iterable packets
229         """
230         remaining_time = timeout
231         capture = None
232         name = self.name if remark is None else "%s (%s)" % (self.name, remark)
233         based_on = "based on provided argument"
234         if expected_count is None:
235             expected_count = \
236                 self.test.get_packet_count_for_if_idx(self.sw_if_index)
237             based_on = "based on stored packet_infos"
238             if expected_count == 0:
239                 raise Exception(
240                     "Internal error, expected packet count for %s is 0!" %
241                     name)
242         self.test.logger.debug("Expecting to capture %s (%s) packets on %s" % (
243             expected_count, based_on, name))
244         while remaining_time > 0:
245             before = time.time()
246             capture = self._get_capture(remaining_time, filter_out_fn)
247             elapsed_time = time.time() - before
248             if capture:
249                 if len(capture.res) == expected_count:
250                     # bingo, got the packets we expected
251                     return capture
252                 elif len(capture.res) > expected_count:
253                     self.test.logger.error(
254                         ppc("Unexpected packets captured:", capture))
255                     break
256                 else:
257                     self.test.logger.debug("Partial capture containing %s "
258                                            "packets doesn't match expected "
259                                            "count %s (yet?)" %
260                                            (len(capture.res), expected_count))
261             elif expected_count == 0:
262                 # bingo, got None as we expected - return empty capture
263                 return PacketList()
264             remaining_time -= elapsed_time
265         if capture:
266             self.generate_debug_aid("count-mismatch")
267             raise Exception("Captured packets mismatch, captured %s packets, "
268                             "expected %s packets on %s" %
269                             (len(capture.res), expected_count, name))
270         else:
271             raise Exception("No packets captured on %s" % name)
272
273     def assert_nothing_captured(self, remark=None, filter_out_fn=is_ipv6_misc):
274         """ Assert that nothing unfiltered was captured on interface
275
276         :param remark: remark printed into debug logs
277         :param filter_out_fn: filter applied to each packet, packets for which
278                               the filter returns True are removed from capture
279         """
280         if os.path.isfile(self.out_path):
281             try:
282                 capture = self.get_capture(
283                     0, remark=remark, filter_out_fn=filter_out_fn)
284                 if not capture or len(capture.res) == 0:
285                     # junk filtered out, we're good
286                     return
287             except:
288                 pass
289             self.generate_debug_aid("empty-assert")
290             if remark:
291                 raise AssertionError(
292                     "Non-empty capture file present for interface %s (%s)" %
293                     (self.name, remark))
294             else:
295                 raise AssertionError("Capture file present for interface %s" %
296                                      self.name)
297
298     def wait_for_capture_file(self, timeout=1):
299         """
300         Wait until pcap capture file appears
301
302         :param timeout: How long to wait for the packet (default 1s)
303
304         :returns: True/False if the file is present or appears within timeout
305         """
306         deadline = time.time() + timeout
307         if not os.path.isfile(self.out_path):
308             self.test.logger.debug("Waiting for capture file %s to appear, "
309                                    "timeout is %ss" % (self.out_path, timeout))
310         else:
311             self.test.logger.debug("Capture file %s already exists" %
312                                    self.out_path)
313             return True
314         while time.time() < deadline:
315             if os.path.isfile(self.out_path):
316                 break
317             self._test.sleep(0)  # yield
318         if os.path.isfile(self.out_path):
319             self.test.logger.debug("Capture file appeared after %fs" %
320                                    (time.time() - (deadline - timeout)))
321         else:
322             self.test.logger.debug("Timeout - capture file still nowhere")
323             return False
324         return True
325
326     def verify_enough_packet_data_in_pcap(self):
327         """
328         Check if enough data is available in file handled by internal pcap
329         reader so that a whole packet can be read.
330
331         :returns: True if enough data present, else False
332         """
333         orig_pos = self._pcap_reader.f.tell()  # save file position
334         enough_data = False
335         # read packet header from pcap
336         packet_header_size = 16
337         caplen = None
338         end_pos = None
339         hdr = self._pcap_reader.f.read(packet_header_size)
340         if len(hdr) == packet_header_size:
341             # parse the capture length - caplen
342             sec, usec, caplen, wirelen = struct.unpack(
343                 self._pcap_reader.endian + "IIII", hdr)
344             self._pcap_reader.f.seek(0, 2)  # seek to end of file
345             end_pos = self._pcap_reader.f.tell()  # get position at end
346             if end_pos >= orig_pos + len(hdr) + caplen:
347                 enough_data = True  # yay, we have enough data
348         self._pcap_reader.f.seek(orig_pos, 0)  # restore original position
349         return enough_data
350
351     def wait_for_packet(self, timeout, filter_out_fn=is_ipv6_misc):
352         """
353         Wait for next packet captured with a timeout
354
355         :param timeout: How long to wait for the packet
356
357         :returns: Captured packet if no packet arrived within timeout
358         :raises Exception: if no packet arrives within timeout
359         """
360         deadline = time.time() + timeout
361         if self._pcap_reader is None:
362             if not self.wait_for_capture_file(timeout):
363                 raise CaptureTimeoutError("Capture file %s did not appear "
364                                           "within timeout" % self.out_path)
365             while time.time() < deadline:
366                 try:
367                     self._pcap_reader = PcapReader(self.out_path)
368                     break
369                 except:
370                     self.test.logger.debug(
371                         "Exception in scapy.PcapReader(%s): %s" %
372                         (self.out_path, format_exc()))
373         if not self._pcap_reader:
374             raise CaptureTimeoutError("Capture file %s did not appear within "
375                                       "timeout" % self.out_path)
376
377         poll = False
378         if timeout > 0:
379             self.test.logger.debug("Waiting for packet")
380         else:
381             poll = True
382             self.test.logger.debug("Polling for packet")
383         while time.time() < deadline or poll:
384             if not self.verify_enough_packet_data_in_pcap():
385                 self._test.sleep(0)  # yield
386                 poll = False
387                 continue
388             p = self._pcap_reader.recv()
389             if p is not None:
390                 if filter_out_fn is not None and filter_out_fn(p):
391                     self.test.logger.debug(
392                         "Packet received after %ss was filtered out" %
393                         (time.time() - (deadline - timeout)))
394                 else:
395                     self.test.logger.debug(
396                         "Packet received after %fs" %
397                         (time.time() - (deadline - timeout)))
398                     return p
399             self._test.sleep(0)  # yield
400             poll = False
401         self.test.logger.debug("Timeout - no packets received")
402         raise CaptureTimeoutError("Packet didn't arrive within timeout")
403
404     def create_arp_req(self):
405         """Create ARP request applicable for this interface"""
406         return (Ether(dst="ff:ff:ff:ff:ff:ff", src=self.remote_mac) /
407                 ARP(op=ARP.who_has, pdst=self.local_ip4,
408                     psrc=self.remote_ip4, hwsrc=self.remote_mac))
409
410     def create_ndp_req(self):
411         """Create NDP - NS applicable for this interface"""
412         nsma = in6_getnsma(inet_pton(socket.AF_INET6, self.local_ip6))
413         d = inet_ntop(socket.AF_INET6, nsma)
414
415         return (Ether(dst=in6_getnsmac(nsma)) /
416                 IPv6(dst=d, src=self.remote_ip6) /
417                 ICMPv6ND_NS(tgt=self.local_ip6) /
418                 ICMPv6NDOptSrcLLAddr(lladdr=self.remote_mac))
419
420     def resolve_arp(self, pg_interface=None):
421         """Resolve ARP using provided packet-generator interface
422
423         :param pg_interface: interface used to resolve, if None then this
424             interface is used
425
426         """
427         if pg_interface is None:
428             pg_interface = self
429         self.test.logger.info("Sending ARP request for %s on port %s" %
430                               (self.local_ip4, pg_interface.name))
431         arp_req = self.create_arp_req()
432         pg_interface.add_stream(arp_req)
433         pg_interface.enable_capture()
434         self.test.pg_start()
435         self.test.logger.info(self.test.vapi.cli("show trace"))
436         try:
437             captured_packet = pg_interface.wait_for_packet(1)
438         except:
439             self.test.logger.info("No ARP received on port %s" %
440                                   pg_interface.name)
441             return
442         arp_reply = captured_packet.copy()  # keep original for exception
443         try:
444             if arp_reply[ARP].op == ARP.is_at:
445                 self.test.logger.info("VPP %s MAC address is %s " %
446                                       (self.name, arp_reply[ARP].hwsrc))
447                 self._local_mac = arp_reply[ARP].hwsrc
448             else:
449                 self.test.logger.info("No ARP received on port %s" %
450                                       pg_interface.name)
451         except:
452             self.test.logger.error(
453                 ppp("Unexpected response to ARP request:", captured_packet))
454             raise
455
456     def resolve_ndp(self, pg_interface=None, timeout=1):
457         """Resolve NDP using provided packet-generator interface
458
459         :param pg_interface: interface used to resolve, if None then this
460             interface is used
461         :param timeout: how long to wait for response before giving up
462
463         """
464         if pg_interface is None:
465             pg_interface = self
466         self.test.logger.info("Sending NDP request for %s on port %s" %
467                               (self.local_ip6, pg_interface.name))
468         ndp_req = self.create_ndp_req()
469         pg_interface.add_stream(ndp_req)
470         pg_interface.enable_capture()
471         self.test.pg_start()
472         now = time.time()
473         deadline = now + timeout
474         # Enabling IPv6 on an interface can generate more than the
475         # ND reply we are looking for (namely MLD). So loop through
476         # the replies to look for want we want.
477         while now < deadline:
478             try:
479                 captured_packet = pg_interface.wait_for_packet(
480                     deadline - now, filter_out_fn=None)
481             except:
482                 self.test.logger.error(
483                     "Timeout while waiting for NDP response")
484                 raise
485             ndp_reply = captured_packet.copy()  # keep original for exception
486             try:
487                 ndp_na = ndp_reply[ICMPv6ND_NA]
488                 opt = ndp_na[ICMPv6NDOptDstLLAddr]
489                 self.test.logger.info("VPP %s MAC address is %s " %
490                                       (self.name, opt.lladdr))
491                 self._local_mac = opt.lladdr
492                 self.test.logger.debug(self.test.vapi.cli("show trace"))
493                 # we now have the MAC we've been after
494                 return
495             except:
496                 self.test.logger.info(
497                     ppp("Unexpected response to NDP request:",
498                         captured_packet))
499             now = time.time()
500
501         self.test.logger.debug(self.test.vapi.cli("show trace"))
502         raise Exception("Timeout while waiting for NDP response")