dpdk: add rte_delay_us_callback
[vpp.git] / test / hook.py
1 import signal
2 import os
3 import pexpect
4 import traceback
5 from log import *
6
7
8 class Hook(object):
9     """
10     Generic hooks before/after API/CLI calls
11     """
12
13     def __init__(self, logger):
14         self.logger = logger
15
16     def before_api(self, api_name, api_args):
17         """
18         Function called before API call
19         Emit a debug message describing the API name and arguments
20
21         @param api_name: name of the API
22         @param api_args: tuple containing the API arguments
23         """
24         self.logger.debug("API: %s (%s)" %
25                           (api_name, api_args), extra={'color': RED})
26
27     def after_api(self, api_name, api_args):
28         """
29         Function called after API call
30
31         @param api_name: name of the API
32         @param api_args: tuple containing the API arguments
33         """
34         pass
35
36     def before_cli(self, cli):
37         """
38         Function called before CLI call
39         Emit a debug message describing the CLI
40
41         @param cli: CLI string
42         """
43         self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
44
45     def after_cli(self, cli):
46         """
47         Function called after CLI call
48         """
49         pass
50
51
52 class VppDiedError(Exception):
53     pass
54
55
56 class PollHook(Hook):
57     """ Hook which checks if the vpp subprocess is alive """
58
59     def __init__(self, testcase):
60         self.testcase = testcase
61         self.logger = testcase.logger
62
63     def spawn_gdb(self, gdb_path, core_path):
64         gdb_cmdline = gdb_path + ' ' + self.testcase.vpp_bin + ' ' + core_path
65         gdb = pexpect.spawn(gdb_cmdline)
66         gdb.interact()
67         try:
68             gdb.terminate(True)
69         except:
70             pass
71         if gdb.isalive():
72             raise Exception("GDB refused to die...")
73
74     def on_crash(self, core_path):
75         if self.testcase.debug_core:
76             gdb_path = '/usr/bin/gdb'
77             if os.path.isfile(gdb_path) and os.access(gdb_path, os.X_OK):
78                 # automatically attach gdb
79                 self.spawn_gdb(gdb_path, core_path)
80                 return
81             else:
82                 self.logger.error(
83                     "Debugger '%s' does not exist or is not an executable.." %
84                     gdb_path)
85
86         self.logger.critical('core file present, debug with: gdb ' +
87                              self.testcase.vpp_bin + ' ' + core_path)
88
89     def poll_vpp(self):
90         """
91         Poll the vpp status and throw an exception if it's not running
92         :raises VppDiedError: exception if VPP is not running anymore
93         """
94         if self.testcase.vpp_dead:
95             # already dead, nothing to do
96             return
97
98         self.testcase.vpp.poll()
99         if self.testcase.vpp.returncode is not None:
100             signaldict = dict(
101                 (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
102                 if v.startswith('SIG') and not v.startswith('SIG_'))
103             msg = "VPP subprocess died unexpectedly with returncode %d [%s]" % (
104                 self.testcase.vpp.returncode,
105                 signaldict[abs(self.testcase.vpp.returncode)])
106             self.logger.critical(msg)
107             core_path = self.testcase.tempdir + '/core'
108             if os.path.isfile(core_path):
109                 self.on_crash(core_path)
110             self.testcase.vpp_dead = True
111             raise VppDiedError(msg)
112
113     def after_api(self, api_name, api_args):
114         """
115         Check if VPP died after executing an API
116
117         :param api_name: name of the API
118         :param api_args: tuple containing the API arguments
119         :raises VppDiedError: exception if VPP is not running anymore
120
121         """
122         super(PollHook, self).after_api(api_name, api_args)
123         self.poll_vpp()
124
125     def after_cli(self, cli):
126         """
127         Check if VPP died after executing a CLI
128
129         :param cli: CLI string
130         :raises Exception: exception if VPP is not running anymore
131
132         """
133         super(PollHook, self).after_cli(cli)
134         self.poll_vpp()
135
136
137 class StepHook(PollHook):
138     """ Hook which requires user to press ENTER before doing any API/CLI """
139
140     def __init__(self, testcase):
141         self.skip_stack = None
142         self.skip_num = None
143         self.skip_count = 0
144         super(StepHook, self).__init__(testcase)
145
146     def skip(self):
147         if self.skip_stack is None:
148             return False
149         stack = traceback.extract_stack()
150         counter = 0
151         skip = True
152         for e in stack:
153             if counter > self.skip_num:
154                 break
155             if e[0] != self.skip_stack[counter][0]:
156                 skip = False
157             if e[1] != self.skip_stack[counter][1]:
158                 skip = False
159             counter += 1
160         if skip:
161             self.skip_count += 1
162             return True
163         else:
164             print("%d API/CLI calls skipped in specified stack "
165                   "frame" % self.skip_count)
166             self.skip_count = 0
167             self.skip_stack = None
168             self.skip_num = None
169             return False
170
171     def user_input(self):
172         print('number\tfunction\tfile\tcode')
173         counter = 0
174         stack = traceback.extract_stack()
175         for e in stack:
176             print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
177             counter += 1
178         print(single_line_delim)
179         print("You can enter a number of stack frame chosen from above")
180         print("Calls in/below that stack frame will be not be stepped anymore")
181         print(single_line_delim)
182         while True:
183             choice = raw_input("Enter your choice, if any, and press ENTER to "
184                                "continue running the testcase...")
185             if choice == "":
186                 choice = None
187             try:
188                 if choice is not None:
189                     num = int(choice)
190             except:
191                 print("Invalid input")
192                 continue
193             if choice is not None and (num < 0 or num >= len(stack)):
194                 print("Invalid choice")
195                 continue
196             break
197         if choice is not None:
198             self.skip_stack = stack
199             self.skip_num = num
200
201     def before_cli(self, cli):
202         """ Wait for ENTER before executing CLI """
203         if self.skip():
204             print("Skip pause before executing CLI: %s" % cli)
205         else:
206             print(double_line_delim)
207             print("Test paused before executing CLI: %s" % cli)
208             print(single_line_delim)
209             self.user_input()
210         super(StepHook, self).before_cli(cli)
211
212     def before_api(self, api_name, api_args):
213         """ Wait for ENTER before executing API """
214         if self.skip():
215             print("Skip pause before executing API: %s (%s)"
216                   % (api_name, api_args))
217         else:
218             print(double_line_delim)
219             print("Test paused before executing API: %s (%s)"
220                   % (api_name, api_args))
221             print(single_line_delim)
222             self.user_input()
223         super(StepHook, self).before_api(api_name, api_args)