blob: e0295381e57194e6774506bd8058b95fb3c87d1b [file] [log] [blame]
Stephen Lowriec8548fc2016-05-24 15:57:35 -05001# Copyright 2016 Rackspace
2#
3# All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
17"""
18subunit-describe-calls is a parser for subunit streams to determine what REST
19API calls are made inside of a test and in what order they are called.
20
21Runtime Arguments
22-----------------
23
Masayuki Igawabbbaad62017-11-21 16:04:03 +090024* ``--subunit, -s``: (Optional) The path to the subunit file being parsed,
25 defaults to stdin
26* ``--non-subunit-name, -n``: (Optional) The file_name that the logs are being
27 stored in
28* ``--output-file, -o``: (Optional) The path where the JSON output will be
29 written to. This contains more information than is present in stdout.
30* ``--ports, -p``: (Optional) The path to a JSON file describing the ports
31 being used by different services
Doug Schveninger8b3dc862018-02-16 21:42:27 -060032* ``--verbose, -v``: (Optional) Print Request and Response Headers and Body
33 data to stdout
34
Stephen Lowriec8548fc2016-05-24 15:57:35 -050035
36Usage
37-----
38
Stephen Lowrieb85502d2016-06-27 15:05:47 -050039subunit-describe-calls will take in either stdin subunit v1 or v2 stream or a
40file path which contains either a subunit v1 or v2 stream passed via the
41--subunit parameter. This is then parsed checking for details contained in the
42file_bytes of the --non-subunit-name parameter (the default is pythonlogging
43which is what Tempest uses to store logs). By default the OpenStack Kilo
44release port defaults (http://bit.ly/22jpF5P) are used unless a file is
45provided via the --ports option. The resulting output is dumped in JSON output
46to the path provided in the --output-file option.
Stephen Lowriec8548fc2016-05-24 15:57:35 -050047
48Ports file JSON structure
49^^^^^^^^^^^^^^^^^^^^^^^^^
Masayuki Igawa62f421d2016-06-29 14:54:04 +090050::
Stephen Lowriec8548fc2016-05-24 15:57:35 -050051
52 {
53 "<port number>": "<name of service>",
54 ...
55 }
56
57
58Output file JSON structure
59^^^^^^^^^^^^^^^^^^^^^^^^^^
Masayuki Igawa62f421d2016-06-29 14:54:04 +090060::
61
Stephen Lowriec8548fc2016-05-24 15:57:35 -050062 {
63 "full_test_name[with_id_and_tags]": [
64 {
65 "name": "The ClassName.MethodName that made the call",
66 "verb": "HTTP Verb",
67 "service": "Name of the service",
68 "url": "A shortened version of the URL called",
Stephen Lowrieb85502d2016-06-27 15:05:47 -050069 "status_code": "The status code of the response",
70 "request_headers": "The headers of the request",
71 "request_body": "The body of the request",
72 "response_headers": "The headers of the response",
73 "response_body": "The body of the response"
Stephen Lowriec8548fc2016-05-24 15:57:35 -050074 }
75 ]
76 }
77"""
78import argparse
79import collections
80import io
Stephen Lowriec8548fc2016-05-24 15:57:35 -050081import os
82import re
Stephen Lowrieb85502d2016-06-27 15:05:47 -050083import sys
Soniya Vyas55ad7cd2019-11-11 11:48:35 +053084import traceback
Stephen Lowriec8548fc2016-05-24 15:57:35 -050085
Soniya Vyas55ad7cd2019-11-11 11:48:35 +053086from cliff.command import Command
zhulingjie92b87a52019-02-21 01:05:54 +080087from oslo_serialization import jsonutils as json
Stephen Lowriec8548fc2016-05-24 15:57:35 -050088import subunit
89import testtools
90
91
Soniya Vyas55ad7cd2019-11-11 11:48:35 +053092DESCRIPTION = "Outputs all HTTP calls a given test made that were logged."
93
94
Stephen Lowriec8548fc2016-05-24 15:57:35 -050095class UrlParser(testtools.TestResult):
Soniya Vyas55ad7cd2019-11-11 11:48:35 +053096
Stephen Lowriec8548fc2016-05-24 15:57:35 -050097 uuid_re = re.compile(r'(^|[^0-9a-f])[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-'
98 '[0-9a-f]{4}-[0-9a-f]{12}([^0-9a-f]|$)')
99 id_re = re.compile(r'(^|[^0-9a-z])[0-9a-z]{8}[0-9a-z]{4}[0-9a-z]{4}'
100 '[0-9a-z]{4}[0-9a-z]{12}([^0-9a-z]|$)')
101 ip_re = re.compile(r'(^|[^0-9])[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]'
102 '{1,3}([^0-9]|$)')
103 url_re = re.compile(r'.*INFO.*Request \((?P<name>.*)\): (?P<code>[\d]{3}) '
Stephen Finucane7f4a6212018-07-06 13:58:21 +0100104 r'(?P<verb>\w*) (?P<url>.*) .*')
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500105 port_re = re.compile(r'.*:(?P<port>\d+).*')
106 path_re = re.compile(r'http[s]?://[^/]*/(?P<path>.*)')
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500107 request_re = re.compile(r'.* Request - Headers: (?P<headers>.*)')
108 response_re = re.compile(r'.* Response - Headers: (?P<headers>.*)')
109 body_re = re.compile(r'.*Body: (?P<body>.*)')
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500110
Chandan Kumar7d216dc2017-07-28 20:50:39 +0530111 # Based on newton defaults:
112 # http://docs.openstack.org/newton/config-reference/
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500113 # firewalls-default-ports.html
114 services = {
115 "8776": "Block Storage",
116 "8774": "Nova",
117 "8773": "Nova-API", "8775": "Nova-API",
118 "8386": "Sahara",
119 "35357": "Keystone", "5000": "Keystone",
120 "9292": "Glance", "9191": "Glance",
121 "9696": "Neutron",
122 "6000": "Swift", "6001": "Swift", "6002": "Swift",
123 "8004": "Heat", "8000": "Heat", "8003": "Heat",
124 "8777": "Ceilometer",
125 "80": "Horizon",
126 "8080": "Swift",
127 "443": "SSL",
128 "873": "rsync",
129 "3260": "iSCSI",
130 "3306": "MySQL",
Chandan Kumar7d216dc2017-07-28 20:50:39 +0530131 "5672": "AMQP",
132 "8082": "murano"}
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500133
134 def __init__(self, services=None):
135 super(UrlParser, self).__init__()
136 self.test_logs = {}
137 self.services = services or self.services
138
139 def addSuccess(self, test, details=None):
140 output = test.shortDescription() or test.id()
141 calls = self.parse_details(details)
142 self.test_logs.update({output: calls})
143
144 def addSkip(self, test, err, details=None):
145 output = test.shortDescription() or test.id()
146 calls = self.parse_details(details)
147 self.test_logs.update({output: calls})
148
149 def addError(self, test, err, details=None):
150 output = test.shortDescription() or test.id()
151 calls = self.parse_details(details)
152 self.test_logs.update({output: calls})
153
154 def addFailure(self, test, err, details=None):
155 output = test.shortDescription() or test.id()
156 calls = self.parse_details(details)
157 self.test_logs.update({output: calls})
158
159 def stopTestRun(self):
160 super(UrlParser, self).stopTestRun()
161
162 def startTestRun(self):
163 super(UrlParser, self).startTestRun()
164
165 def parse_details(self, details):
166 if details is None:
167 return
168
169 calls = []
170 for _, detail in details.items():
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500171 in_request = False
172 in_response = False
173 current_call = {}
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500174 for line in detail.as_text().split("\n"):
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500175 url_match = self.url_re.match(line)
176 request_match = self.request_re.match(line)
177 response_match = self.response_re.match(line)
178 body_match = self.body_re.match(line)
179
180 if url_match is not None:
181 if current_call != {}:
182 calls.append(current_call.copy())
183 current_call = {}
184 in_request, in_response = False, False
185 current_call.update({
186 "name": url_match.group("name"),
187 "verb": url_match.group("verb"),
188 "status_code": url_match.group("code"),
189 "service": self.get_service(url_match.group("url")),
190 "url": self.url_path(url_match.group("url"))})
191 elif request_match is not None:
192 in_request, in_response = True, False
193 current_call.update(
194 {"request_headers": request_match.group("headers")})
195 elif in_request and body_match is not None:
196 in_request = False
197 current_call.update(
198 {"request_body": body_match.group(
199 "body")})
200 elif response_match is not None:
201 in_request, in_response = False, True
202 current_call.update(
203 {"response_headers": response_match.group(
204 "headers")})
205 elif in_response and body_match is not None:
206 in_response = False
207 current_call.update(
208 {"response_body": body_match.group("body")})
209 if current_call != {}:
210 calls.append(current_call.copy())
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500211
212 return calls
213
214 def get_service(self, url):
215 match = self.port_re.match(url)
216 if match is not None:
217 return self.services.get(match.group("port"), "Unknown")
218 return "Unknown"
219
220 def url_path(self, url):
221 match = self.path_re.match(url)
222 if match is not None:
223 path = match.group("path")
224 path = self.uuid_re.sub(r'\1<uuid>\2', path)
225 path = self.ip_re.sub(r'\1<ip>\2', path)
226 path = self.id_re.sub(r'\1<id>\2', path)
227 return path
228 return url
229
230
231class FileAccumulator(testtools.StreamResult):
232
233 def __init__(self, non_subunit_name='pythonlogging'):
234 super(FileAccumulator, self).__init__()
235 self.route_codes = collections.defaultdict(io.BytesIO)
236 self.non_subunit_name = non_subunit_name
237
238 def status(self, **kwargs):
239 if kwargs.get('file_name') != self.non_subunit_name:
240 return
241 file_bytes = kwargs.get('file_bytes')
242 if not file_bytes:
243 return
244 route_code = kwargs.get('route_code')
245 stream = self.route_codes[route_code]
246 stream.write(file_bytes)
247
248
249class ArgumentParser(argparse.ArgumentParser):
Soniya Vyas55ad7cd2019-11-11 11:48:35 +0530250
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500251 def __init__(self):
Soniya Vyas55ad7cd2019-11-11 11:48:35 +0530252 desc = DESCRIPTION
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500253 super(ArgumentParser, self).__init__(description=desc)
Masayuki Igawa2f03bc92016-07-20 18:21:14 +0900254 self.prog = "subunit-describe-calls"
Soniya Vyas55ad7cd2019-11-11 11:48:35 +0530255 _parser_add_args(self)
Doug Schveninger8b3dc862018-02-16 21:42:27 -0600256
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500257
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500258def parse(stream, non_subunit_name, ports):
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500259 if ports is not None and os.path.exists(ports):
260 ports = json.loads(open(ports).read())
261
262 url_parser = UrlParser(ports)
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500263 suite = subunit.ByteStreamToStreamResult(
264 stream, non_subunit_name=non_subunit_name)
265 result = testtools.StreamToExtendedDecorator(url_parser)
266 accumulator = FileAccumulator(non_subunit_name)
267 result = testtools.StreamResultRouter(result)
268 result.add_rule(accumulator, 'test_id', test_id=None)
269 result.startTestRun()
270 suite.run(result)
271
272 for bytes_io in accumulator.route_codes.values(): # v1 processing
273 bytes_io.seek(0)
274 suite = subunit.ProtocolTestCase(bytes_io)
275 suite.run(url_parser)
276 result.stopTestRun()
277
278 return url_parser
279
280
Doug Schveninger8b3dc862018-02-16 21:42:27 -0600281def output(url_parser, output_file, verbose):
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500282 if output_file is not None:
283 with open(output_file, "w") as outfile:
284 outfile.write(json.dumps(url_parser.test_logs))
285 return
286
Andrea Frittolie6a375e2017-02-27 16:06:23 +0000287 for test_name in url_parser.test_logs:
288 items = url_parser.test_logs[test_name]
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500289 sys.stdout.write('{0}\n'.format(test_name))
290 if not items:
291 sys.stdout.write('\n')
292 continue
293 for item in items:
294 sys.stdout.write('\t- {0} {1} request for {2} to {3}\n'.format(
295 item.get('status_code'), item.get('verb'),
296 item.get('service'), item.get('url')))
Doug Schveninger8b3dc862018-02-16 21:42:27 -0600297 if verbose:
298 sys.stdout.write('\t\t- request headers: {0}\n'.format(
299 item.get('request_headers')))
300 sys.stdout.write('\t\t- request body: {0}\n'.format(
301 item.get('request_body')))
302 sys.stdout.write('\t\t- response headers: {0}\n'.format(
303 item.get('response_headers')))
304 sys.stdout.write('\t\t- response body: {0}\n'.format(
305 item.get('response_body')))
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500306 sys.stdout.write('\n')
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500307
308
Soniya Vyas55ad7cd2019-11-11 11:48:35 +0530309def entry_point(cl_args=None):
310 print('Running subunit_describe_calls ...')
311 if not cl_args:
312 print("Use of: 'subunit-describe-calls' is deprecated, "
313 "please use: 'tempest subunit-describe-calls'")
314 cl_args = ArgumentParser().parse_args()
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500315 parser = parse(cl_args.subunit, cl_args.non_subunit_name, cl_args.ports)
Doug Schveninger8b3dc862018-02-16 21:42:27 -0600316 output(parser, cl_args.output_file, cl_args.verbose)
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500317
318
Soniya Vyas55ad7cd2019-11-11 11:48:35 +0530319def _parser_add_args(parser):
320 parser.add_argument(
321 "-s", "--subunit", metavar="<subunit file>",
322 nargs="?", type=argparse.FileType('rb'), default=sys.stdin,
323 help="The path to the subunit output file(default:stdin v1/v2 stream)"
324 )
325
326 parser.add_argument(
327 "-n", "--non-subunit-name", metavar="<non subunit name>",
328 default="pythonlogging",
329 help="The name used in subunit to describe the file contents."
330 )
331
332 parser.add_argument(
333 "-o", "--output-file", metavar="<output file>", default=None,
334 help="The output file name for the json."
335 )
336
337 parser.add_argument(
338 "-p", "--ports", metavar="<ports file>", default=None,
339 help="A JSON file describing the ports for each service."
340 )
341
342 parser.add_argument(
343 "-v", "--verbose", action='store_true', default=False,
344 help="Add Request and Response header and body data to stdout."
345 )
346
347
348class TempestSubunitDescribeCalls(Command):
349
350 def get_parser(self, prog_name):
351 parser = super(TempestSubunitDescribeCalls, self).get_parser(prog_name)
352 _parser_add_args(parser)
353 return parser
354
355 def take_action(self, parsed_args):
356 try:
357 entry_point(parsed_args)
358
359 except Exception:
360 traceback.print_exc()
361 raise
362
363 def get_description(self):
364 return DESCRIPTION
365
366
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500367if __name__ == "__main__":
368 entry_point()