blob: 555fc2ea32a55c2c6944a6957fadb2be13e2d030 [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
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -07008
9import scapy.compat
10
juraj.linkes40dd73b2018-09-21 13:55:16 +020011from util import check_core_path, get_core_path
Klement Sekeraf62ae122016-10-11 11:47:09 +020012
13
14class Hook(object):
15 """
16 Generic hooks before/after API/CLI calls
17 """
18
Paul Vinciguerra895e2f82019-01-08 20:37:40 -080019 def __init__(self, test):
20 self.test = test
21 self.logger = test.logger
Klement Sekera277b89c2016-10-28 13:20:27 +020022
Klement Sekeraf62ae122016-10-11 11:47:09 +020023 def before_api(self, api_name, api_args):
24 """
25 Function called before API call
26 Emit a debug message describing the API name and arguments
27
28 @param api_name: name of the API
29 @param api_args: tuple containing the API arguments
30 """
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080031
32 def _friendly_format(val):
33 if not isinstance(val, str):
34 return val
35 if len(val) == 6:
36 return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format(
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -070037 scapy.compat.orb(x)) for x in val]))
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080038 try:
Paul Vinciguerra9e315952019-01-29 11:51:44 -080039 # we don't call test_type(val) because it is a packed value.
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080040 return '{!s} ({!s})'.format(val, str(
41 ipaddress.ip_address(val)))
42 except ipaddress.AddressValueError:
43 return val
44
45 _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for
46 (key, val) in api_args.items())
Klement Sekera277b89c2016-10-28 13:20:27 +020047 self.logger.debug("API: %s (%s)" %
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080048 (api_name, _args), extra={'color': RED})
Klement Sekeraf62ae122016-10-11 11:47:09 +020049
50 def after_api(self, api_name, api_args):
51 """
52 Function called after API call
53
54 @param api_name: name of the API
55 @param api_args: tuple containing the API arguments
56 """
57 pass
58
59 def before_cli(self, cli):
60 """
61 Function called before CLI call
62 Emit a debug message describing the CLI
63
64 @param cli: CLI string
65 """
Klement Sekera277b89c2016-10-28 13:20:27 +020066 self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
Klement Sekeraf62ae122016-10-11 11:47:09 +020067
68 def after_cli(self, cli):
69 """
70 Function called after CLI call
71 """
72 pass
73
74
75class VppDiedError(Exception):
76 pass
77
78
79class PollHook(Hook):
80 """ Hook which checks if the vpp subprocess is alive """
81
Paul Vinciguerra895e2f82019-01-08 20:37:40 -080082 def __init__(self, test):
83 super(PollHook, self).__init__(test)
Klement Sekeraf62ae122016-10-11 11:47:09 +020084
Klement Sekeraf62ae122016-10-11 11:47:09 +020085 def on_crash(self, core_path):
Paul Vinciguerra38a4ec72018-11-28 11:34:21 -080086 self.logger.error("Core file present, debug with: gdb %s %s",
Paul Vinciguerraa1bfb3a2019-03-07 17:30:28 -080087 self.test.vpp_bin, core_path)
juraj.linkes40dd73b2018-09-21 13:55:16 +020088 check_core_path(self.logger, core_path)
Paul Vinciguerra38a4ec72018-11-28 11:34:21 -080089 self.logger.error("Running `file %s':", core_path)
juraj.linkes40dd73b2018-09-21 13:55:16 +020090 try:
91 info = check_output(["file", core_path])
92 self.logger.error(info)
93 except CalledProcessError as e:
94 self.logger.error(
Paul Vinciguerra38a4ec72018-11-28 11:34:21 -080095 "Subprocess returned with error running `file' utility on "
96 "core-file, "
97 "rc=%s", e.returncode)
98 except OSError as e:
99 self.logger.error(
100 "Subprocess returned OS error running `file' utility on "
101 "core-file, "
102 "oserror=(%s) %s", e.errno, e.strerror)
103 except Exception as e:
104 self.logger.error(
105 "Subprocess returned unanticipated error running `file' "
106 "utility on core-file, "
107 "%s", e)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200108
109 def poll_vpp(self):
110 """
111 Poll the vpp status and throw an exception if it's not running
112 :raises VppDiedError: exception if VPP is not running anymore
113 """
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800114 if self.test.vpp_dead:
Klement Sekeraf62ae122016-10-11 11:47:09 +0200115 # already dead, nothing to do
116 return
117
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800118 self.test.vpp.poll()
119 if self.test.vpp.returncode is not None:
Klement Sekeraf62ae122016-10-11 11:47:09 +0200120 signaldict = dict(
121 (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
122 if v.startswith('SIG') and not v.startswith('SIG_'))
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200123
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800124 if self.test.vpp.returncode in signaldict:
125 s = signaldict[abs(self.test.vpp.returncode)]
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200126 else:
127 s = "unknown"
Paul Vinciguerra1314ec62018-12-12 01:04:20 -0800128 msg = "VPP subprocess died unexpectedly with returncode %d [%s]." \
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800129 % (self.test.vpp.returncode, s)
Klement Sekera277b89c2016-10-28 13:20:27 +0200130 self.logger.critical(msg)
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800131 core_path = get_core_path(self.test.tempdir)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200132 if os.path.isfile(core_path):
133 self.on_crash(core_path)
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800134 self.test.vpp_dead = True
Klement Sekeraf62ae122016-10-11 11:47:09 +0200135 raise VppDiedError(msg)
136
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200137 def before_api(self, api_name, api_args):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200138 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200139 Check if VPP died before executing an API
Klement Sekeraf62ae122016-10-11 11:47:09 +0200140
141 :param api_name: name of the API
142 :param api_args: tuple containing the API arguments
143 :raises VppDiedError: exception if VPP is not running anymore
144
145 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200146 super(PollHook, self).before_api(api_name, api_args)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200147 self.poll_vpp()
148
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200149 def before_cli(self, cli):
Klement Sekeraf62ae122016-10-11 11:47:09 +0200150 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200151 Check if VPP died before executing a CLI
Klement Sekeraf62ae122016-10-11 11:47:09 +0200152
153 :param cli: CLI string
154 :raises Exception: exception if VPP is not running anymore
155
156 """
Klement Sekera0e3c0de2016-09-29 14:43:44 +0200157 super(PollHook, self).before_cli(cli)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200158 self.poll_vpp()
Klement Sekera277b89c2016-10-28 13:20:27 +0200159
160
161class StepHook(PollHook):
162 """ Hook which requires user to press ENTER before doing any API/CLI """
163
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800164 def __init__(self, test):
Klement Sekera277b89c2016-10-28 13:20:27 +0200165 self.skip_stack = None
166 self.skip_num = None
167 self.skip_count = 0
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800168 super(StepHook, self).__init__(test)
Klement Sekera277b89c2016-10-28 13:20:27 +0200169
170 def skip(self):
171 if self.skip_stack is None:
172 return False
173 stack = traceback.extract_stack()
174 counter = 0
175 skip = True
176 for e in stack:
177 if counter > self.skip_num:
178 break
179 if e[0] != self.skip_stack[counter][0]:
180 skip = False
181 if e[1] != self.skip_stack[counter][1]:
182 skip = False
183 counter += 1
184 if skip:
185 self.skip_count += 1
186 return True
187 else:
188 print("%d API/CLI calls skipped in specified stack "
189 "frame" % self.skip_count)
190 self.skip_count = 0
191 self.skip_stack = None
192 self.skip_num = None
193 return False
194
195 def user_input(self):
196 print('number\tfunction\tfile\tcode')
197 counter = 0
198 stack = traceback.extract_stack()
199 for e in stack:
200 print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
201 counter += 1
202 print(single_line_delim)
juraj.linkes184870a2018-07-16 14:22:01 +0200203 print("You may enter a number of stack frame chosen from above")
Klement Sekera277b89c2016-10-28 13:20:27 +0200204 print("Calls in/below that stack frame will be not be stepped anymore")
205 print(single_line_delim)
206 while True:
juraj.linkes184870a2018-07-16 14:22:01 +0200207 print("Enter your choice, if any, and press ENTER to continue "
208 "running the testcase...")
juraj.linkesbe460e72018-08-28 18:45:18 +0200209 choice = sys.stdin.readline().rstrip('\r\n')
Klement Sekera277b89c2016-10-28 13:20:27 +0200210 if choice == "":
211 choice = None
212 try:
213 if choice is not None:
214 num = int(choice)
juraj.linkes184870a2018-07-16 14:22:01 +0200215 except ValueError:
Klement Sekera277b89c2016-10-28 13:20:27 +0200216 print("Invalid input")
217 continue
218 if choice is not None and (num < 0 or num >= len(stack)):
219 print("Invalid choice")
220 continue
221 break
222 if choice is not None:
223 self.skip_stack = stack
224 self.skip_num = num
225
226 def before_cli(self, cli):
227 """ Wait for ENTER before executing CLI """
228 if self.skip():
229 print("Skip pause before executing CLI: %s" % cli)
230 else:
231 print(double_line_delim)
232 print("Test paused before executing CLI: %s" % cli)
233 print(single_line_delim)
234 self.user_input()
235 super(StepHook, self).before_cli(cli)
236
237 def before_api(self, api_name, api_args):
238 """ Wait for ENTER before executing API """
239 if self.skip():
240 print("Skip pause before executing API: %s (%s)"
241 % (api_name, api_args))
242 else:
243 print(double_line_delim)
244 print("Test paused before executing API: %s (%s)"
245 % (api_name, api_args))
246 print(single_line_delim)
247 self.user_input()
248 super(StepHook, self).before_api(api_name, api_args)