1 # Copyright (c) 2012 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.
5 """Upload a single build command stats file to appengine."""
7 from __future__ import print_function
13 from chromite.cbuildbot import constants
14 from chromite.lib import commandline
15 from chromite.lib import cros_build_lib
16 from chromite.lib import stats
19 FILE_LOAD_ERROR = 'Error loading %s'
20 UNCAUGHT_ERROR = 'Uncaught command stats exception.'
23 class LoadError(RuntimeError):
24 """Error during loading of stats file."""
27 class StatsLoader(object):
28 """Loads stats from a file."""
31 def LoadFile(cls, stat_file):
32 """Return a Stats object constructed from contents of |stat_file|."""
34 with open(stat_file, 'r') as f:
35 first_line = f.readline().rstrip()
36 match = re.match(r'Chromium OS .+ Version (\d+)$', first_line)
38 raise LoadError('Stats file not in expected format')
40 version = int(match.group(1))
41 loader = cls._GetLinesLoader(version)
43 raise LoadError('Stats file version %s not supported.' % version)
45 return loader(f.readlines())
48 def _GetLinesLoader(cls, version):
51 cls._LoadLinesV1, # Version 1 loader (at index 1)
54 if version < len(LOADERS) and version >= 0:
55 return LOADERS[version]
60 def _LoadLinesV1(cls, stat_lines):
61 """Load stat lines in Version 1 format."""
63 for line in stat_lines:
64 # Each line has following format:
65 # attribute_name Rest of line is value for attribute_name
66 # Note that some attributes may have no value after their name.
67 attr, _sep, value = line.rstrip().partition(' ')
73 return stats.Stats(**data)
78 # This is not meant to be a user-friendly script. It takes one and
79 # only one argument, which is a build stats file to be uploaded
81 'This script is not intended to be run manually. It is used as'
82 ' part of the build command statistics project.'
84 in_golo = cros_build_lib.GetHostDomain().endswith(constants.GOLO_DOMAIN)
85 debug_level = commandline.ArgumentParser.DEFAULT_LOG_LEVEL
88 parser = commandline.ArgumentParser(
89 epilog=epilog, default_log_level=debug_level)
91 'build_stats_file', nargs=1, default=None)
92 options = parser.parse_args(argv)
95 cmd_stats = StatsLoader.LoadFile(options.build_stats_file[0])
97 logging.error(FILE_LOAD_ERROR, options.build_stats_file[0],
102 stats.StatsUploader.Upload(cmd_stats)
104 logging.error(UNCAUGHT_ERROR, exc_info=True)