blob: cddb603e46ecf13b6b78fd747941d2060477c6bb [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
Paul Vinciguerra9e315952019-01-29 11:51:44 -08009try:
10 text_type = unicode
11except NameError:
12 text_type = str
Klement Sekeraf62ae122016-10-11 11:47:09 +020013
14
15class Hook(object):
16 """
17 Generic hooks before/after API/CLI calls
18 """
19
Paul Vinciguerra895e2f82019-01-08 20:37:40 -080020 def __init__(self, test):
21 self.test = test
22 self.logger = test.logger
Klement Sekera277b89c2016-10-28 13:20:27 +020023
Klement Sekeraf62ae122016-10-11 11:47:09 +020024 def before_api(self, api_name, api_args):
25 """
26 Function called before API call
27 Emit a debug message describing the API name and arguments
28
29 @param api_name: name of the API
30 @param api_args: tuple containing the API arguments
31 """
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080032
33 def _friendly_format(val):
34 if not isinstance(val, str):
35 return val
36 if len(val) == 6:
37 return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format(
38 ord(x)) for x in val]))
39 try:
Paul Vinciguerra9e315952019-01-29 11:51:44 -080040 # we don't call test_type(val) because it is a packed value.
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080041 return '{!s} ({!s})'.format(val, str(
42 ipaddress.ip_address(val)))
43 except ipaddress.AddressValueError:
44 return val
45
46 _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for
47 (key, val) in api_args.items())
Klement Sekera277b89c2016-10-28 13:20:27 +020048 self.logger.debug("API: %s (%s)" %
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080049 (api_name, _args), extra={'color': RED})
Klement Sekeraf62ae122016-10-11 11:47:09 +020050
51 def after_api(self, api_name, api_args):
52 """
53 Function called after API call
54
55 @param api_name: name of the API
56 @param api_args: tuple containing the API arguments
57 """
58 pass
59
60 def before_cli(self, cli):
61 """
62 Function called before CLI call
63 Emit a debug message describing the CLI
64
65 @param cli: CLI string
66 """
Klement Sekera277b89c2016-10-28 13:20:27 +020067 self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
Klement Sekeraf62ae122016-10-11 11:47:09 +020068
69 def after_cli(self, cli):
70 """
71 Function called after CLI call
72 """
73 pass
74
75
76class VppDiedError(Exception):
77 pass
78
79
80class PollHook(Hook):
81 """ Hook which checks if the vpp subprocess is alive """
82
Paul Vinciguerra895e2f82019-01-08 20:37:40 -080083 def __init__(self, test):
84 super(PollHook, self).__init__(test)
Klement Sekeraf62ae122016-10-11 11:47:09 +020085
Klement Sekeraf62ae122016-10-11 11:47:09 +020086 def on_crash(self, core_path):
juraj.linkes40dd73b2018-09-21 13:55:16 +020087 self.logger.error("Core file present, debug with: gdb %s %s" %
Paul Vinciguerra895e2f82019-01-08 20:37:40 -080088 (self.test.vpp_bin, core_path))
juraj.linkes40dd73b2018-09-21 13:55:16 +020089 check_core_path(self.logger, core_path)
90 self.logger.error("Running `file %s':" % core_path)
91 try:
92 info = check_output(["file", core_path])
93 self.logger.error(info)
94 except CalledProcessError as e:
95 self.logger.error(
96 "Could not run `file' utility on core-file, "
97 "rc=%s" % e.returncode)
Klement Sekeraf62ae122016-10-11 11:47:09 +020098
99 def poll_vpp(self):
100 """
101 Poll the vpp status and throw an exception if it's not running
102 :raises VppDiedError: exception if VPP is not running anymore
103 """
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800104 if self.test.vpp_dead:
Klement Sekeraf62ae122016-10-11 11:47:09 +0200105 # already dead, nothing to do
106 return
107
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800108 self.test.vpp.poll()
109 if self.test.vpp.returncode is not None:
Klement Sekeraf62ae122016-10-11 11:47:09 +0200110 signaldict = dict(
111 (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
112 if v.startswith('SIG') and not v.startswith('SIG_'))
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200113
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800114 if self.test.vpp.returncode in signaldict:
115 s = signaldict[abs(self.test.vpp.returncode)]
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200116 else:
117 s = "unknown"
Paul Vinciguerra1314ec62018-12-12 01:04:20 -0800118 msg = "VPP subprocess died unexpectedly with returncode %d [%s]." \
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800119 % (self.test.vpp.returncode, s)
Klement Sekera277b89c2016-10-28 13:20:27 +0200120 self.logger.critical(msg)
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800121 core_path = get_core_path(self.test.tempdir)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200122 if os.path.isfile(core_path):
123 self.on_crash(core_path)
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800124 self.test.vpp_dead = True
Klement Sekeraf62ae122016-10-11 11:47:09 +0200125 raise VppDiedError(msg)
126
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200127 def before_api(self, api_name, api_args):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200128 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200129 Check if VPP died before executing an API
Klement Sekeraf62ae122016-10-11 11:47:09 +0200130
131 :param api_name: name of the API
132 :param api_args: tuple containing the API arguments
133 :raises VppDiedError: exception if VPP is not running anymore
134
135 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200136 super(PollHook, self).before_api(api_name, api_args)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200137 self.poll_vpp()
138
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200139 def before_cli(self, cli):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200140 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200141 Check if VPP died before executing a CLI
Klement Sekeraf62ae122016-10-11 11:47:09 +0200142
143 :param cli: CLI string
144 :raises Exception: exception if VPP is not running anymore
145
146 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200147 super(PollHook, self).before_cli(cli)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200148 self.poll_vpp()
Klement Sekera277b89c2016-10-28 13:20:27 +0200149
150
151class StepHook(PollHook):
152 """ Hook which requires user to press ENTER before doing any API/CLI """
153
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800154 def __init__(self, test):
Klement Sekera277b89c2016-10-28 13:20:27 +0200155 self.skip_stack = None
156 self.skip_num = None
157 self.skip_count = 0
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800158 super(StepHook, self).__init__(test)
Klement Sekera277b89c2016-10-28 13:20:27 +0200159
160 def skip(self):
161 if self.skip_stack is None:
162 return False
163 stack = traceback.extract_stack()
164 counter = 0
165 skip = True
166 for e in stack:
167 if counter > self.skip_num:
168 break
169 if e[0] != self.skip_stack[counter][0]:
170 skip = False
171 if e[1] != self.skip_stack[counter][1]:
172 skip = False
173 counter += 1
174 if skip:
175 self.skip_count += 1
176 return True
177 else:
178 print("%d API/CLI calls skipped in specified stack "
179 "frame" % self.skip_count)
180 self.skip_count = 0
181 self.skip_stack = None
182 self.skip_num = None
183 return False
184
185 def user_input(self):
186 print('number\tfunction\tfile\tcode')
187 counter = 0
188 stack = traceback.extract_stack()
189 for e in stack:
190 print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
191 counter += 1
192 print(single_line_delim)
juraj.linkes184870a2018-07-16 14:22:01 +0200193 print("You may enter a number of stack frame chosen from above")
Klement Sekera277b89c2016-10-28 13:20:27 +0200194 print("Calls in/below that stack frame will be not be stepped anymore")
195 print(single_line_delim)
196 while True:
juraj.linkes184870a2018-07-16 14:22:01 +0200197 print("Enter your choice, if any, and press ENTER to continue "
198 "running the testcase...")
juraj.linkesbe460e72018-08-28 18:45:18 +0200199 choice = sys.stdin.readline().rstrip('\r\n')
Klement Sekera277b89c2016-10-28 13:20:27 +0200200 if choice == "":
201 choice = None
202 try:
203 if choice is not None:
204 num = int(choice)
juraj.linkes184870a2018-07-16 14:22:01 +0200205 except ValueError:
Klement Sekera277b89c2016-10-28 13:20:27 +0200206 print("Invalid input")
207 continue
208 if choice is not None and (num < 0 or num >= len(stack)):
209 print("Invalid choice")
210 continue
211 break
212 if choice is not None:
213 self.skip_stack = stack
214 self.skip_num = num
215
216 def before_cli(self, cli):
217 """ Wait for ENTER before executing CLI """
218 if self.skip():
219 print("Skip pause before executing CLI: %s" % cli)
220 else:
221 print(double_line_delim)
222 print("Test paused before executing CLI: %s" % cli)
223 print(single_line_delim)
224 self.user_input()
225 super(StepHook, self).before_cli(cli)
226
227 def before_api(self, api_name, api_args):
228 """ Wait for ENTER before executing API """
229 if self.skip():
230 print("Skip pause before executing API: %s (%s)"
231 % (api_name, api_args))
232 else:
233 print(double_line_delim)
234 print("Test paused before executing API: %s (%s)"
235 % (api_name, api_args))
236 print(single_line_delim)
237 self.user_input()
238 super(StepHook, self).before_api(api_name, api_args)