blob: f9ebe20309cf7b51d83a416eb1946f63d7059f52 [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
Stephen Lowrieb85502d2016-06-27 15:05:47 -050024**--subunit, -s**: (Optional) The path to the subunit file being parsed,
25defaults to stdin
Stephen Lowriec8548fc2016-05-24 15:57:35 -050026
27**--non-subunit-name, -n**: (Optional) The file_name that the logs are being
28stored in
29
Stephen Lowrieb85502d2016-06-27 15:05:47 -050030**--output-file, -o**: (Optional) The path where the JSON output will be
31written to. This contains more information than is present in stdout.
Stephen Lowriec8548fc2016-05-24 15:57:35 -050032
33**--ports, -p**: (Optional) The path to a JSON file describing the ports being
34used by different services
35
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
81import json
82import os
83import re
Stephen Lowrieb85502d2016-06-27 15:05:47 -050084import sys
Stephen Lowriec8548fc2016-05-24 15:57:35 -050085
86import subunit
87import testtools
88
89
90class UrlParser(testtools.TestResult):
91 uuid_re = re.compile(r'(^|[^0-9a-f])[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-'
92 '[0-9a-f]{4}-[0-9a-f]{12}([^0-9a-f]|$)')
93 id_re = re.compile(r'(^|[^0-9a-z])[0-9a-z]{8}[0-9a-z]{4}[0-9a-z]{4}'
94 '[0-9a-z]{4}[0-9a-z]{12}([^0-9a-z]|$)')
95 ip_re = re.compile(r'(^|[^0-9])[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]'
96 '{1,3}([^0-9]|$)')
97 url_re = re.compile(r'.*INFO.*Request \((?P<name>.*)\): (?P<code>[\d]{3}) '
98 '(?P<verb>\w*) (?P<url>.*) .*')
99 port_re = re.compile(r'.*:(?P<port>\d+).*')
100 path_re = re.compile(r'http[s]?://[^/]*/(?P<path>.*)')
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500101 request_re = re.compile(r'.* Request - Headers: (?P<headers>.*)')
102 response_re = re.compile(r'.* Response - Headers: (?P<headers>.*)')
103 body_re = re.compile(r'.*Body: (?P<body>.*)')
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500104
Chandan Kumar7d216dc2017-07-28 20:50:39 +0530105 # Based on newton defaults:
106 # http://docs.openstack.org/newton/config-reference/
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500107 # firewalls-default-ports.html
108 services = {
109 "8776": "Block Storage",
110 "8774": "Nova",
111 "8773": "Nova-API", "8775": "Nova-API",
112 "8386": "Sahara",
113 "35357": "Keystone", "5000": "Keystone",
114 "9292": "Glance", "9191": "Glance",
115 "9696": "Neutron",
116 "6000": "Swift", "6001": "Swift", "6002": "Swift",
117 "8004": "Heat", "8000": "Heat", "8003": "Heat",
118 "8777": "Ceilometer",
119 "80": "Horizon",
120 "8080": "Swift",
121 "443": "SSL",
122 "873": "rsync",
123 "3260": "iSCSI",
124 "3306": "MySQL",
Chandan Kumar7d216dc2017-07-28 20:50:39 +0530125 "5672": "AMQP",
126 "8082": "murano"}
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500127
128 def __init__(self, services=None):
129 super(UrlParser, self).__init__()
130 self.test_logs = {}
131 self.services = services or self.services
132
133 def addSuccess(self, test, details=None):
134 output = test.shortDescription() or test.id()
135 calls = self.parse_details(details)
136 self.test_logs.update({output: calls})
137
138 def addSkip(self, test, err, details=None):
139 output = test.shortDescription() or test.id()
140 calls = self.parse_details(details)
141 self.test_logs.update({output: calls})
142
143 def addError(self, test, err, details=None):
144 output = test.shortDescription() or test.id()
145 calls = self.parse_details(details)
146 self.test_logs.update({output: calls})
147
148 def addFailure(self, test, err, details=None):
149 output = test.shortDescription() or test.id()
150 calls = self.parse_details(details)
151 self.test_logs.update({output: calls})
152
153 def stopTestRun(self):
154 super(UrlParser, self).stopTestRun()
155
156 def startTestRun(self):
157 super(UrlParser, self).startTestRun()
158
159 def parse_details(self, details):
160 if details is None:
161 return
162
163 calls = []
164 for _, detail in details.items():
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500165 in_request = False
166 in_response = False
167 current_call = {}
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500168 for line in detail.as_text().split("\n"):
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500169 url_match = self.url_re.match(line)
170 request_match = self.request_re.match(line)
171 response_match = self.response_re.match(line)
172 body_match = self.body_re.match(line)
173
174 if url_match is not None:
175 if current_call != {}:
176 calls.append(current_call.copy())
177 current_call = {}
178 in_request, in_response = False, False
179 current_call.update({
180 "name": url_match.group("name"),
181 "verb": url_match.group("verb"),
182 "status_code": url_match.group("code"),
183 "service": self.get_service(url_match.group("url")),
184 "url": self.url_path(url_match.group("url"))})
185 elif request_match is not None:
186 in_request, in_response = True, False
187 current_call.update(
188 {"request_headers": request_match.group("headers")})
189 elif in_request and body_match is not None:
190 in_request = False
191 current_call.update(
192 {"request_body": body_match.group(
193 "body")})
194 elif response_match is not None:
195 in_request, in_response = False, True
196 current_call.update(
197 {"response_headers": response_match.group(
198 "headers")})
199 elif in_response and body_match is not None:
200 in_response = False
201 current_call.update(
202 {"response_body": body_match.group("body")})
203 if current_call != {}:
204 calls.append(current_call.copy())
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500205
206 return calls
207
208 def get_service(self, url):
209 match = self.port_re.match(url)
210 if match is not None:
211 return self.services.get(match.group("port"), "Unknown")
212 return "Unknown"
213
214 def url_path(self, url):
215 match = self.path_re.match(url)
216 if match is not None:
217 path = match.group("path")
218 path = self.uuid_re.sub(r'\1<uuid>\2', path)
219 path = self.ip_re.sub(r'\1<ip>\2', path)
220 path = self.id_re.sub(r'\1<id>\2', path)
221 return path
222 return url
223
224
225class FileAccumulator(testtools.StreamResult):
226
227 def __init__(self, non_subunit_name='pythonlogging'):
228 super(FileAccumulator, self).__init__()
229 self.route_codes = collections.defaultdict(io.BytesIO)
230 self.non_subunit_name = non_subunit_name
231
232 def status(self, **kwargs):
233 if kwargs.get('file_name') != self.non_subunit_name:
234 return
235 file_bytes = kwargs.get('file_bytes')
236 if not file_bytes:
237 return
238 route_code = kwargs.get('route_code')
239 stream = self.route_codes[route_code]
240 stream.write(file_bytes)
241
242
243class ArgumentParser(argparse.ArgumentParser):
244 def __init__(self):
245 desc = "Outputs all HTTP calls a given test made that were logged."
246 super(ArgumentParser, self).__init__(description=desc)
247
Masayuki Igawa2f03bc92016-07-20 18:21:14 +0900248 self.prog = "subunit-describe-calls"
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500249
250 self.add_argument(
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500251 "-s", "--subunit", metavar="<subunit file>",
252 nargs="?", type=argparse.FileType('rb'), default=sys.stdin,
253 help="The path to the subunit output file.")
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500254
255 self.add_argument(
256 "-n", "--non-subunit-name", metavar="<non subunit name>",
257 default="pythonlogging",
258 help="The name used in subunit to describe the file contents.")
259
260 self.add_argument(
261 "-o", "--output-file", metavar="<output file>", default=None,
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500262 help="The output file name for the json.")
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500263
264 self.add_argument(
265 "-p", "--ports", metavar="<ports file>", default=None,
266 help="A JSON file describing the ports for each service.")
267
268
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500269def parse(stream, non_subunit_name, ports):
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500270 if ports is not None and os.path.exists(ports):
271 ports = json.loads(open(ports).read())
272
273 url_parser = UrlParser(ports)
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500274 suite = subunit.ByteStreamToStreamResult(
275 stream, non_subunit_name=non_subunit_name)
276 result = testtools.StreamToExtendedDecorator(url_parser)
277 accumulator = FileAccumulator(non_subunit_name)
278 result = testtools.StreamResultRouter(result)
279 result.add_rule(accumulator, 'test_id', test_id=None)
280 result.startTestRun()
281 suite.run(result)
282
283 for bytes_io in accumulator.route_codes.values(): # v1 processing
284 bytes_io.seek(0)
285 suite = subunit.ProtocolTestCase(bytes_io)
286 suite.run(url_parser)
287 result.stopTestRun()
288
289 return url_parser
290
291
292def output(url_parser, output_file):
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500293 if output_file is not None:
294 with open(output_file, "w") as outfile:
295 outfile.write(json.dumps(url_parser.test_logs))
296 return
297
Andrea Frittolie6a375e2017-02-27 16:06:23 +0000298 for test_name in url_parser.test_logs:
299 items = url_parser.test_logs[test_name]
Stephen Lowrieb85502d2016-06-27 15:05:47 -0500300 sys.stdout.write('{0}\n'.format(test_name))
301 if not items:
302 sys.stdout.write('\n')
303 continue
304 for item in items:
305 sys.stdout.write('\t- {0} {1} request for {2} to {3}\n'.format(
306 item.get('status_code'), item.get('verb'),
307 item.get('service'), item.get('url')))
308 sys.stdout.write('\n')
Stephen Lowriec8548fc2016-05-24 15:57:35 -0500309
310
311def entry_point():
312 cl_args = ArgumentParser().parse_args()
313 parser = parse(cl_args.subunit, cl_args.non_subunit_name, cl_args.ports)
314 output(parser, cl_args.output_file)
315
316
317if __name__ == "__main__":
318 entry_point()