blob: 8033c9355cb48e812f680bdc68a22aafc420e48e [file] [log] [blame]
Klement Sekeraf62ae122016-10-11 11:47:09 +02001import os
Klement Sekera13a83ef2018-03-21 12:35:51 +01002import sys
Klement Sekera277b89c2016-10-28 13:20:27 +02003import traceback
Paul Vinciguerra1314ec62018-12-12 01:04:20 -08004import ipaddress
Klement Sekera9b6ece72018-03-23 10:50:11 +01005from subprocess import check_output, CalledProcessError
Paul Vinciguerraa7427ec2019-03-10 10:04:23 -07006
7import scapy.compat
Paul Vinciguerra496b0de2019-06-20 12:24:12 -04008import framework
Dmitry Valter3ace4d62022-03-26 15:43:14 +00009from config import config
Paul Vinciguerra496b0de2019-06-20 12:24:12 -040010from log import RED, single_line_delim, double_line_delim
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
Paul Vinciguerrae061dad2020-12-04 14:57:51 -050014class Hook:
Klement Sekeraf62ae122016-10-11 11:47:09 +020015 """
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)))
Naveen Joy64f75302019-03-27 14:28:50 -070042 except ValueError:
Paul Vinciguerra1314ec62018-12-12 01:04:20 -080043 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
Klement Sekeraf62ae122016-10-11 11:47:09 +020075class PollHook(Hook):
76 """ Hook which checks if the vpp subprocess is alive """
77
Paul Vinciguerra895e2f82019-01-08 20:37:40 -080078 def __init__(self, test):
79 super(PollHook, self).__init__(test)
Klement Sekeraf62ae122016-10-11 11:47:09 +020080
Klement Sekeraf62ae122016-10-11 11:47:09 +020081 def on_crash(self, core_path):
Paul Vinciguerra38a4ec72018-11-28 11:34:21 -080082 self.logger.error("Core file present, debug with: gdb %s %s",
Dmitry Valter3ace4d62022-03-26 15:43:14 +000083 config.vpp, core_path)
juraj.linkes40dd73b2018-09-21 13:55:16 +020084 check_core_path(self.logger, core_path)
Paul Vinciguerra38a4ec72018-11-28 11:34:21 -080085 self.logger.error("Running `file %s':", core_path)
juraj.linkes40dd73b2018-09-21 13:55:16 +020086 try:
87 info = check_output(["file", core_path])
88 self.logger.error(info)
89 except CalledProcessError as e:
90 self.logger.error(
Paul Vinciguerra38a4ec72018-11-28 11:34:21 -080091 "Subprocess returned with error running `file' utility on "
92 "core-file, "
93 "rc=%s", e.returncode)
94 except OSError as e:
95 self.logger.error(
96 "Subprocess returned OS error running `file' utility on "
97 "core-file, "
98 "oserror=(%s) %s", e.errno, e.strerror)
99 except Exception as e:
100 self.logger.error(
101 "Subprocess returned unanticipated error running `file' "
102 "utility on core-file, "
103 "%s", e)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200104
105 def poll_vpp(self):
106 """
107 Poll the vpp status and throw an exception if it's not running
108 :raises VppDiedError: exception if VPP is not running anymore
109 """
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800110 if self.test.vpp_dead:
Klement Sekeraf62ae122016-10-11 11:47:09 +0200111 # already dead, nothing to do
112 return
113
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800114 self.test.vpp.poll()
115 if self.test.vpp.returncode is not None:
Paul Vinciguerra496b0de2019-06-20 12:24:12 -0400116 self.test.vpp_dead = True
117 raise framework.VppDiedError(rv=self.test.vpp.returncode)
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800118 core_path = get_core_path(self.test.tempdir)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200119 if os.path.isfile(core_path):
120 self.on_crash(core_path)
Klement Sekeraf62ae122016-10-11 11:47:09 +0200121
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
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800149 def __init__(self, test):
Klement Sekera277b89c2016-10-28 13:20:27 +0200150 self.skip_stack = None
151 self.skip_num = None
152 self.skip_count = 0
Klement Sekerac0a2f0e2022-01-28 11:31:01 +0000153 self.break_func = None
Paul Vinciguerra895e2f82019-01-08 20:37:40 -0800154 super(StepHook, self).__init__(test)
Klement Sekera277b89c2016-10-28 13:20:27 +0200155
156 def skip(self):
Klement Sekerac0a2f0e2022-01-28 11:31:01 +0000157 if self.break_func is not None:
158 return self.should_skip_func_based()
159 if self.skip_stack is not None:
160 return self.should_skip_stack_based()
161
162 def should_skip_func_based(self):
163 stack = traceback.extract_stack()
164 for e in stack:
165 if e[2] == self.break_func:
166 self.break_func = None
167 return False
168 return True
169
170 def should_skip_stack_based(self):
Klement Sekera277b89c2016-10-28 13:20:27 +0200171 stack = traceback.extract_stack()
172 counter = 0
173 skip = True
174 for e in stack:
175 if counter > self.skip_num:
176 break
177 if e[0] != self.skip_stack[counter][0]:
178 skip = False
179 if e[1] != self.skip_stack[counter][1]:
180 skip = False
181 counter += 1
182 if skip:
183 self.skip_count += 1
184 return True
185 else:
186 print("%d API/CLI calls skipped in specified stack "
187 "frame" % self.skip_count)
188 self.skip_count = 0
189 self.skip_stack = None
190 self.skip_num = None
191 return False
192
193 def user_input(self):
194 print('number\tfunction\tfile\tcode')
195 counter = 0
196 stack = traceback.extract_stack()
197 for e in stack:
198 print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
199 counter += 1
200 print(single_line_delim)
juraj.linkes184870a2018-07-16 14:22:01 +0200201 print("You may enter a number of stack frame chosen from above")
Klement Sekera277b89c2016-10-28 13:20:27 +0200202 print("Calls in/below that stack frame will be not be stepped anymore")
Klement Sekerac0a2f0e2022-01-28 11:31:01 +0000203 print("Alternatively, enter a test function name to stop at")
Klement Sekera277b89c2016-10-28 13:20:27 +0200204 print(single_line_delim)
205 while True:
juraj.linkes184870a2018-07-16 14:22:01 +0200206 print("Enter your choice, if any, and press ENTER to continue "
207 "running the testcase...")
juraj.linkesbe460e72018-08-28 18:45:18 +0200208 choice = sys.stdin.readline().rstrip('\r\n')
Klement Sekera277b89c2016-10-28 13:20:27 +0200209 if choice == "":
210 choice = None
211 try:
212 if choice is not None:
213 num = int(choice)
juraj.linkes184870a2018-07-16 14:22:01 +0200214 except ValueError:
Klement Sekerac0a2f0e2022-01-28 11:31:01 +0000215 if choice.startswith("test_"):
216 break
Klement Sekera277b89c2016-10-28 13:20:27 +0200217 print("Invalid input")
218 continue
219 if choice is not None and (num < 0 or num >= len(stack)):
220 print("Invalid choice")
221 continue
222 break
223 if choice is not None:
Klement Sekerac0a2f0e2022-01-28 11:31:01 +0000224 if choice.startswith("test_"):
225 self.break_func = choice
226 else:
227 self.break_func = None
228 self.skip_stack = stack
229 self.skip_num = num
Klement Sekera277b89c2016-10-28 13:20:27 +0200230
231 def before_cli(self, cli):
232 """ Wait for ENTER before executing CLI """
233 if self.skip():
234 print("Skip pause before executing CLI: %s" % cli)
235 else:
236 print(double_line_delim)
237 print("Test paused before executing CLI: %s" % cli)
238 print(single_line_delim)
239 self.user_input()
240 super(StepHook, self).before_cli(cli)
241
242 def before_api(self, api_name, api_args):
243 """ Wait for ENTER before executing API """
244 if self.skip():
245 print("Skip pause before executing API: %s (%s)"
246 % (api_name, api_args))
247 else:
248 print(double_line_delim)
249 print("Test paused before executing API: %s (%s)"
250 % (api_name, api_args))
251 print(single_line_delim)
252 self.user_input()
253 super(StepHook, self).before_api(api_name, api_args)