blob: a8f37c7a35b285f93fe96e6e3dd0bc3dcadd2b39 [file] [log] [blame]
Klement Sekeraf62ae122016-10-11 11:47:09 +02001import signal
2import os
Klement Sekera13a83ef2018-03-21 12:35:51 +01003import sys
Klement Sekera277b89c2016-10-28 13:20:27 +02004import traceback
Klement Sekera909a6a12017-08-08 04:33:53 +02005from log import RED, single_line_delim, double_line_delim
Paul Vinciguerra1314ec62018-12-12 01:04:20 -08006import ipaddress
Klement Sekera9b6ece72018-03-23 10:50:11 +01007from subprocess import check_output, CalledProcessError
juraj.linkes40dd73b2018-09-21 13:55:16 +02008from util import check_core_path, get_core_path
Klement Sekeraf62ae122016-10-11 11:47:09 +02009
10
11class Hook(object):
12 """
13 Generic hooks before/after API/CLI calls
14 """
15
Klement Sekera277b89c2016-10-28 13:20:27 +020016 def __init__(self, logger):
17 self.logger = logger
18
Klement Sekeraf62ae122016-10-11 11:47:09 +020019 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 """
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080027
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())
Klement Sekera277b89c2016-10-28 13:20:27 +020042 self.logger.debug("API: %s (%s)" %
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080043 (api_name, _args), extra={'color': RED})
Klement Sekeraf62ae122016-10-11 11:47:09 +020044
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 """
Klement Sekera277b89c2016-10-28 13:20:27 +020061 self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
Klement Sekeraf62ae122016-10-11 11:47:09 +020062
63 def after_cli(self, cli):
64 """
65 Function called after CLI call
66 """
67 pass
68
69
70class VppDiedError(Exception):
71 pass
72
73
74class PollHook(Hook):
75 """ Hook which checks if the vpp subprocess is alive """
76
77 def __init__(self, testcase):
juraj.linkes40dd73b2018-09-21 13:55:16 +020078 super(PollHook, self).__init__(testcase.logger)
Klement Sekeraf62ae122016-10-11 11:47:09 +020079 self.testcase = testcase
80
Klement Sekeraf62ae122016-10-11 11:47:09 +020081 def on_crash(self, core_path):
juraj.linkes40dd73b2018-09-21 13:55:16 +020082 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)
Klement Sekeraf62ae122016-10-11 11:47:09 +020093
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 """
Klement Sekera085f5c02016-11-24 01:59:16 +010099 if self.testcase.vpp_dead:
Klement Sekeraf62ae122016-10-11 11:47:09 +0200100 # 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_'))
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200108
109 if self.testcase.vpp.returncode in signaldict:
110 s = signaldict[abs(self.testcase.vpp.returncode)]
111 else:
112 s = "unknown"
Paul Vinciguerra1314ec62018-12-12 01:04:20 -0800113 msg = "VPP subprocess died unexpectedly with returncode %d [%s]." \
114 % (self.testcase.vpp.returncode, s)
Klement Sekera277b89c2016-10-28 13:20:27 +0200115 self.logger.critical(msg)
juraj.linkes40dd73b2018-09-21 13:55:16 +0200116 core_path = get_core_path(self.testcase.tempdir)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200117 if os.path.isfile(core_path):
118 self.on_crash(core_path)
119 self.testcase.vpp_dead = True
120 raise VppDiedError(msg)
121
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200122 def before_api(self, api_name, api_args):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200123 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200124 Check if VPP died before executing an API
Klement Sekeraf62ae122016-10-11 11:47:09 +0200125
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 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200131 super(PollHook, self).before_api(api_name, api_args)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200132 self.poll_vpp()
133
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200134 def before_cli(self, cli):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200135 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200136 Check if VPP died before executing a CLI
Klement Sekeraf62ae122016-10-11 11:47:09 +0200137
138 :param cli: CLI string
139 :raises Exception: exception if VPP is not running anymore
140
141 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200142 super(PollHook, self).before_cli(cli)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200143 self.poll_vpp()
Klement Sekera277b89c2016-10-28 13:20:27 +0200144
145
146class 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)
juraj.linkes184870a2018-07-16 14:22:01 +0200188 print("You may enter a number of stack frame chosen from above")
Klement Sekera277b89c2016-10-28 13:20:27 +0200189 print("Calls in/below that stack frame will be not be stepped anymore")
190 print(single_line_delim)
191 while True:
juraj.linkes184870a2018-07-16 14:22:01 +0200192 print("Enter your choice, if any, and press ENTER to continue "
193 "running the testcase...")
juraj.linkesbe460e72018-08-28 18:45:18 +0200194 choice = sys.stdin.readline().rstrip('\r\n')
Klement Sekera277b89c2016-10-28 13:20:27 +0200195 if choice == "":
196 choice = None
197 try:
198 if choice is not None:
199 num = int(choice)
juraj.linkes184870a2018-07-16 14:22:01 +0200200 except ValueError:
Klement Sekera277b89c2016-10-28 13:20:27 +0200201 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)