oe-build-perf-report 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. #!/usr/bin/python3
  2. #
  3. # Examine build performance test results
  4. #
  5. # Copyright (c) 2017, Intel Corporation.
  6. #
  7. # This program is free software; you can redistribute it and/or modify it
  8. # under the terms and conditions of the GNU General Public License,
  9. # version 2, as published by the Free Software Foundation.
  10. #
  11. # This program is distributed in the hope it will be useful, but WITHOUT
  12. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  14. # more details.
  15. #
  16. import argparse
  17. import json
  18. import logging
  19. import os
  20. import re
  21. import sys
  22. from collections import namedtuple, OrderedDict
  23. from operator import attrgetter
  24. from xml.etree import ElementTree as ET
  25. # Import oe libs
  26. scripts_path = os.path.dirname(os.path.realpath(__file__))
  27. sys.path.append(os.path.join(scripts_path, 'lib'))
  28. import scriptpath
  29. from build_perf import print_table
  30. from build_perf.report import (metadata_xml_to_json, results_xml_to_json,
  31. aggregate_data, aggregate_metadata, measurement_stats)
  32. from build_perf import html
  33. scriptpath.add_oe_lib_path()
  34. from oeqa.utils.git import GitRepo
  35. # Setup logging
  36. logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
  37. log = logging.getLogger('oe-build-perf-report')
  38. # Container class for tester revisions
  39. TestedRev = namedtuple('TestedRev', 'commit commit_number tags')
  40. def get_test_runs(repo, tag_name, **kwargs):
  41. """Get a sorted list of test runs, matching given pattern"""
  42. # First, get field names from the tag name pattern
  43. field_names = [m.group(1) for m in re.finditer(r'{(\w+)}', tag_name)]
  44. undef_fields = [f for f in field_names if f not in kwargs.keys()]
  45. # Fields for formatting tag name pattern
  46. str_fields = dict([(f, '*') for f in field_names])
  47. str_fields.update(kwargs)
  48. # Get a list of all matching tags
  49. tag_pattern = tag_name.format(**str_fields)
  50. tags = repo.run_cmd(['tag', '-l', tag_pattern]).splitlines()
  51. log.debug("Found %d tags matching pattern '%s'", len(tags), tag_pattern)
  52. # Parse undefined fields from tag names
  53. str_fields = dict([(f, r'(?P<{}>[\w\-.()]+)'.format(f)) for f in field_names])
  54. str_fields['branch'] = r'(?P<branch>[\w\-.()/]+)'
  55. str_fields['commit'] = '(?P<commit>[0-9a-f]{7,40})'
  56. str_fields['commit_number'] = '(?P<commit_number>[0-9]{1,7})'
  57. str_fields['tag_number'] = '(?P<tag_number>[0-9]{1,5})'
  58. # escape parenthesis in fields in order to not messa up the regexp
  59. fixed_fields = dict([(k, v.replace('(', r'\(').replace(')', r'\)')) for k, v in kwargs.items()])
  60. str_fields.update(fixed_fields)
  61. tag_re = re.compile(tag_name.format(**str_fields))
  62. # Parse fields from tags
  63. revs = []
  64. for tag in tags:
  65. m = tag_re.match(tag)
  66. groups = m.groupdict()
  67. revs.append([groups[f] for f in undef_fields] + [tag])
  68. # Return field names and a sorted list of revs
  69. return undef_fields, sorted(revs)
  70. def list_test_revs(repo, tag_name, **kwargs):
  71. """Get list of all tested revisions"""
  72. fields, revs = get_test_runs(repo, tag_name, **kwargs)
  73. ignore_fields = ['tag_number']
  74. print_fields = [i for i, f in enumerate(fields) if f not in ignore_fields]
  75. # Sort revs
  76. rows = [[fields[i].upper() for i in print_fields] + ['TEST RUNS']]
  77. prev = [''] * len(revs)
  78. for rev in revs:
  79. # Only use fields that we want to print
  80. rev = [rev[i] for i in print_fields]
  81. if rev != prev:
  82. new_row = [''] * len(print_fields) + [1]
  83. for i in print_fields:
  84. if rev[i] != prev[i]:
  85. break
  86. new_row[i:-1] = rev[i:]
  87. rows.append(new_row)
  88. else:
  89. rows[-1][-1] += 1
  90. prev = rev
  91. print_table(rows)
  92. def get_test_revs(repo, tag_name, **kwargs):
  93. """Get list of all tested revisions"""
  94. fields, runs = get_test_runs(repo, tag_name, **kwargs)
  95. revs = {}
  96. commit_i = fields.index('commit')
  97. commit_num_i = fields.index('commit_number')
  98. for run in runs:
  99. commit = run[commit_i]
  100. commit_num = run[commit_num_i]
  101. tag = run[-1]
  102. if not commit in revs:
  103. revs[commit] = TestedRev(commit, commit_num, [tag])
  104. else:
  105. assert commit_num == revs[commit].commit_number, "Commit numbers do not match"
  106. revs[commit].tags.append(tag)
  107. # Return in sorted table
  108. revs = sorted(revs.values(), key=attrgetter('commit_number'))
  109. log.debug("Found %d tested revisions:\n %s", len(revs),
  110. "\n ".join(['{} ({})'.format(rev.commit_number, rev.commit) for rev in revs]))
  111. return revs
  112. def rev_find(revs, attr, val):
  113. """Search from a list of TestedRev"""
  114. for i, rev in enumerate(revs):
  115. if getattr(rev, attr) == val:
  116. return i
  117. raise ValueError("Unable to find '{}' value '{}'".format(attr, val))
  118. def is_xml_format(repo, commit):
  119. """Check if the commit contains xml (or json) data"""
  120. if repo.rev_parse(commit + ':results.xml'):
  121. log.debug("Detected report in xml format in %s", commit)
  122. return True
  123. else:
  124. log.debug("No xml report in %s, assuming json formatted results", commit)
  125. return False
  126. def read_results(repo, tags, xml=True):
  127. """Read result files from repo"""
  128. def parse_xml_stream(data):
  129. """Parse multiple concatenated XML objects"""
  130. objs = []
  131. xml_d = ""
  132. for line in data.splitlines():
  133. if xml_d and line.startswith('<?xml version='):
  134. objs.append(ET.fromstring(xml_d))
  135. xml_d = line
  136. else:
  137. xml_d += line
  138. objs.append(ET.fromstring(xml_d))
  139. return objs
  140. def parse_json_stream(data):
  141. """Parse multiple concatenated JSON objects"""
  142. objs = []
  143. json_d = ""
  144. for line in data.splitlines():
  145. if line == '}{':
  146. json_d += '}'
  147. objs.append(json.loads(json_d, object_pairs_hook=OrderedDict))
  148. json_d = '{'
  149. else:
  150. json_d += line
  151. objs.append(json.loads(json_d, object_pairs_hook=OrderedDict))
  152. return objs
  153. num_revs = len(tags)
  154. # Optimize by reading all data with one git command
  155. log.debug("Loading raw result data from %d tags, %s...", num_revs, tags[0])
  156. if xml:
  157. git_objs = [tag + ':metadata.xml' for tag in tags] + [tag + ':results.xml' for tag in tags]
  158. data = parse_xml_stream(repo.run_cmd(['show'] + git_objs + ['--']))
  159. return ([metadata_xml_to_json(e) for e in data[0:num_revs]],
  160. [results_xml_to_json(e) for e in data[num_revs:]])
  161. else:
  162. git_objs = [tag + ':metadata.json' for tag in tags] + [tag + ':results.json' for tag in tags]
  163. data = parse_json_stream(repo.run_cmd(['show'] + git_objs + ['--']))
  164. return data[0:num_revs], data[num_revs:]
  165. def get_data_item(data, key):
  166. """Nested getitem lookup"""
  167. for k in key.split('.'):
  168. data = data[k]
  169. return data
  170. def metadata_diff(metadata_l, metadata_r):
  171. """Prepare a metadata diff for printing"""
  172. keys = [('Hostname', 'hostname', 'hostname'),
  173. ('Branch', 'branch', 'layers.meta.branch'),
  174. ('Commit number', 'commit_num', 'layers.meta.commit_count'),
  175. ('Commit', 'commit', 'layers.meta.commit'),
  176. ('Number of test runs', 'testrun_count', 'testrun_count')
  177. ]
  178. def _metadata_diff(key):
  179. """Diff metadata from two test reports"""
  180. try:
  181. val1 = get_data_item(metadata_l, key)
  182. except KeyError:
  183. val1 = '(N/A)'
  184. try:
  185. val2 = get_data_item(metadata_r, key)
  186. except KeyError:
  187. val2 = '(N/A)'
  188. return val1, val2
  189. metadata = OrderedDict()
  190. for title, key, key_json in keys:
  191. value_l, value_r = _metadata_diff(key_json)
  192. metadata[key] = {'title': title,
  193. 'value_old': value_l,
  194. 'value': value_r}
  195. return metadata
  196. def print_diff_report(metadata_l, data_l, metadata_r, data_r):
  197. """Print differences between two data sets"""
  198. # First, print general metadata
  199. print("\nTEST METADATA:\n==============")
  200. meta_diff = metadata_diff(metadata_l, metadata_r)
  201. rows = []
  202. row_fmt = ['{:{wid}} ', '{:<{wid}} ', '{:<{wid}}']
  203. rows = [['', 'CURRENT COMMIT', 'COMPARING WITH']]
  204. for key, val in meta_diff.items():
  205. # Shorten commit hashes
  206. if key == 'commit':
  207. rows.append([val['title'] + ':', val['value'][:20], val['value_old'][:20]])
  208. else:
  209. rows.append([val['title'] + ':', val['value'], val['value_old']])
  210. print_table(rows, row_fmt)
  211. # Print test results
  212. print("\nTEST RESULTS:\n=============")
  213. tests = list(data_l['tests'].keys())
  214. # Append tests that are only present in 'right' set
  215. tests += [t for t in list(data_r['tests'].keys()) if t not in tests]
  216. # Prepare data to be printed
  217. rows = []
  218. row_fmt = ['{:8}', '{:{wid}}', '{:{wid}}', ' {:>{wid}}', ' {:{wid}} ', '{:{wid}}',
  219. ' {:>{wid}}', ' {:>{wid}}']
  220. num_cols = len(row_fmt)
  221. for test in tests:
  222. test_l = data_l['tests'][test] if test in data_l['tests'] else None
  223. test_r = data_r['tests'][test] if test in data_r['tests'] else None
  224. pref = ' '
  225. if test_l is None:
  226. pref = '+'
  227. elif test_r is None:
  228. pref = '-'
  229. descr = test_l['description'] if test_l else test_r['description']
  230. heading = "{} {}: {}".format(pref, test, descr)
  231. rows.append([heading])
  232. # Generate the list of measurements
  233. meas_l = test_l['measurements'] if test_l else {}
  234. meas_r = test_r['measurements'] if test_r else {}
  235. measurements = list(meas_l.keys())
  236. measurements += [m for m in list(meas_r.keys()) if m not in measurements]
  237. for meas in measurements:
  238. m_pref = ' '
  239. if meas in meas_l:
  240. stats_l = measurement_stats(meas_l[meas], 'l.')
  241. else:
  242. stats_l = measurement_stats(None, 'l.')
  243. m_pref = '+'
  244. if meas in meas_r:
  245. stats_r = measurement_stats(meas_r[meas], 'r.')
  246. else:
  247. stats_r = measurement_stats(None, 'r.')
  248. m_pref = '-'
  249. stats = stats_l.copy()
  250. stats.update(stats_r)
  251. absdiff = stats['val_cls'](stats['r.mean'] - stats['l.mean'])
  252. reldiff = "{:+.1f} %".format(absdiff * 100 / stats['l.mean'])
  253. if stats['r.mean'] > stats['l.mean']:
  254. absdiff = '+' + str(absdiff)
  255. else:
  256. absdiff = str(absdiff)
  257. rows.append(['', m_pref, stats['name'] + ' ' + stats['quantity'],
  258. str(stats['l.mean']), '->', str(stats['r.mean']),
  259. absdiff, reldiff])
  260. rows.append([''] * num_cols)
  261. print_table(rows, row_fmt)
  262. print()
  263. def print_html_report(data, id_comp):
  264. """Print report in html format"""
  265. # Handle metadata
  266. metadata = {'branch': {'title': 'Branch', 'value': 'master'},
  267. 'hostname': {'title': 'Hostname', 'value': 'foobar'},
  268. 'commit': {'title': 'Commit', 'value': '1234'}
  269. }
  270. metadata = metadata_diff(data[id_comp][0], data[-1][0])
  271. # Generate list of tests
  272. tests = []
  273. for test in data[-1][1]['tests'].keys():
  274. test_r = data[-1][1]['tests'][test]
  275. new_test = {'name': test_r['name'],
  276. 'description': test_r['description'],
  277. 'status': test_r['status'],
  278. 'measurements': [],
  279. 'err_type': test_r.get('err_type'),
  280. }
  281. # Limit length of err output shown
  282. if 'message' in test_r:
  283. lines = test_r['message'].splitlines()
  284. if len(lines) > 20:
  285. new_test['message'] = '...\n' + '\n'.join(lines[-20:])
  286. else:
  287. new_test['message'] = test_r['message']
  288. # Generate the list of measurements
  289. for meas in test_r['measurements'].keys():
  290. meas_r = test_r['measurements'][meas]
  291. meas_type = 'time' if meas_r['type'] == 'sysres' else 'size'
  292. new_meas = {'name': meas_r['name'],
  293. 'legend': meas_r['legend'],
  294. 'description': meas_r['name'] + ' ' + meas_type,
  295. }
  296. samples = []
  297. # Run through all revisions in our data
  298. for meta, test_data in data:
  299. if (not test in test_data['tests'] or
  300. not meas in test_data['tests'][test]['measurements']):
  301. samples.append(measurement_stats(None))
  302. continue
  303. test_i = test_data['tests'][test]
  304. meas_i = test_i['measurements'][meas]
  305. commit_num = get_data_item(meta, 'layers.meta.commit_count')
  306. samples.append(measurement_stats(meas_i))
  307. samples[-1]['commit_num'] = commit_num
  308. absdiff = samples[-1]['val_cls'](samples[-1]['mean'] - samples[id_comp]['mean'])
  309. new_meas['absdiff'] = absdiff
  310. new_meas['absdiff_str'] = str(absdiff) if absdiff < 0 else '+' + str(absdiff)
  311. new_meas['reldiff'] = "{:+.1f} %".format(absdiff * 100 / samples[id_comp]['mean'])
  312. new_meas['samples'] = samples
  313. new_meas['value'] = samples[-1]
  314. new_meas['value_type'] = samples[-1]['val_cls']
  315. new_test['measurements'].append(new_meas)
  316. tests.append(new_test)
  317. # Chart options
  318. chart_opts = {'haxis': {'min': get_data_item(data[0][0], 'layers.meta.commit_count'),
  319. 'max': get_data_item(data[-1][0], 'layers.meta.commit_count')}
  320. }
  321. print(html.template.render(metadata=metadata, test_data=tests, chart_opts=chart_opts))
  322. def auto_args(repo, args):
  323. """Guess arguments, if not defined by the user"""
  324. # Get the latest commit in the repo
  325. log.debug("Guessing arguments from the latest commit")
  326. msg = repo.run_cmd(['log', '-1', '--branches', '--remotes', '--format=%b'])
  327. for line in msg.splitlines():
  328. split = line.split(':', 1)
  329. if len(split) != 2:
  330. continue
  331. key = split[0]
  332. val = split[1].strip()
  333. if key == 'hostname':
  334. log.debug("Using hostname %s", val)
  335. args.hostname = val
  336. elif key == 'branch':
  337. log.debug("Using branch %s", val)
  338. args.branch = val
  339. def parse_args(argv):
  340. """Parse command line arguments"""
  341. description = """
  342. Examine build performance test results from a Git repository"""
  343. parser = argparse.ArgumentParser(
  344. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  345. description=description)
  346. parser.add_argument('--debug', '-d', action='store_true',
  347. help="Verbose logging")
  348. parser.add_argument('--repo', '-r', required=True,
  349. help="Results repository (local git clone)")
  350. parser.add_argument('--list', '-l', action='store_true',
  351. help="List available test runs")
  352. parser.add_argument('--html', action='store_true',
  353. help="Generate report in html format")
  354. group = parser.add_argument_group('Tag and revision')
  355. group.add_argument('--tag-name', '-t',
  356. default='{hostname}/{branch}/{machine}/{commit_number}-g{commit}/{tag_number}',
  357. help="Tag name (pattern) for finding results")
  358. group.add_argument('--hostname', '-H')
  359. group.add_argument('--branch', '-B', default='master')
  360. group.add_argument('--machine', default='qemux86')
  361. group.add_argument('--history-length', default=25, type=int,
  362. help="Number of tested revisions to plot in html report")
  363. group.add_argument('--commit',
  364. help="Revision to search for")
  365. group.add_argument('--commit-number',
  366. help="Revision number to search for, redundant if "
  367. "--commit is specified")
  368. group.add_argument('--commit2',
  369. help="Revision to compare with")
  370. group.add_argument('--commit-number2',
  371. help="Revision number to compare with, redundant if "
  372. "--commit2 is specified")
  373. return parser.parse_args(argv)
  374. def main(argv=None):
  375. """Script entry point"""
  376. args = parse_args(argv)
  377. if args.debug:
  378. log.setLevel(logging.DEBUG)
  379. repo = GitRepo(args.repo)
  380. if args.list:
  381. list_test_revs(repo, args.tag_name)
  382. return 0
  383. # Determine hostname which to use
  384. if not args.hostname:
  385. auto_args(repo, args)
  386. revs = get_test_revs(repo, args.tag_name, hostname=args.hostname,
  387. branch=args.branch, machine=args.machine)
  388. if len(revs) < 2:
  389. log.error("%d tester revisions found, unable to generate report",
  390. len(revs))
  391. return 1
  392. # Pick revisions
  393. if args.commit:
  394. if args.commit_number:
  395. log.warning("Ignoring --commit-number as --commit was specified")
  396. index1 = rev_find(revs, 'commit', args.commit)
  397. elif args.commit_number:
  398. index1 = rev_find(revs, 'commit_number', args.commit_number)
  399. else:
  400. index1 = len(revs) - 1
  401. if args.commit2:
  402. if args.commit_number2:
  403. log.warning("Ignoring --commit-number2 as --commit2 was specified")
  404. index2 = rev_find(revs, 'commit', args.commit2)
  405. elif args.commit_number2:
  406. index2 = rev_find(revs, 'commit_number', args.commit_number2)
  407. else:
  408. if index1 > 0:
  409. index2 = index1 - 1
  410. else:
  411. log.error("Unable to determine the other commit, use "
  412. "--commit2 or --commit-number2 to specify it")
  413. return 1
  414. index_l = min(index1, index2)
  415. index_r = max(index1, index2)
  416. rev_l = revs[index_l]
  417. rev_r = revs[index_r]
  418. log.debug("Using 'left' revision %s (%s), %s test runs:\n %s",
  419. rev_l.commit_number, rev_l.commit, len(rev_l.tags),
  420. '\n '.join(rev_l.tags))
  421. log.debug("Using 'right' revision %s (%s), %s test runs:\n %s",
  422. rev_r.commit_number, rev_r.commit, len(rev_r.tags),
  423. '\n '.join(rev_r.tags))
  424. # Check report format used in the repo (assume all reports in the same fmt)
  425. xml = is_xml_format(repo, revs[index_r].tags[-1])
  426. if args.html:
  427. index_0 = max(0, index_r - args.history_length)
  428. rev_range = range(index_0, index_r + 1)
  429. else:
  430. # We do not need range of commits for text report (no graphs)
  431. index_0 = index_l
  432. rev_range = (index_l, index_r)
  433. # Read raw data
  434. log.debug("Reading %d revisions, starting from %s (%s)",
  435. len(rev_range), revs[index_0].commit_number, revs[index_0].commit)
  436. raw_data = [read_results(repo, revs[i].tags, xml) for i in rev_range]
  437. data = []
  438. for raw_m, raw_d in raw_data:
  439. data.append((aggregate_metadata(raw_m), aggregate_data(raw_d)))
  440. # Re-map list indexes to the new table starting from index 0
  441. index_r = index_r - index_0
  442. index_l = index_l - index_0
  443. # Print report
  444. if not args.html:
  445. print_diff_report(data[index_l][0], data[index_l][1],
  446. data[index_r][0], data[index_r][1])
  447. else:
  448. print_html_report(data, index_l)
  449. return 0
  450. if __name__ == "__main__":
  451. sys.exit(main())