blob: 75f36db75f56ebf883401734a079c1d0e9e3df72 [file] [log] [blame]
Roger Meier41ad4342015-03-24 22:30:40 +01001#
2# Licensed to the Apache Software Foundation (ASF) under one
3# or more contributor license agreements. See the NOTICE file
4# distributed with this work for additional information
5# regarding copyright ownership. The ASF licenses this file
6# to you under the Apache License, Version 2.0 (the
7# "License"); you may not use this file except in compliance
8# with the License. You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing,
13# software distributed under the License is distributed on an
14# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15# KIND, either express or implied. See the License for the
16# specific language governing permissions and limitations
17# under the License.
18#
19
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090020from __future__ import print_function
Roger Meier41ad4342015-03-24 22:30:40 +010021import datetime
22import json
23import multiprocessing
24import os
25import platform
26import re
27import subprocess
28import sys
29import time
30import traceback
31
Nobuaki Sukegawaa6ab1f52015-11-28 15:04:39 +090032from .compat import logfile_open, path_join, str_join
Nobuaki Sukegawa2de27002015-11-22 01:13:48 +090033from .test import TestEntry
Roger Meier41ad4342015-03-24 22:30:40 +010034
35LOG_DIR = 'log'
Nobuaki Sukegawabd165302016-01-19 11:10:07 +090036RESULT_HTML = 'index.html'
Roger Meier41ad4342015-03-24 22:30:40 +010037RESULT_JSON = 'results.json'
38FAIL_JSON = 'known_failures_%s.json'
39
40
41def generate_known_failures(testdir, overwrite, save, out):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090042 def collect_failures(results):
43 success_index = 5
44 for r in results:
45 if not r[success_index]:
46 yield TestEntry.get_name(*r)
47 try:
48 with logfile_open(path_join(testdir, RESULT_JSON), 'r') as fp:
49 results = json.load(fp)
50 except IOError:
51 sys.stderr.write('Unable to load last result. Did you run tests ?\n')
52 return False
53 fails = collect_failures(results['results'])
54 if not overwrite:
55 known = load_known_failures(testdir)
56 known.extend(fails)
57 fails = known
58 fails_json = json.dumps(sorted(set(fails)), indent=2, separators=(',', ': '))
59 if save:
60 with logfile_open(os.path.join(testdir, FAIL_JSON % platform.system()), 'w+') as fp:
61 fp.write(fails_json)
62 sys.stdout.write('Successfully updated known failures.\n')
63 if out:
64 sys.stdout.write(fails_json)
65 sys.stdout.write('\n')
66 return True
Roger Meier41ad4342015-03-24 22:30:40 +010067
68
69def load_known_failures(testdir):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090070 try:
71 with logfile_open(path_join(testdir, FAIL_JSON % platform.system()), 'r') as fp:
72 return json.load(fp)
73 except IOError:
74 return []
Roger Meier41ad4342015-03-24 22:30:40 +010075
76
77class TestReporter(object):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090078 # Unfortunately, standard library doesn't handle timezone well
79 # DATETIME_FORMAT = '%a %b %d %H:%M:%S %Z %Y'
80 DATETIME_FORMAT = '%a %b %d %H:%M:%S %Y'
Roger Meier41ad4342015-03-24 22:30:40 +010081
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090082 def __init__(self):
83 self._log = multiprocessing.get_logger()
84 self._lock = multiprocessing.Lock()
Roger Meier41ad4342015-03-24 22:30:40 +010085
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090086 @classmethod
87 def test_logfile(cls, test_name, prog_kind, dir=None):
88 relpath = path_join('log', '%s_%s.log' % (test_name, prog_kind))
89 return relpath if not dir else os.path.realpath(path_join(dir, relpath))
Roger Meier41ad4342015-03-24 22:30:40 +010090
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090091 def _start(self):
92 self._start_time = time.time()
Roger Meier41ad4342015-03-24 22:30:40 +010093
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090094 @property
95 def _elapsed(self):
96 return time.time() - self._start_time
Roger Meier41ad4342015-03-24 22:30:40 +010097
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +090098 @classmethod
99 def _format_date(cls):
100 return '%s' % datetime.datetime.now().strftime(cls.DATETIME_FORMAT)
Roger Meier41ad4342015-03-24 22:30:40 +0100101
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900102 def _print_date(self):
103 print(self._format_date(), file=self.out)
Roger Meier41ad4342015-03-24 22:30:40 +0100104
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900105 def _print_bar(self, out=None):
106 print(
Gonzalo Aguilar Delgadobc0082e2016-03-04 13:16:22 +0100107 '===============================================================================',
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900108 file=(out or self.out))
Roger Meier41ad4342015-03-24 22:30:40 +0100109
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900110 def _print_exec_time(self):
111 print('Test execution took {:.1f} seconds.'.format(self._elapsed), file=self.out)
Roger Meier41ad4342015-03-24 22:30:40 +0100112
113
114class ExecReporter(TestReporter):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900115 def __init__(self, testdir, test, prog):
116 super(ExecReporter, self).__init__()
117 self._test = test
118 self._prog = prog
119 self.logpath = self.test_logfile(test.name, prog.kind, testdir)
Roger Meier41ad4342015-03-24 22:30:40 +0100120 self.out = None
Roger Meier41ad4342015-03-24 22:30:40 +0100121
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900122 def begin(self):
123 self._start()
124 self._open()
125 if self.out and not self.out.closed:
126 self._print_header()
127 else:
128 self._log.debug('Output stream is not available.')
Nobuaki Sukegawa2ba79442016-01-12 19:37:55 +0900129
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900130 def end(self, returncode):
131 self._lock.acquire()
132 try:
133 if self.out and not self.out.closed:
134 self._print_footer(returncode)
135 self._close()
136 self.out = None
137 else:
138 self._log.debug('Output stream is not available.')
139 finally:
140 self._lock.release()
Roger Meier41ad4342015-03-24 22:30:40 +0100141
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900142 def killed(self):
143 print(file=self.out)
144 print('Server process is successfully killed.', file=self.out)
145 self.end(None)
Roger Meier41ad4342015-03-24 22:30:40 +0100146
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900147 def died(self):
148 print(file=self.out)
149 print('*** Server process has died unexpectedly ***', file=self.out)
150 self.end(None)
151
152 _init_failure_exprs = {
153 'server': list(map(re.compile, [
154 '[Aa]ddress already in use',
155 'Could not bind',
156 'EADDRINUSE',
157 ])),
158 'client': list(map(re.compile, [
159 '[Cc]onnection refused',
James E. King III9bea32f2018-03-16 16:07:42 -0400160 'Could not connect to',
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900161 'ECONNREFUSED',
James E. King III9bea32f2018-03-16 16:07:42 -0400162 'econnrefused', # erl
163 'CONNECTION-REFUSED-ERROR', # cl
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900164 'No such file or directory', # domain socket
165 ])),
166 }
167
168 def maybe_false_positive(self):
169 """Searches through log file for socket bind error.
170 Returns True if suspicious expression is found, otherwise False"""
171 try:
172 if self.out and not self.out.closed:
173 self.out.flush()
174 exprs = self._init_failure_exprs[self._prog.kind]
175
176 def match(line):
177 for expr in exprs:
178 if expr.search(line):
James E. King III9bea32f2018-03-16 16:07:42 -0400179 self._log.info("maybe false positive: %s" % line)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900180 return True
181
182 with logfile_open(self.logpath, 'r') as fp:
183 if any(map(match, fp)):
184 return True
185 except (KeyboardInterrupt, SystemExit):
186 raise
187 except Exception as ex:
188 self._log.warn('[%s]: Error while detecting false positive: %s' % (self._test.name, str(ex)))
189 self._log.info(traceback.print_exc())
190 return False
191
192 def _open(self):
193 self.out = logfile_open(self.logpath, 'w+')
194
195 def _close(self):
196 self.out.close()
197
198 def _print_header(self):
199 self._print_date()
200 print('Executing: %s' % str_join(' ', self._prog.command), file=self.out)
201 print('Directory: %s' % self._prog.workdir, file=self.out)
202 print('config:delay: %s' % self._test.delay, file=self.out)
203 print('config:timeout: %s' % self._test.timeout, file=self.out)
204 self._print_bar()
Roger Meier41ad4342015-03-24 22:30:40 +0100205 self.out.flush()
Roger Meier41ad4342015-03-24 22:30:40 +0100206
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900207 def _print_footer(self, returncode=None):
208 self._print_bar()
209 if returncode is not None:
James E. King III9bea32f2018-03-16 16:07:42 -0400210 print('Return code: %d (negative values indicate kill by signal)' % returncode, file=self.out)
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900211 else:
212 print('Process is killed.', file=self.out)
213 self._print_exec_time()
214 self._print_date()
Roger Meier41ad4342015-03-24 22:30:40 +0100215
216
217class SummaryReporter(TestReporter):
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900218 def __init__(self, basedir, testdir_relative, concurrent=True):
219 super(SummaryReporter, self).__init__()
220 self._basedir = basedir
221 self._testdir_rel = testdir_relative
222 self.logdir = path_join(self.testdir, LOG_DIR)
223 self.out_path = path_join(self.testdir, RESULT_JSON)
224 self.concurrent = concurrent
225 self.out = sys.stdout
226 self._platform = platform.system()
227 self._revision = self._get_revision()
228 self._tests = []
229 if not os.path.exists(self.logdir):
230 os.mkdir(self.logdir)
231 self._known_failures = load_known_failures(self.testdir)
232 self._unexpected_success = []
233 self._flaky_success = []
234 self._unexpected_failure = []
235 self._expected_failure = []
236 self._print_header()
Roger Meier41ad4342015-03-24 22:30:40 +0100237
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900238 @property
239 def testdir(self):
240 return path_join(self._basedir, self._testdir_rel)
Nobuaki Sukegawabd165302016-01-19 11:10:07 +0900241
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900242 def _result_string(self, test):
243 if test.success:
244 if test.retry_count == 0:
245 return 'success'
246 elif test.retry_count == 1:
247 return 'flaky(1 retry)'
248 else:
249 return 'flaky(%d retries)' % test.retry_count
250 elif test.expired:
251 return 'failure(timeout)'
Roger Meier41ad4342015-03-24 22:30:40 +0100252 else:
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900253 return 'failure(%d)' % test.returncode
254
255 def _get_revision(self):
256 p = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'],
257 cwd=self.testdir, stdout=subprocess.PIPE)
258 out, _ = p.communicate()
259 return out.strip()
260
261 def _format_test(self, test, with_result=True):
262 name = '%s-%s' % (test.server.name, test.client.name)
263 trans = '%s-%s' % (test.transport, test.socket)
264 if not with_result:
Gonzalo Aguilar Delgadobc0082e2016-03-04 13:16:22 +0100265 return '{:24s}{:18s}{:25s}'.format(name[:23], test.protocol[:17], trans[:24])
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900266 else:
James E. King III9bea32f2018-03-16 16:07:42 -0400267 return '{:24s}{:18s}{:25s}{:s}\n'.format(name[:23], test.protocol[:17],
268 trans[:24], self._result_string(test))
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900269
270 def _print_test_header(self):
271 self._print_bar()
272 print(
Gonzalo Aguilar Delgadobc0082e2016-03-04 13:16:22 +0100273 '{:24s}{:18s}{:25s}{:s}'.format('server-client:', 'protocol:', 'transport:', 'result:'),
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900274 file=self.out)
275
276 def _print_header(self):
277 self._start()
278 print('Apache Thrift - Integration Test Suite', file=self.out)
279 self._print_date()
280 self._print_test_header()
281
282 def _print_unexpected_failure(self):
283 if len(self._unexpected_failure) > 0:
284 self.out.writelines([
285 '*** Following %d failures were unexpected ***:\n' % len(self._unexpected_failure),
286 'If it is introduced by you, please fix it before submitting the code.\n',
287 # 'If not, please report at https://issues.apache.org/jira/browse/THRIFT\n',
288 ])
289 self._print_test_header()
290 for i in self._unexpected_failure:
291 self.out.write(self._format_test(self._tests[i]))
292 self._print_bar()
293 else:
294 print('No unexpected failures.', file=self.out)
295
296 def _print_flaky_success(self):
297 if len(self._flaky_success) > 0:
298 print(
299 'Following %d tests were expected to cleanly succeed but needed retry:' % len(self._flaky_success),
300 file=self.out)
301 self._print_test_header()
302 for i in self._flaky_success:
303 self.out.write(self._format_test(self._tests[i]))
304 self._print_bar()
305
306 def _print_unexpected_success(self):
307 if len(self._unexpected_success) > 0:
308 print(
309 'Following %d tests were known to fail but succeeded (maybe flaky):' % len(self._unexpected_success),
310 file=self.out)
311 self._print_test_header()
312 for i in self._unexpected_success:
313 self.out.write(self._format_test(self._tests[i]))
314 self._print_bar()
315
316 def _http_server_command(self, port):
317 if sys.version_info[0] < 3:
318 return 'python -m SimpleHTTPServer %d' % port
319 else:
320 return 'python -m http.server %d' % port
321
322 def _print_footer(self):
323 fail_count = len(self._expected_failure) + len(self._unexpected_failure)
324 self._print_bar()
325 self._print_unexpected_success()
326 self._print_flaky_success()
327 self._print_unexpected_failure()
328 self._write_html_data()
329 self._assemble_log('unexpected failures', self._unexpected_failure)
330 self._assemble_log('known failures', self._expected_failure)
331 self.out.writelines([
332 'You can browse results at:\n',
333 '\tfile://%s/%s\n' % (self.testdir, RESULT_HTML),
334 '# If you use Chrome, run:\n',
335 '# \tcd %s\n#\t%s\n' % (self._basedir, self._http_server_command(8001)),
336 '# then browse:\n',
337 '# \thttp://localhost:%d/%s/\n' % (8001, self._testdir_rel),
338 'Full log for each test is here:\n',
James E. King, III375bfee2017-10-26 00:09:34 -0400339 '\ttest/log/server_client_protocol_transport_client.log\n',
340 '\ttest/log/server_client_protocol_transport_server.log\n',
Nobuaki Sukegawa10308cb2016-02-03 01:57:03 +0900341 '%d failed of %d tests in total.\n' % (fail_count, len(self._tests)),
342 ])
343 self._print_exec_time()
344 self._print_date()
345
346 def _render_result(self, test):
347 return [
348 test.server.name,
349 test.client.name,
350 test.protocol,
351 test.transport,
352 test.socket,
353 test.success,
354 test.as_expected,
355 test.returncode,
356 {
357 'server': self.test_logfile(test.name, test.server.kind),
358 'client': self.test_logfile(test.name, test.client.kind),
359 },
360 ]
361
362 def _write_html_data(self):
363 """Writes JSON data to be read by result html"""
364 results = [self._render_result(r) for r in self._tests]
365 with logfile_open(self.out_path, 'w+') as fp:
366 fp.write(json.dumps({
367 'date': self._format_date(),
368 'revision': str(self._revision),
369 'platform': self._platform,
370 'duration': '{:.1f}'.format(self._elapsed),
371 'results': results,
372 }, indent=2))
373
374 def _assemble_log(self, title, indexes):
375 if len(indexes) > 0:
376 def add_prog_log(fp, test, prog_kind):
377 print('*************************** %s message ***************************' % prog_kind,
378 file=fp)
379 path = self.test_logfile(test.name, prog_kind, self.testdir)
380 if os.path.exists(path):
381 with logfile_open(path, 'r') as prog_fp:
382 print(prog_fp.read(), file=fp)
383 filename = title.replace(' ', '_') + '.log'
384 with logfile_open(os.path.join(self.logdir, filename), 'w+') as fp:
385 for test in map(self._tests.__getitem__, indexes):
386 fp.write('TEST: [%s]\n' % test.name)
387 add_prog_log(fp, test, test.server.kind)
388 add_prog_log(fp, test, test.client.kind)
389 fp.write('**********************************************************************\n\n')
390 print('%s are logged to %s/%s/%s' % (title.capitalize(), self._testdir_rel, LOG_DIR, filename))
391
392 def end(self):
393 self._print_footer()
394 return len(self._unexpected_failure) == 0
395
396 def add_test(self, test_dict):
397 test = TestEntry(self.testdir, **test_dict)
398 self._lock.acquire()
399 try:
400 if not self.concurrent:
401 self.out.write(self._format_test(test, False))
402 self.out.flush()
403 self._tests.append(test)
404 return len(self._tests) - 1
405 finally:
406 self._lock.release()
407
408 def add_result(self, index, returncode, expired, retry_count):
409 self._lock.acquire()
410 try:
411 failed = returncode is None or returncode != 0
412 flaky = not failed and retry_count != 0
413 test = self._tests[index]
414 known = test.name in self._known_failures
415 if failed:
416 if known:
417 self._log.debug('%s failed as expected' % test.name)
418 self._expected_failure.append(index)
419 else:
420 self._log.info('unexpected failure: %s' % test.name)
421 self._unexpected_failure.append(index)
422 elif flaky and not known:
423 self._log.info('unexpected flaky success: %s' % test.name)
424 self._flaky_success.append(index)
425 elif not flaky and known:
426 self._log.info('unexpected success: %s' % test.name)
427 self._unexpected_success.append(index)
428 test.success = not failed
429 test.returncode = returncode
430 test.retry_count = retry_count
431 test.expired = expired
432 test.as_expected = known == failed
433 if not self.concurrent:
434 self.out.write(self._result_string(test) + '\n')
435 else:
436 self.out.write(self._format_test(test))
437 finally:
438 self._lock.release()