blob: 3ab4eea5b5b69ea0f91e80fac83df0afe3277958 [file] [log] [blame]
Kuang-che Wu41e8b592018-09-25 17:01:30 +08001#!/usr/bin/env python2
2# -*- coding: utf-8 -*-
3# Copyright 2018 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"""Helper script to prepare source trees for ChromeOS bisection.
7
8Typical usage:
9
10 Initial setup:
11 $ %(prog)s init --chromeos
12 $ %(prog)s init --chrome
13 $ %(prog)s init --android=pi-arc-dev
14
15 Sync code if necessary:
16 $ %(prog)s sync
17
18 Create source trees for bisection
19 $ %(prog)s new --session=12345
20
21 After bisection finished, delete trees
22 $ %(prog)s delete --session=12345
23"""
24from __future__ import print_function
25import argparse
26import csv
27import logging
28import os
Kuang-che Wu67be74b2018-10-15 14:17:26 +080029import time
Kuang-che Wu41e8b592018-09-25 17:01:30 +080030import urllib2
Kuang-che Wu67be74b2018-10-15 14:17:26 +080031import urlparse
Kuang-che Wu41e8b592018-09-25 17:01:30 +080032
33from bisect_kit import common
34from bisect_kit import configure
35from bisect_kit import gclient_util
36from bisect_kit import git_util
37from bisect_kit import repo_util
38from bisect_kit import util
39
40DEFAULT_MIRROR_BASE = os.path.expanduser('~/git-mirrors')
41DEFAULT_WORK_BASE = os.path.expanduser('~/bisect-workdir')
42CHECKOUT_TEMPLATE_NAME = 'template'
43
44logger = logging.getLogger(__name__)
45
46
47class DefaultProjectPathFactory(object):
48 """Factory for chromeos/chrome/android source tree paths."""
49
50 def __init__(self, mirror_base, work_base, session):
51 self.mirror_base = mirror_base
52 self.work_base = work_base
53 self.session = session
54
55 def get_chromeos_mirror(self):
56 return os.path.join(self.mirror_base, 'chromeos')
57
58 def get_chromeos_tree(self):
59 return os.path.join(self.work_base, self.session, 'chromeos')
60
61 def get_android_mirror(self, branch):
62 return os.path.join(self.mirror_base, 'android.%s' % branch)
63
64 def get_android_tree(self, branch):
65 return os.path.join(self.work_base, self.session, 'android.%s' % branch)
66
67 def get_chrome_cache(self):
68 return os.path.join(self.mirror_base, 'chrome')
69
70 def get_chrome_tree(self):
71 return os.path.join(self.work_base, self.session, 'chrome')
72
73
74def subvolume_or_makedirs(opts, path):
75 if os.path.exists(path):
76 return
77
78 path = os.path.abspath(path)
79 if opts.btrfs:
80 dirname, basename = os.path.split(path)
81 if not os.path.exists(dirname):
82 os.makedirs(dirname)
83 util.check_call('btrfs', 'subvolume', 'create', basename, cwd=dirname)
84 else:
85 os.makedirs(path)
86
87
88def is_btrfs_subvolume(path):
89 if util.check_output('stat', '-f', '--format=%T', path).strip() != 'btrfs':
90 return False
91 return util.check_output('stat', '--format=%i', path).strip() == '256'
92
93
94def snapshot_or_copytree(src, dst):
95 assert os.path.isdir(src), '%s does not exist' % src
96 assert os.path.isdir(os.path.dirname(dst))
97
98 # Make sure dst do not exist, otherwise it becomes "dst/name" (one extra
99 # depth) instead of "dst".
100 assert not os.path.exists(dst)
101
102 if is_btrfs_subvolume(src):
103 util.check_call('btrfs', 'subvolume', 'snapshot', src, dst)
104 else:
105 # -a for recursion and preserve all attributes.
106 util.check_call('cp', '-a', src, dst)
107
108
Kuang-che Wubfa64482018-10-16 11:49:49 +0800109def collect_removed_manifest_repos(repo_dir, last_sync_time, only_branch=None):
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800110 manifest_dir = os.path.join(repo_dir, '.repo', 'manifests')
111
112 manifest_path = 'default.xml'
113 manifest_full_path = os.path.join(manifest_dir, manifest_path)
114 # hack for chromeos symlink
115 if os.path.islink(manifest_full_path):
116 manifest_path = os.readlink(manifest_full_path)
117
118 parser = repo_util.ManifestParser(manifest_dir)
119 latest = None
120 removed = {}
121 for _, git_rev in reversed(
122 parser.enumerate_manifest_commits(last_sync_time, None, manifest_path)):
123 root = parser.parse_xml_recursive(git_rev, manifest_path)
Kuang-che Wubfa64482018-10-16 11:49:49 +0800124 if (only_branch and root.find('default') is not None and
125 root.find('default').get('revision') != only_branch):
126 break
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800127 entries = parser.process_parsed_result(root)
128 if latest is None:
129 assert entries is not None
130 latest = entries
131 continue
132
133 for path, path_spec in entries.items():
134 if path in latest:
135 continue
136 if path in removed:
137 continue
138 removed[path] = path_spec
139
140 return removed
141
142
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800143def setup_chromeos_repos(opts, path_factory):
144 chromeos_mirror = path_factory.get_chromeos_mirror()
145 chromeos_tree = path_factory.get_chromeos_tree()
146 subvolume_or_makedirs(opts, chromeos_mirror)
147 subvolume_or_makedirs(opts, chromeos_tree)
148
149 manifest_url = (
150 'https://chrome-internal.googlesource.com/chromeos/manifest-internal')
151 repo_url = 'https://chromium.googlesource.com/external/repo.git'
152
153 if os.path.exists(os.path.join(chromeos_mirror, '.repo', 'manifests')):
154 logger.warning(
155 '%s has already been initialized, assume it is setup properly',
156 chromeos_mirror)
157 else:
158 logger.info('repo init for chromeos mirror')
159 repo_util.init(
160 chromeos_mirror,
161 manifest_url=manifest_url,
162 repo_url=repo_url,
163 mirror=True)
164
165 local_manifest_dir = os.path.join(chromeos_mirror, '.repo',
166 'local_manifests')
167 os.mkdir(local_manifest_dir)
168 with open(os.path.join(local_manifest_dir, 'manifest-versions.xml'),
169 'w') as f:
170 f.write('''<?xml version="1.0" encoding="UTF-8"?>
171 <manifest>
172 <project name="chromeos/manifest-versions" remote="cros-internal" />
173 </manifest>
174 ''')
175
176 logger.info('repo init for chromeos tree')
177 repo_util.init(
178 chromeos_tree,
179 manifest_url=manifest_url,
180 repo_url=repo_url,
181 reference=chromeos_mirror)
182
183 logger.info('repo sync for chromeos mirror (this takes hours; be patient)')
184 repo_util.sync(chromeos_mirror)
185
186 logger.info('repo sync for chromeos tree')
187 repo_util.sync(chromeos_tree)
188
189
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800190def read_last_sync_time(repo_dir):
191 timestamp_path = os.path.join(repo_dir, 'last_sync_time')
192 if os.path.exists(timestamp_path):
193 with open(timestamp_path) as f:
194 return int(f.read())
195 else:
196 # 4 months should be enough for most bisect cases.
197 return int(time.time()) - 86400 * 120
198
199
200def write_sync_time(repo_dir, sync_time):
201 timestamp_path = os.path.join(repo_dir, 'last_sync_time')
202 with open(timestamp_path, 'w') as f:
203 f.write('%d\n' % sync_time)
204
205
206def write_extra_manifest_to_mirror(repo_dir, removed):
207 local_manifest_dir = os.path.join(repo_dir, '.repo', 'local_manifests')
208 if not os.path.exists(local_manifest_dir):
209 os.mkdir(local_manifest_dir)
210 with open(os.path.join(local_manifest_dir, 'deleted-repos.xml'), 'w') as f:
211 f.write('''<?xml version="1.0" encoding="UTF-8"?>\n<manifest>\n''')
212 remotes = {}
213 for path_spec in removed.values():
214 scheme, netloc, remote_path = urlparse.urlsplit(path_spec.repo_url)[:3]
215 assert remote_path[0] == '/'
216 remote_path = remote_path[1:]
217 if (scheme, netloc) not in remotes:
218 remote_name = 'remote_for_deleted_repo_%s' % (scheme + netloc)
219 remotes[scheme, netloc] = remote_name
220 f.write(''' <remote name="%s" fetch="%s" />\n''' %
221 (remote_name, '%s://%s' % (scheme, netloc)))
Kuang-che Wubfa64482018-10-16 11:49:49 +0800222 f.write(
223 ''' <project name="%s" path="%s" remote="%s" revision="%s" />\n''' %
224 (remote_path, path_spec.path, remotes[scheme, netloc], path_spec.at))
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800225 f.write('''</manifest>\n''')
226
227
Kuang-che Wubfa64482018-10-16 11:49:49 +0800228def generate_extra_manifest_for_deleted_repo(repo_dir, only_branch=None):
229 last_sync_time = read_last_sync_time(repo_dir)
230 removed = collect_removed_manifest_repos(
231 repo_dir, last_sync_time, only_branch=only_branch)
232 write_extra_manifest_to_mirror(repo_dir, removed)
233 logger.info('since last sync, %d repo got removed', len(removed))
234
235
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800236def sync_chromeos_code(opts, path_factory):
237 del opts # unused
238
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800239 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800240 chromeos_mirror = path_factory.get_chromeos_mirror()
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800241
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800242 logger.info('repo sync for chromeos mirror')
Kuang-che Wubfa64482018-10-16 11:49:49 +0800243 generate_extra_manifest_for_deleted_repo(chromeos_mirror)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800244 repo_util.sync(chromeos_mirror)
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800245 write_sync_time(chromeos_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800246
247 logger.info('repo sync for chromeos tree')
248 chromeos_tree = path_factory.get_chromeos_tree()
249 repo_util.sync(chromeos_tree)
250
251 # test_that may use this ssh key and ssh complains its permission is too open
252 util.check_call(
253 'chmod',
254 'o-r,g-r',
255 'src/scripts/mod_for_test_scripts/ssh_keys/testing_rsa',
256 cwd=chromeos_tree)
257
258
259def query_chrome_latest_branch():
260 result = None
261 r = urllib2.urlopen('https://omahaproxy.appspot.com/all')
262 for row in csv.DictReader(r):
263 if row['true_branch'].isdigit():
264 result = max(result, int(row['true_branch']))
265 return result
266
267
268def setup_chrome_repos(opts, path_factory):
269 chrome_cache = path_factory.get_chrome_cache()
270 subvolume_or_makedirs(opts, chrome_cache)
271 chrome_tree = path_factory.get_chrome_tree()
272 subvolume_or_makedirs(opts, chrome_tree)
273
274 latest_branch = query_chrome_latest_branch()
275 logger.info('latest chrome branch is %d', latest_branch)
276 assert latest_branch
277 spec = '''
278solutions = [
279 { "name" : "buildspec",
280 "url" : "https://chrome-internal.googlesource.com/a/chrome/tools/buildspec.git",
281 "deps_file" : "branches/%d/DEPS",
282 "custom_deps" : {
283 },
284 "custom_vars": {'checkout_src_internal': True},
285 },
286]
287target_os = ['chromeos']
288cache_dir = %r
289''' % (latest_branch, chrome_cache)
290
291 logger.info('gclient config for chrome')
292 gclient_util.config(chrome_tree, spec=spec)
293
294 is_first_sync = not os.listdir(chrome_cache)
295 if is_first_sync:
296 logger.info('gclient sync for chrome (this takes hours; be patient)')
297 else:
298 logger.info('gclient sync for chrome')
299 gclient_util.sync(chrome_tree, with_branch_heads=True, with_tags=True)
300
301 # It's possible that some repos are removed from latest branch and thus their
302 # commit history is not fetched in recent gclient sync. So we call 'git
303 # fetch' for all existing git mirrors.
304 # TODO(kcwu): only sync repos not in DEPS files of latest branch
305 logger.info('additional sync for chrome mirror')
306 for git_repo_name in os.listdir(chrome_cache):
307 # another gclient is running or leftover of previous run; skip
308 if git_repo_name.startswith('_cache_tmp'):
309 continue
310 git_repo = os.path.join(chrome_cache, git_repo_name)
311 if not git_util.is_git_rev(git_repo):
312 continue
313 util.check_call('git', 'fetch', cwd=git_repo)
314
315
316def sync_chrome_code(opts, path_factory):
317 # The sync step is identical to the initial gclient config step.
318 setup_chrome_repos(opts, path_factory)
319
320
321def setup_android_repos(opts, path_factory, branch):
322 android_mirror = path_factory.get_android_mirror(branch)
323 android_tree = path_factory.get_android_tree(branch)
324 subvolume_or_makedirs(opts, android_mirror)
325 subvolume_or_makedirs(opts, android_tree)
326
327 manifest_url = ('persistent-https://googleplex-android.git.corp.google.com'
328 '/platform/manifest')
329 repo_url = 'https://gerrit.googlesource.com/git-repo'
330
331 if os.path.exists(os.path.join(android_mirror, '.repo', 'manifests')):
332 logger.warning(
333 '%s has already been initialized, assume it is setup properly',
334 android_mirror)
335 else:
336 logger.info('repo init for android mirror branch=%s', branch)
337 repo_util.init(
338 android_mirror,
339 manifest_url=manifest_url,
340 repo_url=repo_url,
341 manifest_branch=branch,
342 mirror=True)
343
344 logger.info('repo init for android tree branch=%s', branch)
345 repo_util.init(
346 android_tree,
347 manifest_url=manifest_url,
348 repo_url=repo_url,
349 manifest_branch=branch,
350 reference=android_mirror)
351
352 logger.info('repo sync for android mirror (this takes hours; be patient)')
353 repo_util.sync(android_mirror, current_branch=True)
354
355 logger.info('repo sync for android tree branch=%s', branch)
356 repo_util.sync(android_tree, current_branch=True)
357
358
359def sync_android_code(opts, path_factory, branch):
360 del opts # unused
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800361 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800362 android_mirror = path_factory.get_android_mirror(branch)
363 android_tree = path_factory.get_android_tree(branch)
364
365 logger.info('repo sync for android mirror branch=%s', branch)
Kuang-che Wubfa64482018-10-16 11:49:49 +0800366 # Android usually big jump between milestone releases and add/delete lots of
367 # repos when switch releases. Because it's infeasible to bisect between such
368 # big jump, the deleted repo is useless. In order to save disk, do not sync
369 # repos deleted in other branches.
370 generate_extra_manifest_for_deleted_repo(android_mirror, only_branch=branch)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800371 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800372 write_sync_time(android_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800373
374 logger.info('repo sync for android tree branch=%s', branch)
375 repo_util.sync(android_tree, current_branch=True)
376
377
378def cmd_init(opts):
379 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
380 CHECKOUT_TEMPLATE_NAME)
381
382 if opts.chromeos:
383 setup_chromeos_repos(opts, path_factory)
384 if opts.chrome:
385 setup_chrome_repos(opts, path_factory)
386 for branch in opts.android:
387 setup_android_repos(opts, path_factory, branch)
388
389
390def enumerate_android_branches_available(base):
391 branches = []
392 for name in os.listdir(base):
393 if name.startswith('android.'):
394 branches.append(name.partition('.')[2])
395 return branches
396
397
398def cmd_sync(opts):
399 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
400 CHECKOUT_TEMPLATE_NAME)
401
402 sync_all = False
403 if not opts.chromeos and not opts.chrome and not opts.android:
404 logger.info('sync trees for all')
405 sync_all = True
406
407 if sync_all or opts.chromeos:
408 sync_chromeos_code(opts, path_factory)
409 if sync_all or opts.chrome:
410 sync_chrome_code(opts, path_factory)
411
412 if sync_all:
413 android_branches = enumerate_android_branches_available(opts.mirror_base)
414 else:
415 android_branches = opts.android
416 for branch in android_branches:
417 sync_android_code(opts, path_factory, branch)
418
419
420def cmd_new(opts):
421 work_dir = os.path.join(opts.work_base, opts.session)
422 if not os.path.exists(work_dir):
423 os.makedirs(work_dir)
424
425 template_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
426 CHECKOUT_TEMPLATE_NAME)
427 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
428 opts.session)
429
430 prepare_all = False
431 if not opts.chromeos and not opts.chrome and not opts.android:
432 logger.info('prepare trees for all')
433 prepare_all = True
434
435 chromeos_template = template_factory.get_chromeos_tree()
436 if (prepare_all and os.path.exists(chromeos_template)) or opts.chromeos:
437 logger.info('prepare tree for chromeos, %s',
438 path_factory.get_chromeos_tree())
439 snapshot_or_copytree(chromeos_template, path_factory.get_chromeos_tree())
440
441 chrome_template = template_factory.get_chrome_tree()
442 if (prepare_all and os.path.exists(chrome_template)) or opts.chrome:
443 logger.info('prepare tree for chrome, %s', path_factory.get_chrome_tree())
444 snapshot_or_copytree(chrome_template, path_factory.get_chrome_tree())
445
446 if prepare_all:
447 android_branches = enumerate_android_branches_available(opts.mirror_base)
448 else:
449 android_branches = opts.android
450 for branch in android_branches:
451 logger.info('prepare tree for android branch=%s, %s', branch,
452 path_factory.get_android_tree(branch))
453 snapshot_or_copytree(
454 template_factory.get_android_tree(branch),
455 path_factory.get_android_tree(branch))
456
457
458def delete_tree(path):
459 if is_btrfs_subvolume(path):
460 util.check_call('btrfs', 'subvolume', 'delete', path)
461 else:
462 util.check_call('rm', '-rf', path)
463
464
465def cmd_list(opts):
466 print('%-20s %s' % ('Session', 'Path'))
467 for name in os.listdir(opts.work_base):
468 if name == CHECKOUT_TEMPLATE_NAME:
469 continue
470 path = os.path.join(opts.work_base, name)
471 print('%-20s %s' % (name, path))
472
473
474def cmd_delete(opts):
475 assert opts.session
476 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
477 opts.session)
478
479 chromeos_tree = path_factory.get_chromeos_tree()
480 if os.path.exists(chromeos_tree):
481 if os.path.exists(os.path.join(chromeos_tree, 'chromite')):
482 # ignore error
483 util.call('cros_sdk', '--unmount', cwd=chromeos_tree)
484 delete_tree(chromeos_tree)
485
486 chrome_tree = path_factory.get_chrome_tree()
487 if os.path.exists(chrome_tree):
488 delete_tree(chrome_tree)
489
490 android_branches = enumerate_android_branches_available(opts.mirror_base)
491 for branch in android_branches:
492 android_tree = path_factory.get_android_tree(branch)
493 if os.path.exists(android_tree):
494 delete_tree(android_tree)
495
496 os.rmdir(os.path.join(opts.work_base, opts.session))
497
498
499def create_parser():
500 parser = argparse.ArgumentParser(
501 formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
502 parser.add_argument(
503 '--mirror_base',
504 metavar='MIRROR_BASE',
505 default=configure.get('MIRROR_BASE', DEFAULT_MIRROR_BASE),
506 help='Directory for mirrors (default: %(default)s)')
507 parser.add_argument(
508 '--work_base',
509 metavar='WORK_BASE',
510 default=configure.get('WORK_BASE', DEFAULT_WORK_BASE),
511 help='Directory for bisection working directories (default: %(default)s)')
512 common.add_common_arguments(parser)
513 subparsers = parser.add_subparsers(
514 dest='command', title='commands', metavar='<command>')
515
516 parser_init = subparsers.add_parser(
517 'init', help='Mirror source trees and create template checkout')
518 parser_init.add_argument(
519 '--chrome', action='store_true', help='init chrome mirror and tree')
520 parser_init.add_argument(
521 '--chromeos', action='store_true', help='init chromeos mirror and tree')
522 parser_init.add_argument(
523 '--android',
524 metavar='BRANCH',
525 action='append',
526 default=[],
527 help='init android mirror and tree of BRANCH')
528 parser_init.add_argument(
529 '--btrfs',
530 action='store_true',
531 help='create btrfs subvolume for source tree')
532 parser_init.set_defaults(func=cmd_init)
533
534 parser_sync = subparsers.add_parser(
535 'sync',
536 help='Sync source trees',
537 description='Sync all if no projects are specified '
538 '(--chrome, --chromeos, or --android)')
539 parser_sync.add_argument(
540 '--chrome', action='store_true', help='sync chrome mirror and tree')
541 parser_sync.add_argument(
542 '--chromeos', action='store_true', help='sync chromeos mirror and tree')
543 parser_sync.add_argument(
544 '--android',
545 metavar='BRANCH',
546 action='append',
547 default=[],
548 help='sync android mirror and tree of BRANCH')
549 parser_sync.set_defaults(func=cmd_sync)
550
551 parser_new = subparsers.add_parser(
552 'new',
553 help='Create new source checkout for bisect',
554 description='Create for all if no projects are specified '
555 '(--chrome, --chromeos, or --android)')
556 parser_new.add_argument('--session', required=True)
557 parser_new.add_argument(
558 '--chrome', action='store_true', help='create chrome checkout')
559 parser_new.add_argument(
560 '--chromeos', action='store_true', help='create chromeos checkout')
561 parser_new.add_argument(
562 '--android',
563 metavar='BRANCH',
564 action='append',
565 default=[],
566 help='create android checkout of BRANCH')
567 parser_new.set_defaults(func=cmd_new)
568
569 parser_list = subparsers.add_parser(
570 'list', help='List existing sessions with source checkout')
571 parser_list.set_defaults(func=cmd_list)
572
573 parser_delete = subparsers.add_parser('delete', help='Delete source checkout')
574 parser_delete.add_argument('--session', required=True)
575 parser_delete.set_defaults(func=cmd_delete)
576
577 return parser
578
579
580def main():
581 common.init()
582 parser = create_parser()
583 opts = parser.parse_args()
584 common.config_logging(opts)
585
586 opts.func(opts)
587
588
589if __name__ == '__main__':
590 main()