• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Uploads performance data to the performance dashboard.
6
7Performance tests may output data that needs to be displayed on the performance
8dashboard.  The autotest TKO parser invokes this module with each test
9associated with a job.  If a test has performance data associated with it, it
10is uploaded to the performance dashboard.  The performance dashboard is owned
11by Chrome team and is available here: https://chromeperf.appspot.com/.  Users
12must be logged in with an @google.com account to view chromeOS perf data there.
13
14"""
15
16import httplib
17import json
18import os
19import re
20import urllib
21import urllib2
22
23import common
24from autotest_lib.tko import utils as tko_utils
25
26_ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
27
28_OAUTH_IMPORT_OK = False
29_OAUTH_CREDS = None
30try:
31    from google.oauth2 import service_account
32    from google.auth.transport.requests import Request
33    from google.auth.exceptions import RefreshError
34    _OAUTH_IMPORT_OK = True
35except ImportError as e:
36    tko_utils.dprint('Failed to import google-auth:\n%s' % e)
37
38_DASHBOARD_UPLOAD_URL = 'https://chromeperf.appspot.com/add_point'
39_OAUTH_SCOPES = ['https://www.googleapis.com/auth/userinfo.email']
40_PRESENTATION_CONFIG_FILE = os.path.join(
41        _ROOT_DIR, 'perf_dashboard_config.json')
42_PRESENTATION_SHADOW_CONFIG_FILE = os.path.join(
43        _ROOT_DIR, 'perf_dashboard_shadow_config.json')
44_SERVICE_ACCOUNT_FILE = '/creds/service_accounts/skylab-drone.json'
45
46# Format for Chrome and Chrome OS version strings.
47VERSION_REGEXP = r'^(\d+)\.(\d+)\.(\d+)\.(\d+)$'
48
49
50class PerfUploadingError(Exception):
51    """Exception raised in perf_uploader"""
52    pass
53
54
55def _parse_config_file(config_file):
56    """Parses a presentation config file and stores the info into a dict.
57
58    The config file contains information about how to present the perf data
59    on the perf dashboard.  This is required if the default presentation
60    settings aren't desired for certain tests.
61
62    @param config_file: Path to the configuration file to be parsed.
63
64    @returns A dictionary mapping each unique autotest name to a dictionary
65        of presentation config information.
66
67    @raises PerfUploadingError if config data or master name for the test
68        is missing from the config file.
69
70    """
71    json_obj = []
72    if os.path.exists(config_file):
73        with open(config_file, 'r') as fp:
74            json_obj = json.load(fp)
75    config_dict = {}
76    for entry in json_obj:
77        if 'autotest_regex' in entry:
78            config_dict[entry['autotest_regex']] = entry
79        else:
80            config_dict['^' + re.escape(entry['autotest_name']) + '$'] = entry
81    return config_dict
82
83
84def _gather_presentation_info(config_data, test_name):
85    """Gathers presentation info from config data for the given test name.
86
87    @param config_data: A dictionary of dashboard presentation info for all
88        tests, as returned by _parse_config_file().  Info is keyed by autotest
89        name.
90    @param test_name: The name of an autotest.
91
92    @return A dictionary containing presentation information extracted from
93        |config_data| for the given autotest name.
94
95    @raises PerfUploadingError if some required data is missing.
96    """
97    presentation_dict = None
98    for regex in config_data:
99        match = re.match(regex, test_name)
100        if match:
101            if presentation_dict:
102                raise PerfUploadingError('Duplicate config data refer to the '
103                                         'same test %s' % test_name)
104            presentation_dict = config_data[regex]
105
106    if not presentation_dict:
107        raise PerfUploadingError(
108                'No config data is specified for test %s in %s.' %
109                (test_name, _PRESENTATION_CONFIG_FILE))
110    try:
111        master_name = presentation_dict['master_name']
112    except KeyError:
113        raise PerfUploadingError(
114                'No master name is specified for test %s in %s.' %
115                (test_name, _PRESENTATION_CONFIG_FILE))
116    if 'dashboard_test_name' in presentation_dict:
117        test_name = presentation_dict['dashboard_test_name']
118    return {'master_name': master_name, 'test_name': test_name}
119
120
121def _format_for_upload(board_name, cros_version, chrome_version,
122                       hardware_id, hardware_hostname, perf_values,
123                       presentation_info, jobname):
124    """Formats perf data suitable to upload to the perf dashboard.
125
126    The perf dashboard expects perf data to be uploaded as a
127    specially-formatted JSON string.  In particular, the JSON object must be a
128    dictionary with key "data", and value being a list of dictionaries where
129    each dictionary contains all the information associated with a single
130    measured perf value: master name, bot name, test name, perf value, error
131    value, units, and build version numbers.
132
133    @param board_name: The string name of the image board name.
134    @param cros_version: The string chromeOS version number.
135    @param chrome_version: The string chrome version number.
136    @param hardware_id: String that identifies the type of hardware the test was
137            executed on.
138    @param hardware_hostname: String that identifies the name of the device the
139            test was executed on.
140    @param perf_values: A dictionary of measured perf data as computed by
141            _compute_avg_stddev().
142    @param presentation_info: A dictionary of dashboard presentation info for
143            the given test, as identified by _gather_presentation_info().
144    @param jobname: A string uniquely identifying the test run, this enables
145            linking back from a test result to the logs of the test run.
146
147    @return A dictionary containing the formatted information ready to upload
148        to the performance dashboard.
149
150    """
151    # Client side case - server side comes with its own charts data section.
152    if 'charts' not in perf_values:
153        perf_values = {
154          'format_version': '1.0',
155          'benchmark_name': presentation_info['test_name'],
156          'charts': perf_values,
157        }
158
159    dash_entry = {
160        'master': presentation_info['master_name'],
161        'bot': 'cros-' + board_name,  # Prefix to clarify it's ChromeOS.
162        'point_id': _get_id_from_version(chrome_version, cros_version),
163        'versions': {
164            'cros_version': cros_version,
165            'chrome_version': chrome_version,
166        },
167        'supplemental': {
168            'default_rev': 'r_cros_version',
169            'hardware_identifier': hardware_id,
170            'hardware_hostname': hardware_hostname,
171            'jobname': jobname,
172        },
173        'chart_data': perf_values,
174    }
175    return {'data': json.dumps(dash_entry)}
176
177
178def _get_version_numbers(test_attributes):
179    """Gets the version numbers from the test attributes and validates them.
180
181    @param test_attributes: The attributes property (which is a dict) of an
182        autotest tko.models.test object.
183
184    @return A pair of strings (Chrome OS version, Chrome version).
185
186    @raises PerfUploadingError if a version isn't formatted as expected.
187    """
188    chrome_version = test_attributes.get('CHROME_VERSION', '')
189    cros_version = test_attributes.get('CHROMEOS_RELEASE_VERSION', '')
190    cros_milestone = test_attributes.get('CHROMEOS_RELEASE_CHROME_MILESTONE')
191    # Use the release milestone as the milestone if present, othewise prefix the
192    # cros version with the with the Chrome browser milestone.
193    if cros_milestone:
194      cros_version = "%s.%s" % (cros_milestone, cros_version)
195    else:
196      cros_version = chrome_version[:chrome_version.find('.') + 1] + cros_version
197    if not re.match(VERSION_REGEXP, cros_version):
198        raise PerfUploadingError('CrOS version "%s" does not match expected '
199                                 'format.' % cros_version)
200    if not re.match(VERSION_REGEXP, chrome_version):
201        raise PerfUploadingError('Chrome version "%s" does not match expected '
202                                 'format.' % chrome_version)
203    return (cros_version, chrome_version)
204
205
206def _get_id_from_version(chrome_version, cros_version):
207    """Computes the point ID to use, from Chrome and ChromeOS version numbers.
208
209    For ChromeOS row data, data values are associated with both a Chrome
210    version number and a ChromeOS version number (unlike for Chrome row data
211    that is associated with a single revision number).  This function takes
212    both version numbers as input, then computes a single, unique integer ID
213    from them, which serves as a 'fake' revision number that can uniquely
214    identify each ChromeOS data point, and which will allow ChromeOS data points
215    to be sorted by Chrome version number, with ties broken by ChromeOS version
216    number.
217
218    To compute the integer ID, we take the portions of each version number that
219    serve as the shortest unambiguous names for each (as described here:
220    http://www.chromium.org/developers/version-numbers).  We then force each
221    component of each portion to be a fixed width (padded by zeros if needed),
222    concatenate all digits together (with those coming from the Chrome version
223    number first), and convert the entire string of digits into an integer.
224    We ensure that the total number of digits does not exceed that which is
225    allowed by AppEngine NDB for an integer (64-bit signed value).
226
227    For example:
228      Chrome version: 27.0.1452.2 (shortest unambiguous name: 1452.2)
229      ChromeOS version: 27.3906.0.0 (shortest unambiguous name: 3906.0.0)
230      concatenated together with padding for fixed-width columns:
231          ('01452' + '002') + ('03906' + '000' + '00') = '014520020390600000'
232      Final integer ID: 14520020390600000
233
234    @param chrome_ver: The Chrome version number as a string.
235    @param cros_ver: The ChromeOS version number as a string.
236
237    @return A unique integer ID associated with the two given version numbers.
238
239    """
240
241    # Number of digits to use from each part of the version string for Chrome
242    # and Chrome OS versions when building a point ID out of these two versions.
243    chrome_version_col_widths = [0, 0, 5, 3]
244    cros_version_col_widths = [0, 5, 3, 2]
245
246    def get_digits_from_version(version_num, column_widths):
247        if re.match(VERSION_REGEXP, version_num):
248            computed_string = ''
249            version_parts = version_num.split('.')
250            for i, version_part in enumerate(version_parts):
251                if column_widths[i]:
252                    computed_string += version_part.zfill(column_widths[i])
253            return computed_string
254        else:
255            return None
256
257    chrome_digits = get_digits_from_version(
258            chrome_version, chrome_version_col_widths)
259    cros_digits = get_digits_from_version(
260            cros_version, cros_version_col_widths)
261    if not chrome_digits or not cros_digits:
262        return None
263    result_digits = chrome_digits + cros_digits
264    max_digits = sum(chrome_version_col_widths + cros_version_col_widths)
265    if len(result_digits) > max_digits:
266        return None
267    return int(result_digits)
268
269
270def _initialize_oauth():
271    """Initialize oauth using local credentials and scopes.
272
273    @return A boolean if oauth is apparently ready to use.
274    """
275    global _OAUTH_CREDS
276    if _OAUTH_CREDS:
277        return True
278    if not _OAUTH_IMPORT_OK:
279        return False
280    try:
281        _OAUTH_CREDS = (service_account.Credentials.from_service_account_file(
282                        _SERVICE_ACCOUNT_FILE)
283                        .with_scopes(_OAUTH_SCOPES))
284        return True
285    except Exception as e:
286        tko_utils.dprint('Failed to initialize oauth credentials:\n%s' % e)
287        return False
288
289
290def _add_oauth_token(headers):
291    """Add support for oauth2 via service credentials.
292
293    This is currently best effort, we will silently not add the token
294    for a number of possible reasons (missing service account, etc).
295
296    TODO(engeg@): Once this is validated, make mandatory.
297
298    @param headers: A map of request headers to add the token to.
299    """
300    if _initialize_oauth():
301        if not _OAUTH_CREDS.valid:
302            try:
303                _OAUTH_CREDS.refresh(Request())
304            except RefreshError as e:
305                tko_utils.dprint('Failed to refresh oauth token:\n%s' % e)
306                return
307        _OAUTH_CREDS.apply(headers)
308
309
310def _send_to_dashboard(data_obj):
311    """Sends formatted perf data to the perf dashboard.
312
313    @param data_obj: A formatted data object as returned by
314        _format_for_upload().
315
316    @raises PerfUploadingError if an exception was raised when uploading.
317
318    """
319    encoded = urllib.urlencode(data_obj)
320    req = urllib2.Request(_DASHBOARD_UPLOAD_URL, encoded)
321    _add_oauth_token(req.headers)
322    try:
323        urllib2.urlopen(req)
324    except urllib2.HTTPError as e:
325        raise PerfUploadingError('HTTPError: %d %s for JSON %s\n' % (
326                e.code, e.msg, data_obj['data']))
327    except urllib2.URLError as e:
328        raise PerfUploadingError(
329                'URLError: %s for JSON %s\n' %
330                (str(e.reason), data_obj['data']))
331    except httplib.HTTPException:
332        raise PerfUploadingError(
333                'HTTPException for JSON %s\n' % data_obj['data'])
334
335
336def _get_image_board_name(platform, image):
337    """Returns the board name of the tested image.
338
339    Note that it can be different from the board name of DUTs the test was
340    scheduled to.
341
342    @param platform: The DUT platform in lab. eg. eve
343    @param image: The image installed in the DUT. eg. eve-arcnext-release.
344    @return: the image board name.
345    """
346    # This is a hacky way to resolve the mixture of reports in chromeperf
347    # dashboard. This solution is copied from our other reporting
348    # pipeline.
349    image_board_name = platform
350
351    suffixes = ['-arcnext', '-ndktranslation', '-arcvm', '-kernelnext']
352
353    for suffix in suffixes:
354        if not platform.endswith(suffix) and (suffix + '-') in image:
355            image_board_name += suffix
356    return image_board_name
357
358
359def upload_test(job, test, jobname):
360    """Uploads any perf data associated with a test to the perf dashboard.
361
362    @param job: An autotest tko.models.job object that is associated with the
363        given |test|.
364    @param test: An autotest tko.models.test object that may or may not be
365        associated with measured perf data.
366    @param jobname: A string uniquely identifying the test run, this enables
367            linking back from a test result to the logs of the test run.
368
369    """
370
371    # Format the perf data for the upload, then upload it.
372    test_name = test.testname
373    image_board_name = _get_image_board_name(
374        job.machine_group, job.keyval_dict.get('build', job.machine_group))
375    # Append the platform name with '.arc' if the suffix of the control
376    # filename is '.arc'.
377    if job.label and re.match('.*\.arc$', job.label):
378        image_board_name += '.arc'
379    hardware_id = test.attributes.get('hwid', '')
380    hardware_hostname = test.machine
381    config_data = _parse_config_file(_PRESENTATION_CONFIG_FILE)
382    try:
383        shadow_config_data = _parse_config_file(_PRESENTATION_SHADOW_CONFIG_FILE)
384        config_data.update(shadow_config_data)
385    except ValueError as e:
386        tko_utils.dprint('Failed to parse config file %s: %s.' %
387                         (_PRESENTATION_SHADOW_CONFIG_FILE, e))
388    try:
389        cros_version, chrome_version = _get_version_numbers(test.attributes)
390        presentation_info = _gather_presentation_info(config_data, test_name)
391        formatted_data = _format_for_upload(image_board_name, cros_version,
392                                            chrome_version, hardware_id,
393                                            hardware_hostname, test.perf_values,
394                                            presentation_info, jobname)
395        _send_to_dashboard(formatted_data)
396    except PerfUploadingError as e:
397        tko_utils.dprint('Warning: unable to upload perf data to the perf '
398                         'dashboard for test %s: %s' % (test_name, e))
399    else:
400        tko_utils.dprint('Successfully uploaded perf data to the perf '
401                         'dashboard for test %s.' % test_name)
402
403