blob: c990adde32bddaf63027b1a9259a2dcfdafd8265 [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
24**--subunit, -s**: (Required) The path to the subunit file being parsed
25
26**--non-subunit-name, -n**: (Optional) The file_name that the logs are being
27stored in
28
29**--output-file, -o**: (Required) The path where the JSON output will be
30written to
31
32**--ports, -p**: (Optional) The path to a JSON file describing the ports being
33used by different services
34
35Usage
36-----
37
38subunit-describe-calls will take in a file path via the --subunit parameter
39which contains either a subunit v1 or v2 stream. This is then parsed checking
40for details contained in the file_bytes of the --non-subunit-name parameter
41(the default is pythonlogging which is what Tempest uses to store logs). By
42default the OpenStack Kilo release port defaults (http://bit.ly/22jpF5P)
43are used unless a file is provided via the --ports option. The resulting output
44is dumped in JSON output to the path provided in the --output-file option.
45
46Ports file JSON structure
47^^^^^^^^^^^^^^^^^^^^^^^^^
48
49 {
50 "<port number>": "<name of service>",
51 ...
52 }
53
54
55Output file JSON structure
56^^^^^^^^^^^^^^^^^^^^^^^^^^
57 {
58 "full_test_name[with_id_and_tags]": [
59 {
60 "name": "The ClassName.MethodName that made the call",
61 "verb": "HTTP Verb",
62 "service": "Name of the service",
63 "url": "A shortened version of the URL called",
64 "status_code": "The status code of the response"
65 }
66 ]
67 }
68"""
69import argparse
70import collections
71import io
72import json
73import os
74import re
75
76import subunit
77import testtools
78
79
80class UrlParser(testtools.TestResult):
81 uuid_re = re.compile(r'(^|[^0-9a-f])[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-'
82 '[0-9a-f]{4}-[0-9a-f]{12}([^0-9a-f]|$)')
83 id_re = re.compile(r'(^|[^0-9a-z])[0-9a-z]{8}[0-9a-z]{4}[0-9a-z]{4}'
84 '[0-9a-z]{4}[0-9a-z]{12}([^0-9a-z]|$)')
85 ip_re = re.compile(r'(^|[^0-9])[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]'
86 '{1,3}([^0-9]|$)')
87 url_re = re.compile(r'.*INFO.*Request \((?P<name>.*)\): (?P<code>[\d]{3}) '
88 '(?P<verb>\w*) (?P<url>.*) .*')
89 port_re = re.compile(r'.*:(?P<port>\d+).*')
90 path_re = re.compile(r'http[s]?://[^/]*/(?P<path>.*)')
91
92 # Based on mitaka defaults:
93 # http://docs.openstack.org/mitaka/config-reference/
94 # firewalls-default-ports.html
95 services = {
96 "8776": "Block Storage",
97 "8774": "Nova",
98 "8773": "Nova-API", "8775": "Nova-API",
99 "8386": "Sahara",
100 "35357": "Keystone", "5000": "Keystone",
101 "9292": "Glance", "9191": "Glance",
102 "9696": "Neutron",
103 "6000": "Swift", "6001": "Swift", "6002": "Swift",
104 "8004": "Heat", "8000": "Heat", "8003": "Heat",
105 "8777": "Ceilometer",
106 "80": "Horizon",
107 "8080": "Swift",
108 "443": "SSL",
109 "873": "rsync",
110 "3260": "iSCSI",
111 "3306": "MySQL",
112 "5672": "AMQP"}
113
114 def __init__(self, services=None):
115 super(UrlParser, self).__init__()
116 self.test_logs = {}
117 self.services = services or self.services
118
119 def addSuccess(self, test, details=None):
120 output = test.shortDescription() or test.id()
121 calls = self.parse_details(details)
122 self.test_logs.update({output: calls})
123
124 def addSkip(self, test, err, details=None):
125 output = test.shortDescription() or test.id()
126 calls = self.parse_details(details)
127 self.test_logs.update({output: calls})
128
129 def addError(self, test, err, details=None):
130 output = test.shortDescription() or test.id()
131 calls = self.parse_details(details)
132 self.test_logs.update({output: calls})
133
134 def addFailure(self, test, err, details=None):
135 output = test.shortDescription() or test.id()
136 calls = self.parse_details(details)
137 self.test_logs.update({output: calls})
138
139 def stopTestRun(self):
140 super(UrlParser, self).stopTestRun()
141
142 def startTestRun(self):
143 super(UrlParser, self).startTestRun()
144
145 def parse_details(self, details):
146 if details is None:
147 return
148
149 calls = []
150 for _, detail in details.items():
151 for line in detail.as_text().split("\n"):
152 match = self.url_re.match(line)
153 if match is not None:
154 calls.append({
155 "name": match.group("name"),
156 "verb": match.group("verb"),
157 "status_code": match.group("code"),
158 "service": self.get_service(match.group("url")),
159 "url": self.url_path(match.group("url"))})
160
161 return calls
162
163 def get_service(self, url):
164 match = self.port_re.match(url)
165 if match is not None:
166 return self.services.get(match.group("port"), "Unknown")
167 return "Unknown"
168
169 def url_path(self, url):
170 match = self.path_re.match(url)
171 if match is not None:
172 path = match.group("path")
173 path = self.uuid_re.sub(r'\1<uuid>\2', path)
174 path = self.ip_re.sub(r'\1<ip>\2', path)
175 path = self.id_re.sub(r'\1<id>\2', path)
176 return path
177 return url
178
179
180class FileAccumulator(testtools.StreamResult):
181
182 def __init__(self, non_subunit_name='pythonlogging'):
183 super(FileAccumulator, self).__init__()
184 self.route_codes = collections.defaultdict(io.BytesIO)
185 self.non_subunit_name = non_subunit_name
186
187 def status(self, **kwargs):
188 if kwargs.get('file_name') != self.non_subunit_name:
189 return
190 file_bytes = kwargs.get('file_bytes')
191 if not file_bytes:
192 return
193 route_code = kwargs.get('route_code')
194 stream = self.route_codes[route_code]
195 stream.write(file_bytes)
196
197
198class ArgumentParser(argparse.ArgumentParser):
199 def __init__(self):
200 desc = "Outputs all HTTP calls a given test made that were logged."
201 super(ArgumentParser, self).__init__(description=desc)
202
203 self.prog = "Argument Parser"
204
205 self.add_argument(
206 "-s", "--subunit", metavar="<subunit file>", required=True,
207 default=None, help="The path to the subunit output file.")
208
209 self.add_argument(
210 "-n", "--non-subunit-name", metavar="<non subunit name>",
211 default="pythonlogging",
212 help="The name used in subunit to describe the file contents.")
213
214 self.add_argument(
215 "-o", "--output-file", metavar="<output file>", default=None,
216 help="The output file name for the json.", required=True)
217
218 self.add_argument(
219 "-p", "--ports", metavar="<ports file>", default=None,
220 help="A JSON file describing the ports for each service.")
221
222
223def parse(subunit_file, non_subunit_name, ports):
224 if ports is not None and os.path.exists(ports):
225 ports = json.loads(open(ports).read())
226
227 url_parser = UrlParser(ports)
228 stream = open(subunit_file, 'rb')
229 suite = subunit.ByteStreamToStreamResult(
230 stream, non_subunit_name=non_subunit_name)
231 result = testtools.StreamToExtendedDecorator(url_parser)
232 accumulator = FileAccumulator(non_subunit_name)
233 result = testtools.StreamResultRouter(result)
234 result.add_rule(accumulator, 'test_id', test_id=None)
235 result.startTestRun()
236 suite.run(result)
237
238 for bytes_io in accumulator.route_codes.values(): # v1 processing
239 bytes_io.seek(0)
240 suite = subunit.ProtocolTestCase(bytes_io)
241 suite.run(url_parser)
242 result.stopTestRun()
243
244 return url_parser
245
246
247def output(url_parser, output_file):
248 with open(output_file, "w") as outfile:
249 outfile.write(json.dumps(url_parser.test_logs))
250
251
252def entry_point():
253 cl_args = ArgumentParser().parse_args()
254 parser = parse(cl_args.subunit, cl_args.non_subunit_name, cl_args.ports)
255 output(parser, cl_args.output_file)
256
257
258if __name__ == "__main__":
259 entry_point()