MAP: Convert from DPO to input feature.
[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 import ipaddress
7 from subprocess import check_output, CalledProcessError
8 from util import check_core_path, get_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
28         def _friendly_format(val):
29             if not isinstance(val, str):
30                 return val
31             if len(val) == 6:
32                 return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format(
33                     ord(x)) for x in val]))
34             try:
35                 return '{!s} ({!s})'.format(val, str(
36                     ipaddress.ip_address(val)))
37             except ipaddress.AddressValueError:
38                 return val
39
40         _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for
41                           (key, val) in api_args.items())
42         self.logger.debug("API: %s (%s)" %
43                           (api_name, _args), extra={'color': RED})
44
45     def after_api(self, api_name, api_args):
46         """
47         Function called after API call
48
49         @param api_name: name of the API
50         @param api_args: tuple containing the API arguments
51         """
52         pass
53
54     def before_cli(self, cli):
55         """
56         Function called before CLI call
57         Emit a debug message describing the CLI
58
59         @param cli: CLI string
60         """
61         self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
62
63     def after_cli(self, cli):
64         """
65         Function called after CLI call
66         """
67         pass
68
69
70 class VppDiedError(Exception):
71     pass
72
73
74 class PollHook(Hook):
75     """ Hook which checks if the vpp subprocess is alive """
76
77     def __init__(self, testcase):
78         super(PollHook, self).__init__(testcase.logger)
79         self.testcase = testcase
80
81     def on_crash(self, core_path):
82         self.logger.error("Core file present, debug with: gdb %s %s" %
83                           (self.testcase.vpp_bin, core_path))
84         check_core_path(self.logger, core_path)
85         self.logger.error("Running `file %s':" % core_path)
86         try:
87             info = check_output(["file", core_path])
88             self.logger.error(info)
89         except CalledProcessError as e:
90             self.logger.error(
91                 "Could not run `file' utility on core-file, "
92                 "rc=%s" % e.returncode)
93
94     def poll_vpp(self):
95         """
96         Poll the vpp status and throw an exception if it's not running
97         :raises VppDiedError: exception if VPP is not running anymore
98         """
99         if self.testcase.vpp_dead:
100             # already dead, nothing to do
101             return
102
103         self.testcase.vpp.poll()
104         if self.testcase.vpp.returncode is not None:
105             signaldict = dict(
106                 (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
107                 if v.startswith('SIG') and not v.startswith('SIG_'))
108
109             if self.testcase.vpp.returncode in signaldict:
110                 s = signaldict[abs(self.testcase.vpp.returncode)]
111             else:
112                 s = "unknown"
113             msg = "VPP subprocess died unexpectedly with returncode %d [%s]." \
114                   % (self.testcase.vpp.returncode, s)
115             self.logger.critical(msg)
116             core_path = get_core_path(self.testcase.tempdir)
117             if os.path.isfile(core_path):
118                 self.on_crash(core_path)
119             self.testcase.vpp_dead = True
120             raise VppDiedError(msg)
121
122     def before_api(self, api_name, api_args):
123         """
124         Check if VPP died before executing an API
125
126         :param api_name: name of the API
127         :param api_args: tuple containing the API arguments
128         :raises VppDiedError: exception if VPP is not running anymore
129
130         """
131         super(PollHook, self).before_api(api_name, api_args)
132         self.poll_vpp()
133
134     def before_cli(self, cli):
135         """
136         Check if VPP died before executing a CLI
137
138         :param cli: CLI string
139         :raises Exception: exception if VPP is not running anymore
140
141         """
142         super(PollHook, self).before_cli(cli)
143         self.poll_vpp()
144
145
146 class StepHook(PollHook):
147     """ Hook which requires user to press ENTER before doing any API/CLI """
148
149     def __init__(self, testcase):
150         self.skip_stack = None
151         self.skip_num = None
152         self.skip_count = 0
153         super(StepHook, self).__init__(testcase)
154
155     def skip(self):
156         if self.skip_stack is None:
157             return False
158         stack = traceback.extract_stack()
159         counter = 0
160         skip = True
161         for e in stack:
162             if counter > self.skip_num:
163                 break
164             if e[0] != self.skip_stack[counter][0]:
165                 skip = False
166             if e[1] != self.skip_stack[counter][1]:
167                 skip = False
168             counter += 1
169         if skip:
170             self.skip_count += 1
171             return True
172         else:
173             print("%d API/CLI calls skipped in specified stack "
174                   "frame" % self.skip_count)
175             self.skip_count = 0
176             self.skip_stack = None
177             self.skip_num = None
178             return False
179
180     def user_input(self):
181         print('number\tfunction\tfile\tcode')
182         counter = 0
183         stack = traceback.extract_stack()
184         for e in stack:
185             print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
186             counter += 1
187         print(single_line_delim)
188         print("You may enter a number of stack frame chosen from above")
189         print("Calls in/below that stack frame will be not be stepped anymore")
190         print(single_line_delim)
191         while True:
192             print("Enter your choice, if any, and press ENTER to continue "
193                   "running the testcase...")
194             choice = sys.stdin.readline().rstrip('\r\n')
195             if choice == "":
196                 choice = None
197             try:
198                 if choice is not None:
199                     num = int(choice)
200             except ValueError:
201                 print("Invalid input")
202                 continue
203             if choice is not None and (num < 0 or num >= len(stack)):
204                 print("Invalid choice")
205                 continue
206             break
207         if choice is not None:
208             self.skip_stack = stack
209             self.skip_num = num
210
211     def before_cli(self, cli):
212         """ Wait for ENTER before executing CLI """
213         if self.skip():
214             print("Skip pause before executing CLI: %s" % cli)
215         else:
216             print(double_line_delim)
217             print("Test paused before executing CLI: %s" % cli)
218             print(single_line_delim)
219             self.user_input()
220         super(StepHook, self).before_cli(cli)
221
222     def before_api(self, api_name, api_args):
223         """ Wait for ENTER before executing API """
224         if self.skip():
225             print("Skip pause before executing API: %s (%s)"
226                   % (api_name, api_args))
227         else:
228             print(double_line_delim)
229             print("Test paused before executing API: %s (%s)"
230                   % (api_name, api_args))
231             print(single_line_delim)
232             self.user_input()
233         super(StepHook, self).before_api(api_name, api_args)