7287aaa192026106345cbb834a880b1f8702de97
[vpp.git] / test / hook.py
1 import signal
2 import os
3 import sys
4 import traceback
5 from log import RED, single_line_delim, double_line_delim
6 from debug import spawn_gdb
7 from subprocess import check_output, CalledProcessError
8 from util import check_core_path
9
10
11 class Hook(object):
12     """
13     Generic hooks before/after API/CLI calls
14     """
15
16     def __init__(self, logger):
17         self.logger = logger
18
19     def before_api(self, api_name, api_args):
20         """
21         Function called before API call
22         Emit a debug message describing the API name and arguments
23
24         @param api_name: name of the API
25         @param api_args: tuple containing the API arguments
26         """
27         self.logger.debug("API: %s (%s)" %
28                           (api_name, api_args), extra={'color': RED})
29
30     def after_api(self, api_name, api_args):
31         """
32         Function called after API call
33
34         @param api_name: name of the API
35         @param api_args: tuple containing the API arguments
36         """
37         pass
38
39     def before_cli(self, cli):
40         """
41         Function called before CLI call
42         Emit a debug message describing the CLI
43
44         @param cli: CLI string
45         """
46         self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
47
48     def after_cli(self, cli):
49         """
50         Function called after CLI call
51         """
52         pass
53
54
55 class VppDiedError(Exception):
56     pass
57
58
59 class PollHook(Hook):
60     """ Hook which checks if the vpp subprocess is alive """
61
62     def __init__(self, testcase):
63         self.testcase = testcase
64         self.logger = testcase.logger
65
66     def on_crash(self, core_path):
67         if self.testcase.debug_core:
68             # notify parent process that we're handling a core file
69             open('%s/_core_handled' % self.testcase.tempdir, 'a').close()
70             spawn_gdb(self.testcase.vpp_bin, core_path, self.logger)
71         else:
72             self.logger.error("Core file present, debug with: gdb %s %s" %
73                               (self.testcase.vpp_bin, core_path))
74             check_core_path(self.logger, core_path)
75             self.logger.error("Running `file %s':" % core_path)
76             try:
77                 info = check_output(["file", core_path])
78                 self.logger.error(info)
79             except CalledProcessError as e:
80                 self.logger.error(
81                     "Could not run `file' utility on core-file, "
82                     "rc=%s" % e.returncode)
83                 pass
84
85     def poll_vpp(self):
86         """
87         Poll the vpp status and throw an exception if it's not running
88         :raises VppDiedError: exception if VPP is not running anymore
89         """
90         if self.testcase.vpp_dead:
91             # already dead, nothing to do
92             return
93
94         self.testcase.vpp.poll()
95         if self.testcase.vpp.returncode is not None:
96             signaldict = dict(
97                 (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
98                 if v.startswith('SIG') and not v.startswith('SIG_'))
99
100             if self.testcase.vpp.returncode in signaldict:
101                 s = signaldict[abs(self.testcase.vpp.returncode)]
102             else:
103                 s = "unknown"
104             msg = "VPP subprocess died unexpectedly with returncode %d [%s]" %\
105                 (self.testcase.vpp.returncode, s)
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 before_api(self, api_name, api_args):
114         """
115         Check if VPP died before 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).before_api(api_name, api_args)
123         self.poll_vpp()
124
125     def before_cli(self, cli):
126         """
127         Check if VPP died before 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).before_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 may 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             print("Enter your choice, if any, and press ENTER to continue "
184                   "running the testcase...")
185             choice = sys.stdin.readline().rstrip('\r\n')
186             if choice == "":
187                 choice = None
188             try:
189                 if choice is not None:
190                     num = int(choice)
191             except ValueError:
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)