1# -*- coding: utf-8 -*- 2# Copyright (c) 2013 The Chromium OS Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6"""A module to handle the report format.""" 7from __future__ import print_function 8 9import datetime 10import functools 11import itertools 12import json 13import os 14import re 15import time 16 17from cros_utils.tabulator import AmeanResult 18from cros_utils.tabulator import Cell 19from cros_utils.tabulator import CoeffVarFormat 20from cros_utils.tabulator import CoeffVarResult 21from cros_utils.tabulator import Column 22from cros_utils.tabulator import SamplesTableGenerator 23from cros_utils.tabulator import Format 24from cros_utils.tabulator import IterationResult 25from cros_utils.tabulator import GmeanRatioResult 26from cros_utils.tabulator import LiteralResult 27from cros_utils.tabulator import MaxResult 28from cros_utils.tabulator import MinResult 29from cros_utils.tabulator import PValueFormat 30from cros_utils.tabulator import PValueResult 31from cros_utils.tabulator import RatioFormat 32from cros_utils.tabulator import RawResult 33from cros_utils.tabulator import StdResult 34from cros_utils.tabulator import TableFormatter 35from cros_utils.tabulator import TableGenerator 36from cros_utils.tabulator import TablePrinter 37from update_telemetry_defaults import TelemetryDefaults 38 39from column_chart import ColumnChart 40from results_organizer import OrganizeResults 41 42import results_report_templates as templates 43 44 45def ParseChromeosImage(chromeos_image): 46 """Parse the chromeos_image string for the image and version. 47 48 The chromeos_image string will probably be in one of two formats: 49 1: <path-to-chroot>/src/build/images/<board>/<ChromeOS-version>.<datetime>/ \ 50 chromiumos_test_image.bin 51 2: <path-to-chroot>/chroot/tmp/<buildbot-build>/<ChromeOS-version>/ \ 52 chromiumos_test_image.bin 53 54 We parse these strings to find the 'chromeos_version' to store in the 55 json archive (without the .datatime bit in the first case); and also 56 the 'chromeos_image', which would be all of the first case, but only the 57 part after '/chroot/tmp' in the second case. 58 59 Args: 60 chromeos_image: string containing the path to the chromeos_image that 61 crosperf used for the test. 62 63 Returns: 64 version, image: The results of parsing the input string, as explained 65 above. 66 """ 67 # Find the Chromeos Version, e.g. R45-2345.0.0..... 68 # chromeos_image should have been something like: 69 # <path>/<board-trybot-release>/<chromeos-version>/chromiumos_test_image.bin" 70 if chromeos_image.endswith('/chromiumos_test_image.bin'): 71 full_version = chromeos_image.split('/')[-2] 72 # Strip the date and time off of local builds (which have the format 73 # "R43-2345.0.0.date-and-time"). 74 version, _ = os.path.splitext(full_version) 75 else: 76 version = '' 77 78 # Find the chromeos image. If it's somewhere in .../chroot/tmp/..., then 79 # it's an official image that got downloaded, so chop off the download path 80 # to make the official image name more clear. 81 official_image_path = '/chroot/tmp' 82 if official_image_path in chromeos_image: 83 image = chromeos_image.split(official_image_path, 1)[1] 84 else: 85 image = chromeos_image 86 return version, image 87 88 89def _AppendUntilLengthIs(gen, the_list, target_len): 90 """Appends to `list` until `list` is `target_len` elements long. 91 92 Uses `gen` to generate elements. 93 """ 94 the_list.extend(gen() for _ in range(target_len - len(the_list))) 95 return the_list 96 97 98def _FilterPerfReport(event_threshold, report): 99 """Filters out entries with `< event_threshold` percent in a perf report.""" 100 101 def filter_dict(m): 102 return { 103 fn_name: pct for fn_name, pct in m.items() if pct >= event_threshold 104 } 105 106 return {event: filter_dict(m) for event, m in report.items()} 107 108 109class _PerfTable(object): 110 """Generates dicts from a perf table. 111 112 Dicts look like: 113 {'benchmark_name': {'perf_event_name': [LabelData]}} 114 where LabelData is a list of perf dicts, each perf dict coming from the same 115 label. 116 Each perf dict looks like {'function_name': 0.10, ...} (where 0.10 is the 117 percentage of time spent in function_name). 118 """ 119 120 def __init__(self, 121 benchmark_names_and_iterations, 122 label_names, 123 read_perf_report, 124 event_threshold=None): 125 """Constructor. 126 127 read_perf_report is a function that takes a label name, benchmark name, and 128 benchmark iteration, and returns a dictionary describing the perf output for 129 that given run. 130 """ 131 self.event_threshold = event_threshold 132 self._label_indices = {name: i for i, name in enumerate(label_names)} 133 self.perf_data = {} 134 for label in label_names: 135 for bench_name, bench_iterations in benchmark_names_and_iterations: 136 for i in range(bench_iterations): 137 report = read_perf_report(label, bench_name, i) 138 self._ProcessPerfReport(report, label, bench_name, i) 139 140 def _ProcessPerfReport(self, perf_report, label, benchmark_name, iteration): 141 """Add the data from one run to the dict.""" 142 perf_of_run = perf_report 143 if self.event_threshold is not None: 144 perf_of_run = _FilterPerfReport(self.event_threshold, perf_report) 145 if benchmark_name not in self.perf_data: 146 self.perf_data[benchmark_name] = {event: [] for event in perf_of_run} 147 ben_data = self.perf_data[benchmark_name] 148 label_index = self._label_indices[label] 149 for event in ben_data: 150 _AppendUntilLengthIs(list, ben_data[event], label_index + 1) 151 data_for_label = ben_data[event][label_index] 152 _AppendUntilLengthIs(dict, data_for_label, iteration + 1) 153 data_for_label[iteration] = perf_of_run[event] if perf_of_run else {} 154 155 156def _GetResultsTableHeader(ben_name, iterations): 157 benchmark_info = ('Benchmark: {0}; Iterations: {1}'.format( 158 ben_name, iterations)) 159 cell = Cell() 160 cell.string_value = benchmark_info 161 cell.header = True 162 return [[cell]] 163 164 165def _GetDSOHeader(cwp_dso): 166 info = 'CWP_DSO: %s' % cwp_dso 167 cell = Cell() 168 cell.string_value = info 169 cell.header = False 170 return [[cell]] 171 172 173def _ParseColumn(columns, iteration): 174 new_column = [] 175 for column in columns: 176 if column.result.__class__.__name__ != 'RawResult': 177 new_column.append(column) 178 else: 179 new_column.extend( 180 Column(LiteralResult(i), Format(), str(i + 1)) 181 for i in range(iteration)) 182 return new_column 183 184 185def _GetTables(benchmark_results, columns, table_type): 186 iter_counts = benchmark_results.iter_counts 187 result = benchmark_results.run_keyvals 188 tables = [] 189 for bench_name, runs in result.items(): 190 iterations = iter_counts[bench_name] 191 ben_table = _GetResultsTableHeader(bench_name, iterations) 192 193 all_runs_empty = all(not dict for label in runs for dict in label) 194 if all_runs_empty: 195 cell = Cell() 196 cell.string_value = ('This benchmark contains no result.' 197 ' Is the benchmark name valid?') 198 cell_table = [[cell]] 199 else: 200 table = TableGenerator(runs, benchmark_results.label_names).GetTable() 201 parsed_columns = _ParseColumn(columns, iterations) 202 tf = TableFormatter(table, parsed_columns) 203 cell_table = tf.GetCellTable(table_type) 204 tables.append(ben_table) 205 tables.append(cell_table) 206 return tables 207 208 209def _GetPerfTables(benchmark_results, columns, table_type): 210 p_table = _PerfTable(benchmark_results.benchmark_names_and_iterations, 211 benchmark_results.label_names, 212 benchmark_results.read_perf_report) 213 214 tables = [] 215 for benchmark in p_table.perf_data: 216 iterations = benchmark_results.iter_counts[benchmark] 217 ben_table = _GetResultsTableHeader(benchmark, iterations) 218 tables.append(ben_table) 219 benchmark_data = p_table.perf_data[benchmark] 220 table = [] 221 for event in benchmark_data: 222 tg = TableGenerator( 223 benchmark_data[event], 224 benchmark_results.label_names, 225 sort=TableGenerator.SORT_BY_VALUES_DESC) 226 table = tg.GetTable(ResultsReport.PERF_ROWS) 227 parsed_columns = _ParseColumn(columns, iterations) 228 tf = TableFormatter(table, parsed_columns) 229 tf.GenerateCellTable(table_type) 230 tf.AddColumnName() 231 tf.AddLabelName() 232 tf.AddHeader(str(event)) 233 table = tf.GetCellTable(table_type, headers=False) 234 tables.append(table) 235 return tables 236 237 238def _GetSamplesTables(benchmark_results, columns, table_type): 239 tables = [] 240 dso_header_table = _GetDSOHeader(benchmark_results.cwp_dso) 241 tables.append(dso_header_table) 242 (table, new_keyvals, iter_counts) = SamplesTableGenerator( 243 benchmark_results.run_keyvals, benchmark_results.label_names, 244 benchmark_results.iter_counts, benchmark_results.weights).GetTable() 245 parsed_columns = _ParseColumn(columns, 1) 246 tf = TableFormatter(table, parsed_columns, samples_table=True) 247 cell_table = tf.GetCellTable(table_type) 248 tables.append(cell_table) 249 return (tables, new_keyvals, iter_counts) 250 251 252class ResultsReport(object): 253 """Class to handle the report format.""" 254 MAX_COLOR_CODE = 255 255 PERF_ROWS = 5 256 257 def __init__(self, results): 258 self.benchmark_results = results 259 260 def _GetTablesWithColumns(self, columns, table_type, summary_type): 261 if summary_type == 'perf': 262 get_tables = _GetPerfTables 263 elif summary_type == 'samples': 264 get_tables = _GetSamplesTables 265 else: 266 get_tables = _GetTables 267 ret = get_tables(self.benchmark_results, columns, table_type) 268 # If we are generating a samples summary table, the return value of 269 # get_tables will be a tuple, and we will update the benchmark_results for 270 # composite benchmark so that full table can use it. 271 if isinstance(ret, tuple): 272 self.benchmark_results.run_keyvals = ret[1] 273 self.benchmark_results.iter_counts = ret[2] 274 ret = ret[0] 275 return ret 276 277 def GetFullTables(self, perf=False): 278 ignore_min_max = self.benchmark_results.ignore_min_max 279 columns = [ 280 Column(RawResult(), Format()), 281 Column(MinResult(), Format()), 282 Column(MaxResult(), Format()), 283 Column(AmeanResult(ignore_min_max), Format()), 284 Column(StdResult(ignore_min_max), Format(), 'StdDev'), 285 Column(CoeffVarResult(ignore_min_max), CoeffVarFormat(), 'StdDev/Mean'), 286 Column(GmeanRatioResult(ignore_min_max), RatioFormat(), 'GmeanSpeedup'), 287 Column(PValueResult(ignore_min_max), PValueFormat(), 'p-value') 288 ] 289 return self._GetTablesWithColumns(columns, 'full', perf) 290 291 def GetSummaryTables(self, summary_type=''): 292 ignore_min_max = self.benchmark_results.ignore_min_max 293 columns = [] 294 if summary_type == 'samples': 295 columns += [Column(IterationResult(), Format(), 'Iterations [Pass:Fail]')] 296 columns += [ 297 Column( 298 AmeanResult(ignore_min_max), Format(), 299 'Weighted Samples Amean' if summary_type == 'samples' else ''), 300 Column(StdResult(ignore_min_max), Format(), 'StdDev'), 301 Column(CoeffVarResult(ignore_min_max), CoeffVarFormat(), 'StdDev/Mean'), 302 Column(GmeanRatioResult(ignore_min_max), RatioFormat(), 'GmeanSpeedup'), 303 Column(PValueResult(ignore_min_max), PValueFormat(), 'p-value') 304 ] 305 return self._GetTablesWithColumns(columns, 'summary', summary_type) 306 307 308def _PrintTable(tables, out_to): 309 # tables may be None. 310 if not tables: 311 return '' 312 313 if out_to == 'HTML': 314 out_type = TablePrinter.HTML 315 elif out_to == 'PLAIN': 316 out_type = TablePrinter.PLAIN 317 elif out_to == 'CONSOLE': 318 out_type = TablePrinter.CONSOLE 319 elif out_to == 'TSV': 320 out_type = TablePrinter.TSV 321 elif out_to == 'EMAIL': 322 out_type = TablePrinter.EMAIL 323 else: 324 raise ValueError('Invalid out_to value: %s' % (out_to,)) 325 326 printers = (TablePrinter(table, out_type) for table in tables) 327 return ''.join(printer.Print() for printer in printers) 328 329 330class TextResultsReport(ResultsReport): 331 """Class to generate text result report.""" 332 333 H1_STR = '===========================================' 334 H2_STR = '-------------------------------------------' 335 336 def __init__(self, results, email=False, experiment=None): 337 super(TextResultsReport, self).__init__(results) 338 self.email = email 339 self.experiment = experiment 340 341 @staticmethod 342 def _MakeTitle(title): 343 header_line = TextResultsReport.H1_STR 344 # '' at the end gives one newline. 345 return '\n'.join([header_line, title, header_line, '']) 346 347 @staticmethod 348 def _MakeSection(title, body): 349 header_line = TextResultsReport.H2_STR 350 # '\n' at the end gives us two newlines. 351 return '\n'.join([header_line, title, header_line, body, '\n']) 352 353 @staticmethod 354 def FromExperiment(experiment, email=False): 355 results = BenchmarkResults.FromExperiment(experiment) 356 return TextResultsReport(results, email, experiment) 357 358 def GetStatusTable(self): 359 """Generate the status table by the tabulator.""" 360 table = [['', '']] 361 columns = [ 362 Column(LiteralResult(iteration=0), Format(), 'Status'), 363 Column(LiteralResult(iteration=1), Format(), 'Failing Reason') 364 ] 365 366 for benchmark_run in self.experiment.benchmark_runs: 367 status = [ 368 benchmark_run.name, 369 [benchmark_run.timeline.GetLastEvent(), benchmark_run.failure_reason] 370 ] 371 table.append(status) 372 cell_table = TableFormatter(table, columns).GetCellTable('status') 373 return [cell_table] 374 375 def GetTotalWaitCooldownTime(self): 376 """Get cooldown wait time in seconds from experiment benchmark runs. 377 378 Returns: 379 Dictionary {'dut': int(wait_time_in_seconds)} 380 """ 381 waittime_dict = {} 382 for dut in self.experiment.machine_manager.GetMachines(): 383 waittime_dict[dut.name] = dut.GetCooldownWaitTime() 384 return waittime_dict 385 386 def GetReport(self): 387 """Generate the report for email and console.""" 388 output_type = 'EMAIL' if self.email else 'CONSOLE' 389 experiment = self.experiment 390 391 sections = [] 392 if experiment is not None: 393 title_contents = "Results report for '%s'" % (experiment.name,) 394 else: 395 title_contents = 'Results report' 396 sections.append(self._MakeTitle(title_contents)) 397 398 if not self.benchmark_results.cwp_dso: 399 summary_table = _PrintTable(self.GetSummaryTables(), output_type) 400 else: 401 summary_table = _PrintTable( 402 self.GetSummaryTables(summary_type='samples'), output_type) 403 sections.append(self._MakeSection('Summary', summary_table)) 404 405 if experiment is not None: 406 table = _PrintTable(self.GetStatusTable(), output_type) 407 sections.append(self._MakeSection('Benchmark Run Status', table)) 408 409 if not self.benchmark_results.cwp_dso: 410 perf_table = _PrintTable( 411 self.GetSummaryTables(summary_type='perf'), output_type) 412 sections.append(self._MakeSection('Perf Data', perf_table)) 413 414 if experiment is not None: 415 experiment_file = experiment.experiment_file 416 sections.append(self._MakeSection('Experiment File', experiment_file)) 417 418 cpu_info = experiment.machine_manager.GetAllCPUInfo(experiment.labels) 419 sections.append(self._MakeSection('CPUInfo', cpu_info)) 420 421 totaltime = ( 422 time.time() - experiment.start_time) if experiment.start_time else 0 423 totaltime_str = 'Total experiment time:\n%d min' % (totaltime // 60) 424 cooldown_waittime_list = ['Cooldown wait time:'] 425 # When running experiment on multiple DUTs cooldown wait time may vary 426 # on different devices. In addition its combined time may exceed total 427 # experiment time which will look weird but it is reasonable. 428 # For this matter print cooldown time per DUT. 429 for dut, waittime in sorted(self.GetTotalWaitCooldownTime().items()): 430 cooldown_waittime_list.append('DUT %s: %d min' % (dut, waittime // 60)) 431 cooldown_waittime_str = '\n'.join(cooldown_waittime_list) 432 sections.append( 433 self._MakeSection('Duration', '\n\n'.join( 434 [totaltime_str, cooldown_waittime_str]))) 435 436 return '\n'.join(sections) 437 438 439def _GetHTMLCharts(label_names, test_results): 440 charts = [] 441 for item, runs in test_results.items(): 442 # Fun fact: label_names is actually *entirely* useless as a param, since we 443 # never add headers. We still need to pass it anyway. 444 table = TableGenerator(runs, label_names).GetTable() 445 columns = [ 446 Column(AmeanResult(), Format()), 447 Column(MinResult(), Format()), 448 Column(MaxResult(), Format()) 449 ] 450 tf = TableFormatter(table, columns) 451 data_table = tf.GetCellTable('full', headers=False) 452 453 for cur_row_data in data_table: 454 test_key = cur_row_data[0].string_value 455 title = '{0}: {1}'.format(item, test_key.replace('/', '')) 456 chart = ColumnChart(title, 300, 200) 457 chart.AddColumn('Label', 'string') 458 chart.AddColumn('Average', 'number') 459 chart.AddColumn('Min', 'number') 460 chart.AddColumn('Max', 'number') 461 chart.AddSeries('Min', 'line', 'black') 462 chart.AddSeries('Max', 'line', 'black') 463 cur_index = 1 464 for label in label_names: 465 chart.AddRow([ 466 label, cur_row_data[cur_index].value, 467 cur_row_data[cur_index + 1].value, cur_row_data[cur_index + 2].value 468 ]) 469 if isinstance(cur_row_data[cur_index].value, str): 470 chart = None 471 break 472 cur_index += 3 473 if chart: 474 charts.append(chart) 475 return charts 476 477 478class HTMLResultsReport(ResultsReport): 479 """Class to generate html result report.""" 480 481 def __init__(self, benchmark_results, experiment=None): 482 super(HTMLResultsReport, self).__init__(benchmark_results) 483 self.experiment = experiment 484 485 @staticmethod 486 def FromExperiment(experiment): 487 return HTMLResultsReport( 488 BenchmarkResults.FromExperiment(experiment), experiment=experiment) 489 490 def GetReport(self): 491 label_names = self.benchmark_results.label_names 492 test_results = self.benchmark_results.run_keyvals 493 charts = _GetHTMLCharts(label_names, test_results) 494 chart_javascript = ''.join(chart.GetJavascript() for chart in charts) 495 chart_divs = ''.join(chart.GetDiv() for chart in charts) 496 497 if not self.benchmark_results.cwp_dso: 498 summary_table = self.GetSummaryTables() 499 perf_table = self.GetSummaryTables(summary_type='perf') 500 else: 501 summary_table = self.GetSummaryTables(summary_type='samples') 502 perf_table = None 503 full_table = self.GetFullTables() 504 505 experiment_file = '' 506 if self.experiment is not None: 507 experiment_file = self.experiment.experiment_file 508 # Use kwargs for sanity, and so that testing is a bit easier. 509 return templates.GenerateHTMLPage( 510 perf_table=perf_table, 511 chart_js=chart_javascript, 512 summary_table=summary_table, 513 print_table=_PrintTable, 514 chart_divs=chart_divs, 515 full_table=full_table, 516 experiment_file=experiment_file) 517 518 519def ParseStandardPerfReport(report_data): 520 """Parses the output of `perf report`. 521 522 It'll parse the following: 523 {{garbage}} 524 # Samples: 1234M of event 'foo' 525 526 1.23% command shared_object location function::name 527 528 1.22% command shared_object location function2::name 529 530 # Samples: 999K of event 'bar' 531 532 0.23% command shared_object location function3::name 533 {{etc.}} 534 535 Into: 536 {'foo': {'function::name': 1.23, 'function2::name': 1.22}, 537 'bar': {'function3::name': 0.23, etc.}} 538 """ 539 # This function fails silently on its if it's handed a string (as opposed to a 540 # list of lines). So, auto-split if we do happen to get a string. 541 if isinstance(report_data, str): 542 report_data = report_data.splitlines() 543 # When switching to python3 catch the case when bytes are passed. 544 elif isinstance(report_data, bytes): 545 raise TypeError() 546 547 # Samples: N{K,M,G} of event 'event-name' 548 samples_regex = re.compile(r"#\s+Samples: \d+\S? of event '([^']+)'") 549 550 # We expect lines like: 551 # N.NN% command samples shared_object [location] symbol 552 # 553 # Note that we're looking at stripped lines, so there is no space at the 554 # start. 555 perf_regex = re.compile(r'^(\d+(?:.\d*)?)%' # N.NN% 556 r'\s*\d+' # samples count (ignored) 557 r'\s*\S+' # command (ignored) 558 r'\s*\S+' # shared_object (ignored) 559 r'\s*\[.\]' # location (ignored) 560 r'\s*(\S.+)' # function 561 ) 562 563 stripped_lines = (l.strip() for l in report_data) 564 nonempty_lines = (l for l in stripped_lines if l) 565 # Ignore all lines before we see samples_regex 566 interesting_lines = itertools.dropwhile(lambda x: not samples_regex.match(x), 567 nonempty_lines) 568 569 first_sample_line = next(interesting_lines, None) 570 # Went through the entire file without finding a 'samples' header. Quit. 571 if first_sample_line is None: 572 return {} 573 574 sample_name = samples_regex.match(first_sample_line).group(1) 575 current_result = {} 576 results = {sample_name: current_result} 577 for line in interesting_lines: 578 samples_match = samples_regex.match(line) 579 if samples_match: 580 sample_name = samples_match.group(1) 581 current_result = {} 582 results[sample_name] = current_result 583 continue 584 585 match = perf_regex.match(line) 586 if not match: 587 continue 588 percentage_str, func_name = match.groups() 589 try: 590 percentage = float(percentage_str) 591 except ValueError: 592 # Couldn't parse it; try to be "resilient". 593 continue 594 current_result[func_name] = percentage 595 return results 596 597 598def _ReadExperimentPerfReport(results_directory, label_name, benchmark_name, 599 benchmark_iteration): 600 """Reads a perf report for the given benchmark. Returns {} on failure. 601 602 The result should be a map of maps; it should look like: 603 {perf_event_name: {function_name: pct_time_spent}}, e.g. 604 {'cpu_cycles': {'_malloc': 10.0, '_free': 0.3, ...}} 605 """ 606 raw_dir_name = label_name + benchmark_name + str(benchmark_iteration + 1) 607 dir_name = ''.join(c for c in raw_dir_name if c.isalnum()) 608 file_name = os.path.join(results_directory, dir_name, 'perf.data.report.0') 609 try: 610 with open(file_name) as in_file: 611 return ParseStandardPerfReport(in_file) 612 except IOError: 613 # Yes, we swallow any IO-related errors. 614 return {} 615 616 617# Split out so that testing (specifically: mocking) is easier 618def _ExperimentToKeyvals(experiment, for_json_report): 619 """Converts an experiment to keyvals.""" 620 return OrganizeResults( 621 experiment.benchmark_runs, experiment.labels, json_report=for_json_report) 622 623 624class BenchmarkResults(object): 625 """The minimum set of fields that any ResultsReport will take.""" 626 627 def __init__(self, 628 label_names, 629 benchmark_names_and_iterations, 630 run_keyvals, 631 ignore_min_max=False, 632 read_perf_report=None, 633 cwp_dso=None, 634 weights=None): 635 if read_perf_report is None: 636 637 def _NoPerfReport(*_args, **_kwargs): 638 return {} 639 640 read_perf_report = _NoPerfReport 641 642 self.label_names = label_names 643 self.benchmark_names_and_iterations = benchmark_names_and_iterations 644 self.iter_counts = dict(benchmark_names_and_iterations) 645 self.run_keyvals = run_keyvals 646 self.ignore_min_max = ignore_min_max 647 self.read_perf_report = read_perf_report 648 self.cwp_dso = cwp_dso 649 self.weights = dict(weights) if weights else None 650 651 @staticmethod 652 def FromExperiment(experiment, for_json_report=False): 653 label_names = [label.name for label in experiment.labels] 654 benchmark_names_and_iterations = [(benchmark.name, benchmark.iterations) 655 for benchmark in experiment.benchmarks] 656 run_keyvals = _ExperimentToKeyvals(experiment, for_json_report) 657 ignore_min_max = experiment.ignore_min_max 658 read_perf_report = functools.partial(_ReadExperimentPerfReport, 659 experiment.results_directory) 660 cwp_dso = experiment.cwp_dso 661 weights = [(benchmark.name, benchmark.weight) 662 for benchmark in experiment.benchmarks] 663 return BenchmarkResults(label_names, benchmark_names_and_iterations, 664 run_keyvals, ignore_min_max, read_perf_report, 665 cwp_dso, weights) 666 667 668def _GetElemByName(name, from_list): 669 """Gets an element from the given list by its name field. 670 671 Raises an error if it doesn't find exactly one match. 672 """ 673 elems = [e for e in from_list if e.name == name] 674 if len(elems) != 1: 675 raise ValueError('Expected 1 item named %s, found %d' % (name, len(elems))) 676 return elems[0] 677 678 679def _Unlist(l): 680 """If l is a list, extracts the first element of l. Otherwise, returns l.""" 681 return l[0] if isinstance(l, list) else l 682 683 684class JSONResultsReport(ResultsReport): 685 """Class that generates JSON reports for experiments.""" 686 687 def __init__(self, 688 benchmark_results, 689 benchmark_date=None, 690 benchmark_time=None, 691 experiment=None, 692 json_args=None): 693 """Construct a JSONResultsReport. 694 695 json_args is the dict of arguments we pass to json.dumps in GetReport(). 696 """ 697 super(JSONResultsReport, self).__init__(benchmark_results) 698 699 defaults = TelemetryDefaults() 700 defaults.ReadDefaultsFile() 701 summary_field_defaults = defaults.GetDefault() 702 if summary_field_defaults is None: 703 summary_field_defaults = {} 704 self.summary_field_defaults = summary_field_defaults 705 706 if json_args is None: 707 json_args = {} 708 self.json_args = json_args 709 710 self.experiment = experiment 711 if not benchmark_date: 712 timestamp = datetime.datetime.strftime(datetime.datetime.now(), 713 '%Y-%m-%d %H:%M:%S') 714 benchmark_date, benchmark_time = timestamp.split(' ') 715 self.date = benchmark_date 716 self.time = benchmark_time 717 718 @staticmethod 719 def FromExperiment(experiment, 720 benchmark_date=None, 721 benchmark_time=None, 722 json_args=None): 723 benchmark_results = BenchmarkResults.FromExperiment( 724 experiment, for_json_report=True) 725 return JSONResultsReport(benchmark_results, benchmark_date, benchmark_time, 726 experiment, json_args) 727 728 def GetReportObjectIgnoringExperiment(self): 729 """Gets the JSON report object specifically for the output data. 730 731 Ignores any experiment-specific fields (e.g. board, machine checksum, ...). 732 """ 733 benchmark_results = self.benchmark_results 734 label_names = benchmark_results.label_names 735 summary_field_defaults = self.summary_field_defaults 736 final_results = [] 737 for test, test_results in benchmark_results.run_keyvals.items(): 738 for label_name, label_results in zip(label_names, test_results): 739 for iter_results in label_results: 740 passed = iter_results.get('retval') == 0 741 json_results = { 742 'date': self.date, 743 'time': self.time, 744 'label': label_name, 745 'test_name': test, 746 'pass': passed, 747 } 748 final_results.append(json_results) 749 750 if not passed: 751 continue 752 753 # Get overall results. 754 summary_fields = summary_field_defaults.get(test) 755 if summary_fields is not None: 756 value = [] 757 json_results['overall_result'] = value 758 for f in summary_fields: 759 v = iter_results.get(f) 760 if v is None: 761 continue 762 # New telemetry results format: sometimes we get a list of lists 763 # now. 764 v = _Unlist(_Unlist(v)) 765 value.append((f, float(v))) 766 767 # Get detailed results. 768 detail_results = {} 769 json_results['detailed_results'] = detail_results 770 for k, v in iter_results.items(): 771 if k == 'retval' or k == 'PASS' or k == ['PASS'] or v == 'PASS': 772 continue 773 774 v = _Unlist(v) 775 if 'machine' in k: 776 json_results[k] = v 777 elif v is not None: 778 if isinstance(v, list): 779 detail_results[k] = [float(d) for d in v] 780 else: 781 detail_results[k] = float(v) 782 return final_results 783 784 def GetReportObject(self): 785 """Generate the JSON report, returning it as a python object.""" 786 report_list = self.GetReportObjectIgnoringExperiment() 787 if self.experiment is not None: 788 self._AddExperimentSpecificFields(report_list) 789 return report_list 790 791 def _AddExperimentSpecificFields(self, report_list): 792 """Add experiment-specific data to the JSON report.""" 793 board = self.experiment.labels[0].board 794 manager = self.experiment.machine_manager 795 for report in report_list: 796 label_name = report['label'] 797 label = _GetElemByName(label_name, self.experiment.labels) 798 799 img_path = os.path.realpath(os.path.expanduser(label.chromeos_image)) 800 ver, img = ParseChromeosImage(img_path) 801 802 report.update({ 803 'board': board, 804 'chromeos_image': img, 805 'chromeos_version': ver, 806 'chrome_version': label.chrome_version, 807 'compiler': label.compiler 808 }) 809 810 if not report['pass']: 811 continue 812 if 'machine_checksum' not in report: 813 report['machine_checksum'] = manager.machine_checksum[label_name] 814 if 'machine_string' not in report: 815 report['machine_string'] = manager.machine_checksum_string[label_name] 816 817 def GetReport(self): 818 """Dump the results of self.GetReportObject() to a string as JSON.""" 819 # This exists for consistency with the other GetReport methods. 820 # Specifically, they all return strings, so it's a bit awkward if the JSON 821 # results reporter returns an object. 822 return json.dumps(self.GetReportObject(), **self.json_args) 823