Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(50)

Side by Side Diff: scripts/slave/gatekeeper_ng_db.py

Issue 172523005: Keep track of hashes triggered instead of builds. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/tools/build
Patch Set: Address iannucci's comments. Created 6 years, 10 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « scripts/slave/gatekeeper_ng_config.py ('k') | scripts/slave/unittests/gatekeeper_ng_test.py » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 #!/usr/bin/env python
2 # Copyright 2014 The Chromium 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 """Contains configuration and setup of gatekeeper build database.
7
8 The databse is a versioned JSON file built of NamedTuples.
9 """
10
11 import collections
12 import json
13 import logging
14 import optparse
15 import os
16 import sys
17
18 from common import chromium_utils
19 from slave import gatekeeper_ng_config
20
21
22 DATA_DIR = os.path.dirname(os.path.abspath(__file__))
23
24
25 # Bump each time there is an incompatible change in build_db.
26 BUILD_DB_VERSION = 1
27
28
29 _BuildDB = collections.namedtuple('BuildDB', [
30 'build_db_version', # An int representing the build_db version.
31 'masters', # {mastername: {buildername: {buildnumber: BuildDBBuild}}}}
32 'sections', # {section_hash: human_readable_json_of_gatekeeper_section}
33 ])
34
35
36 _BuildDBBuild = collections.namedtuple('BuildDBBuild', [
37 'finished', # Whether the build has finished or not.
38 'triggered', # What gatekeeper sections, if any, have triggered.
39 ])
40
41
42 class JsonNode(object):
43 """Allows for serialization of NamedTuples to JSON."""
44 def _asdict(self): # pylint: disable=R0201
45 return {}
46
47 # TODO(stip): recursively encode child nodes.
48 def asJson(self):
49 nodes_to_encode = [(k, v) for k, v in self._asdict().iteritems()
50 if hasattr(v, 'asJson')]
51 standard_nodes = [(k, v) for k, v in self._asdict().iteritems()
52 if not hasattr(v, 'asJson')]
53 newly_encoded_nodes = [(k, v.asJson()) for k, v in nodes_to_encode]
54
55 return dict(standard_nodes + newly_encoded_nodes)
56
57
58 class BuildDB(_BuildDB, JsonNode):
59 pass
60
61
62 class BuildDBBuild(_BuildDBBuild, JsonNode):
63 pass
64
65
66 class BadConf(Exception):
67 pass
68
69
70 def gen_db(**kwargs):
71 """Helper function to generate a default database."""
72 defaults = [('build_db_version', BUILD_DB_VERSION),
73 ('masters', {}),
74 ('sections', {})]
75
76 for key, default in defaults:
77 kwargs.setdefault(key, default)
78
79 return BuildDB(**kwargs)
80
81 def gen_build(**kwargs):
82 """Helper function to generate a default build."""
83 defaults = [('finished', False),
84 ('triggered', [])]
85
86 for key, default in defaults:
87 kwargs.setdefault(key, default)
88
89 return BuildDBBuild(**kwargs)
90
91
92 def load_from_json(f):
93 """Load a build from a JSON stream."""
94 build_db = gen_db()
95
96 json_build_db = json.load(f)
97
98 if json_build_db.get('build_db_version') != BUILD_DB_VERSION:
99 raise BadConf('file is an older db version: %r (expecting %d)' % (
100 json.build_db.get('build_db_version', 0), BUILD_DB_VERSION))
101
102 masters = json_build_db.get('masters', {})
103 # Convert build dicts into BuildDBBuilds.
104 build_db = gen_db()
105 for mastername, master in masters.iteritems():
106 build_db.masters.setdefault(mastername, {})
107 for buildername, builder in master.iteritems():
108 build_db.masters[mastername].setdefault(buildername, {})
109 for buildnumber, build in builder.iteritems():
110 # Note that buildnumber is forced to be an int here, and
111 # we use * instead of ** -- until the serializer is recursive,
112 # BuildDBBuild will be written as a value list (tuple).
113 build_db.masters[mastername][buildername][
114 int(buildnumber)] = BuildDBBuild(*build)
115
116 return build_db
117
118
119 def get_build_db(filename):
120 """Open the build_db file.
121
122 filename: the filename of the build db.
123 """
124 build_db = gen_db()
125
126 if os.path.isfile(filename):
127 print 'loading build_db from', filename
128 try:
129 with open(filename) as f:
130 build_db = load_from_json(f)
131 except BadConf as e:
132 new_fn = '%s.old' % filename
133 logging.warn('error loading %s: %s, moving to %s' % (
134 filename, e, new_fn))
135 chromium_utils.MoveFile(filename, new_fn)
136
137 return build_db
138
139
140 def convert_db_to_json(build_db_data, gatekeeper_config, f):
141 """Converts build_db to a format suitable for JSON encoding and writes it."""
142 # Remove all but the last finished build.
143 for builders in build_db_data.masters.values():
144 for builder in builders:
145 unfinished = [(k, v) for k, v in builders[builder].iteritems()
146 if not v.finished]
147
148 finished = [(k, v) for k, v in builders[builder].iteritems()
149 if v.finished]
150
151 builders[builder] = dict(unfinished)
152
153 if finished:
154 max_finished = max(finished, key=lambda x: x[0])
155 builders[builder][max_finished[0]] = max_finished[1]
156
157
158 build_db = gen_db(masters=build_db_data.masters)
159
160 # Output the gatekeeper sections we're operating with, so a human reading the
161 # file can debug issues. This is discarded by the parser in get_build_db.
162 used_sections = set([])
163 for masters in build_db_data.masters.values():
164 for builder in masters.values():
165 used_sections |= set(t for b in builder.values() for t in b.triggered)
166
167 for master in gatekeeper_config.values():
168 for section in master:
169 section_hash = gatekeeper_ng_config.gatekeeper_section_hash(section)
170 if section_hash in used_sections:
171 build_db.sections[section_hash] = section
172
173 json.dump(build_db.asJson(), f, cls=gatekeeper_ng_config.SetEncoder,
174 sort_keys=True)
175
176
177 def save_build_db(build_db_data, gatekeeper_config, filename):
178 """Save the build_db file.
179
180 build_db: dictionary to jsonize and store as build_db.
181 gatekeeper_config: the gatekeeper config used for this pass.
182 filename: the filename of the build db.
183 """
184 print 'saving build_db to', filename
185 with open(filename, 'wb') as f:
186 convert_db_to_json(build_db_data, gatekeeper_config, f)
187
188
189 def main():
190 prog_desc = 'Parses the build_db and outputs to stdout.'
191 usage = '%prog [options]'
192 parser = optparse.OptionParser(usage=(usage + '\n\n' + prog_desc))
193 parser.add_option('--json', default=os.path.join(DATA_DIR, 'gatekeeper.json'),
194 help='location of gatekeeper configuration file')
195 parser.add_option('--build-db', default='build_db.json',
196 help='records the build status information for builders')
197 options, _ = parser.parse_args()
198
199 build_db = get_build_db(options.build_db)
200 gatekeeper_config = gatekeeper_ng_config.load_gatekeeper_config(options.json)
201
202 convert_db_to_json(build_db, gatekeeper_config, sys.stdout)
203 print
204
205 return 0
206
207
208 if __name__ == '__main__':
209 sys.exit(main())
OLDNEW
« no previous file with comments | « scripts/slave/gatekeeper_ng_config.py ('k') | scripts/slave/unittests/gatekeeper_ng_test.py » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698