blob: b4705d4905cc0e5d122462d8a09ddd263ce30ced [file] [log] [blame]
Salud Lemus055838a2019-08-19 13:37:28 -07001#!/usr/bin/env python2
2# -*- coding: utf-8 -*-
3# Copyright 2019 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Performs bisection on LLVM based off a .JSON file."""
8
9from __future__ import division
10from __future__ import print_function
11
12import argparse
13import errno
14import json
15import os
16
17from assert_not_in_chroot import VerifyOutsideChroot
Salud Lemus42235702019-08-23 16:49:28 -070018from get_llvm_hash import CreateTempLLVMRepo
Salud Lemus055838a2019-08-19 13:37:28 -070019from get_llvm_hash import LLVMHash
20from modify_a_tryjob import AddTryjob
21from patch_manager import _ConvertToASCII
22from update_tryjob_status import FindTryjobIndex
23from update_tryjob_status import TryjobStatus
24
25
26def is_file_and_json(json_file):
27 """Validates that the file exists and is a JSON file."""
28 return os.path.isfile(json_file) and json_file.endswith('.json')
29
30
31def GetCommandLineArgs():
32 """Parses the command line for the command line arguments."""
33
34 # Default path to the chroot if a path is not specified.
35 cros_root = os.path.expanduser('~')
36 cros_root = os.path.join(cros_root, 'chromiumos')
37
38 # Create parser and add optional command-line arguments.
39 parser = argparse.ArgumentParser(
40 description='Bisects LLVM via tracking a JSON file.')
41
42 # Add argument for other change lists that want to run alongside the tryjob
43 # which has a change list of updating a package's git hash.
44 parser.add_argument(
45 '--parallel',
46 type=int,
47 default=3,
48 help='How many tryjobs to create between the last good version and '
49 'the first bad version (default: %(default)s)')
50
51 # Add argument for the good LLVM revision for bisection.
52 parser.add_argument(
53 '--start_rev',
54 required=True,
55 type=int,
56 help='The good revision for the bisection.')
57
58 # Add argument for the bad LLVM revision for bisection.
59 parser.add_argument(
60 '--end_rev',
61 required=True,
62 type=int,
63 help='The bad revision for the bisection.')
64
65 # Add argument for the absolute path to the file that contains information on
66 # the previous tested svn version.
67 parser.add_argument(
68 '--last_tested',
69 required=True,
70 help='the absolute path to the file that contains the tryjobs')
71
72 # Add argument for the absolute path to the LLVM source tree.
73 parser.add_argument(
74 '--src_path',
75 help='the path to the LLVM source tree to use (used for retrieving the '
76 'git hash of each version between the last good version and first bad '
77 'version)')
78
79 # Add argument for other change lists that want to run alongside the tryjob
80 # which has a change list of updating a package's git hash.
81 parser.add_argument(
82 '--extra_change_lists',
83 type=int,
84 nargs='+',
85 help='change lists that would like to be run alongside the change list '
86 'of updating the packages')
87
88 # Add argument for custom options for the tryjob.
89 parser.add_argument(
90 '--options',
91 required=False,
92 nargs='+',
93 help='options to use for the tryjob testing')
94
95 # Add argument for the builder to use for the tryjob.
96 parser.add_argument(
97 '--builder', required=True, help='builder to use for the tryjob testing')
98
99 # Add argument for the description of the tryjob.
100 parser.add_argument(
101 '--description',
102 required=False,
103 nargs='+',
104 help='the description of the tryjob')
105
106 # Add argument for a specific chroot path.
107 parser.add_argument(
108 '--chroot_path',
109 default=cros_root,
110 help='the path to the chroot (default: %(default)s)')
111
112 # Add argument for the log level.
113 parser.add_argument(
114 '--log_level',
115 default='none',
116 choices=['none', 'quiet', 'average', 'verbose'],
117 help='the level for the logs (default: %(default)s)')
118
119 args_output = parser.parse_args()
120
121 assert args_output.start_rev < args_output.end_rev, (
122 'Start revision %d is >= end revision %d' % (args_output.start_rev,
123 args_output.end_rev))
124
125 if args_output.last_tested and not args_output.last_tested.endswith('.json'):
126 raise ValueError(
127 'Filed provided %s does not end in \'.json\'' % args_output.last_tested)
128
129 return args_output
130
131
132def _ValidateStartAndEndAgainstJSONStartAndEnd(start, end, json_start,
133 json_end):
134 """Valides that the command line arguments are the same as the JSON."""
135
136 if start != json_start or end != json_end:
137 raise ValueError('The start %d or the end %d version provided is '
138 'different than \'start\' %d or \'end\' %d in the .JSON '
139 'file' % (start, end, json_start, json_end))
140
141
142def GetStartAndEndRevision(start, end, tryjobs):
143 """Gets the start and end intervals in 'json_file'.
144
145 Args:
146 start: The start version of the bisection provided via the command line.
147 end: The end version of the bisection provided via the command line.
148 tryjobs: A list of tryjobs where each element is in the following format:
149 [
150 {[TRYJOB_INFORMATION]},
151 {[TRYJOB_INFORMATION]},
152 ...,
153 {[TRYJOB_INFORMATION]}
154 ]
155
156 Returns:
157 The new start version and end version for bisection.
158
159 Raises:
160 ValueError: The value for 'status' is missing or there is a mismatch
161 between 'start' and 'end' compared to the 'start' and 'end' in the JSON
162 file.
163 AssertionError: The new start version is >= than the new end version.
164 """
165
166 if not tryjobs:
167 return start, end, []
168
169 # Verify that each tryjob has a value for the 'status' key.
170 for cur_tryjob_dict in tryjobs:
171 if not cur_tryjob_dict.get('status', None):
172 raise ValueError('\'status\' is missing or has no value, please '
173 'go to %s and update it' % cur_tryjob_dict['link'])
174
175 all_bad_revisions = [end]
176 all_bad_revisions.extend(cur_tryjob['rev']
177 for cur_tryjob in tryjobs
178 if cur_tryjob['status'] == TryjobStatus.BAD.value)
179
180 # The minimum value for the 'bad' field in the tryjobs is the new end
181 # version.
182 bad_rev = min(all_bad_revisions)
183
184 all_good_revisions = [start]
185 all_good_revisions.extend(cur_tryjob['rev']
186 for cur_tryjob in tryjobs
187 if cur_tryjob['status'] == TryjobStatus.GOOD.value)
188
189 # The maximum value for the 'good' field in the tryjobs is the new start
190 # version.
191 good_rev = max(all_good_revisions)
192
193 # The good version should always be strictly less than the bad version;
194 # otherwise, bisection is broken.
195 assert good_rev < bad_rev, ('Bisection is broken because %d (good) is >= '
196 '%d (bad)' % (good_rev, bad_rev))
197
198 # Find all revisions that are 'pending' within 'good_rev' and 'bad_rev'.
199 #
200 # NOTE: The intent is to not launch tryjobs between 'good_rev' and 'bad_rev'
201 # that have already been launched (this list is used when constructing the
202 # list of revisions to launch tryjobs for).
203 pending_revisions = [
204 tryjob['rev']
205 for tryjob in tryjobs
206 if tryjob['status'] == TryjobStatus.PENDING.value and
207 good_rev < tryjob['rev'] < bad_rev
208 ]
209
210 return good_rev, bad_rev, pending_revisions
211
212
213def GetRevisionsBetweenBisection(start, end, parallel, src_path,
214 pending_revisions):
215 """Gets the revisions between 'start' and 'end'.
216
217 Sometimes, the LLVM source tree's revisions do not increment by 1 (there is
218 a jump), so need to construct a list of all revisions that are NOT missing
219 between 'start' and 'end'. Then, the step amount (i.e. length of the list
220 divided by ('parallel' + 1)) will be used for indexing into the list.
221
222 Args:
223 start: The start revision.
224 end: The end revision.
225 parallel: The number of tryjobs to create between 'start' and 'end'.
226 src_path: The absolute path to the LLVM source tree to use.
227 pending_revisions: A list of 'pending' revisions that are between 'start'
228 and 'end'.
229
230 Returns:
231 A list of revisions between 'start' and 'end'.
232 """
233
234 new_llvm = LLVMHash()
235
236 valid_revisions = []
237
238 # Start at ('start' + 1) because 'start' is the good revision.
239 #
240 # FIXME: Searching for each revision from ('start' + 1) up to 'end' in the
241 # LLVM source tree is a quadratic algorithm. It's a good idea to optimize
242 # this.
243 for cur_revision in range(start + 1, end):
244 try:
245 if cur_revision not in pending_revisions:
246 # Verify that the current revision exists by finding its corresponding
247 # git hash in the LLVM source tree.
248 new_llvm.GetGitHashForVersion(src_path, cur_revision)
249 valid_revisions.append(cur_revision)
250 except ValueError:
251 # Could not find the git hash for the current revision.
252 continue
253
254 # ('parallel' + 1) so that the last revision in the list is not close to
255 # 'end' (have a bit more coverage).
256 index_step = len(valid_revisions) // (parallel + 1)
257
258 if not index_step:
259 index_step = 1
260
261 # Starting at 'index_step' because the first element would be close to
262 # 'start' (similar to ('parallel' + 1) for the last element).
263 result = [valid_revisions[index] \
264 for index in range(index_step, len(valid_revisions), index_step)]
265
266 return result
267
268
269def GetRevisionsListAndHashList(start, end, parallel, src_path,
270 pending_revisions):
271 """Determines the revisions between start and end."""
272
273 new_llvm = LLVMHash()
274
275 with new_llvm.CreateTempDirectory() as temp_dir:
Salud Lemus42235702019-08-23 16:49:28 -0700276 with CreateTempLLVMRepo(temp_dir) as new_repo:
277 if not src_path:
278 src_path = new_repo
Salud Lemus055838a2019-08-19 13:37:28 -0700279
Salud Lemus42235702019-08-23 16:49:28 -0700280 # Get a list of revisions between start and end.
281 revisions = GetRevisionsBetweenBisection(start, end, parallel, src_path,
282 pending_revisions)
Salud Lemus055838a2019-08-19 13:37:28 -0700283
Salud Lemus42235702019-08-23 16:49:28 -0700284 git_hashes = [
285 new_llvm.GetGitHashForVersion(src_path, rev) for rev in revisions
286 ]
Salud Lemus055838a2019-08-19 13:37:28 -0700287
288 assert revisions, ('No revisions between start %d and end %d to create '
289 'tryjobs.' % (start, end))
290
291 return revisions, git_hashes
292
293
294def main():
295 """Bisects LLVM based off of a .JSON file.
296
297 Raises:
298 AssertionError: The script was run inside the chroot.
299 """
300
301 VerifyOutsideChroot()
302
303 args_output = GetCommandLineArgs()
304
305 update_packages = [
306 'sys-devel/llvm', 'sys-libs/compiler-rt', 'sys-libs/libcxx',
307 'sys-libs/libcxxabi', 'sys-libs/llvm-libunwind'
308 ]
309
310 patch_metadata_file = 'PATCHES.json'
311
312 start = args_output.start_rev
313 end = args_output.end_rev
314
315 try:
316 with open(args_output.last_tested) as f:
317 bisect_contents = _ConvertToASCII(json.load(f))
318 except IOError as err:
319 if err.errno != errno.ENOENT:
320 raise
321 bisect_contents = {'start': start, 'end': end, 'jobs': []}
322
323 _ValidateStartAndEndAgainstJSONStartAndEnd(
324 start, end, bisect_contents['start'], bisect_contents['end'])
325
326 # Pending revisions are between 'start_revision' and 'end_revision'.
327 start_revision, end_revision, pending_revisions = GetStartAndEndRevision(
328 start, end, bisect_contents['jobs'])
329
330 revisions, git_hashes = GetRevisionsListAndHashList(
331 start_revision, end_revision, args_output.parallel, args_output.src_path,
332 pending_revisions)
333
334 # Check if any revisions that are going to be added as a tryjob exist already
335 # in the 'jobs' list.
336 for rev in revisions:
337 if FindTryjobIndex(rev, bisect_contents['jobs']) is not None:
338 raise ValueError('Revision %d exists already in \'jobs\'' % rev)
339
340 try:
341 for svn_revision, git_hash in zip(revisions, git_hashes):
342 tryjob_dict = AddTryjob(update_packages, git_hash, svn_revision,
343 args_output.chroot_path, patch_metadata_file,
344 args_output.extra_change_lists,
345 args_output.options, args_output.builder,
346 args_output.log_level, svn_revision)
347
348 bisect_contents['jobs'].append(tryjob_dict)
349 finally:
350 # Do not want to lose progress if there is an exception.
351 if args_output.last_tested:
352 new_file = '%s.new' % args_output.last_tested
353 with open(new_file, 'w') as json_file:
354 json.dump(bisect_contents, json_file, indent=4, separators=(',', ': '))
355
356 os.rename(new_file, args_output.last_tested)
357
358
359if __name__ == '__main__':
360 main()