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