blob: b210c474dd2b84b651393b177796c3666727814d [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 Wu67be74b2018-10-15 14:17:26 +0800109def collect_removed_manifest_repos(repo_dir, last_sync_time):
110 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)
124 entries = parser.process_parsed_result(root)
125 if latest is None:
126 assert entries is not None
127 latest = entries
128 continue
129
130 for path, path_spec in entries.items():
131 if path in latest:
132 continue
133 if path in removed:
134 continue
135 removed[path] = path_spec
136
137 return removed
138
139
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800140def setup_chromeos_repos(opts, path_factory):
141 chromeos_mirror = path_factory.get_chromeos_mirror()
142 chromeos_tree = path_factory.get_chromeos_tree()
143 subvolume_or_makedirs(opts, chromeos_mirror)
144 subvolume_or_makedirs(opts, chromeos_tree)
145
146 manifest_url = (
147 'https://chrome-internal.googlesource.com/chromeos/manifest-internal')
148 repo_url = 'https://chromium.googlesource.com/external/repo.git'
149
150 if os.path.exists(os.path.join(chromeos_mirror, '.repo', 'manifests')):
151 logger.warning(
152 '%s has already been initialized, assume it is setup properly',
153 chromeos_mirror)
154 else:
155 logger.info('repo init for chromeos mirror')
156 repo_util.init(
157 chromeos_mirror,
158 manifest_url=manifest_url,
159 repo_url=repo_url,
160 mirror=True)
161
162 local_manifest_dir = os.path.join(chromeos_mirror, '.repo',
163 'local_manifests')
164 os.mkdir(local_manifest_dir)
165 with open(os.path.join(local_manifest_dir, 'manifest-versions.xml'),
166 'w') as f:
167 f.write('''<?xml version="1.0" encoding="UTF-8"?>
168 <manifest>
169 <project name="chromeos/manifest-versions" remote="cros-internal" />
170 </manifest>
171 ''')
172
173 logger.info('repo init for chromeos tree')
174 repo_util.init(
175 chromeos_tree,
176 manifest_url=manifest_url,
177 repo_url=repo_url,
178 reference=chromeos_mirror)
179
180 logger.info('repo sync for chromeos mirror (this takes hours; be patient)')
181 repo_util.sync(chromeos_mirror)
182
183 logger.info('repo sync for chromeos tree')
184 repo_util.sync(chromeos_tree)
185
186
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800187def read_last_sync_time(repo_dir):
188 timestamp_path = os.path.join(repo_dir, 'last_sync_time')
189 if os.path.exists(timestamp_path):
190 with open(timestamp_path) as f:
191 return int(f.read())
192 else:
193 # 4 months should be enough for most bisect cases.
194 return int(time.time()) - 86400 * 120
195
196
197def write_sync_time(repo_dir, sync_time):
198 timestamp_path = os.path.join(repo_dir, 'last_sync_time')
199 with open(timestamp_path, 'w') as f:
200 f.write('%d\n' % sync_time)
201
202
203def write_extra_manifest_to_mirror(repo_dir, removed):
204 local_manifest_dir = os.path.join(repo_dir, '.repo', 'local_manifests')
205 if not os.path.exists(local_manifest_dir):
206 os.mkdir(local_manifest_dir)
207 with open(os.path.join(local_manifest_dir, 'deleted-repos.xml'), 'w') as f:
208 f.write('''<?xml version="1.0" encoding="UTF-8"?>\n<manifest>\n''')
209 remotes = {}
210 for path_spec in removed.values():
211 scheme, netloc, remote_path = urlparse.urlsplit(path_spec.repo_url)[:3]
212 assert remote_path[0] == '/'
213 remote_path = remote_path[1:]
214 if (scheme, netloc) not in remotes:
215 remote_name = 'remote_for_deleted_repo_%s' % (scheme + netloc)
216 remotes[scheme, netloc] = remote_name
217 f.write(''' <remote name="%s" fetch="%s" />\n''' %
218 (remote_name, '%s://%s' % (scheme, netloc)))
219 f.write(''' <project name="%s" path="%s" remote="%s"/>\n''' %
220 (remote_path, path_spec.path, remotes[scheme, netloc]))
221 f.write('''</manifest>\n''')
222
223
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800224def sync_chromeos_code(opts, path_factory):
225 del opts # unused
226
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800227 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800228 chromeos_mirror = path_factory.get_chromeos_mirror()
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800229
230 last_sync_time = read_last_sync_time(chromeos_mirror)
231 removed = collect_removed_manifest_repos(chromeos_mirror, last_sync_time)
232 write_extra_manifest_to_mirror(chromeos_mirror, removed)
233 logger.info('since last sync, %d repo got removed', len(removed))
234
235 logger.info('repo sync for chromeos mirror')
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800236 repo_util.sync(chromeos_mirror)
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800237 write_sync_time(chromeos_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800238
239 logger.info('repo sync for chromeos tree')
240 chromeos_tree = path_factory.get_chromeos_tree()
241 repo_util.sync(chromeos_tree)
242
243 # test_that may use this ssh key and ssh complains its permission is too open
244 util.check_call(
245 'chmod',
246 'o-r,g-r',
247 'src/scripts/mod_for_test_scripts/ssh_keys/testing_rsa',
248 cwd=chromeos_tree)
249
250
251def query_chrome_latest_branch():
252 result = None
253 r = urllib2.urlopen('https://omahaproxy.appspot.com/all')
254 for row in csv.DictReader(r):
255 if row['true_branch'].isdigit():
256 result = max(result, int(row['true_branch']))
257 return result
258
259
260def setup_chrome_repos(opts, path_factory):
261 chrome_cache = path_factory.get_chrome_cache()
262 subvolume_or_makedirs(opts, chrome_cache)
263 chrome_tree = path_factory.get_chrome_tree()
264 subvolume_or_makedirs(opts, chrome_tree)
265
266 latest_branch = query_chrome_latest_branch()
267 logger.info('latest chrome branch is %d', latest_branch)
268 assert latest_branch
269 spec = '''
270solutions = [
271 { "name" : "buildspec",
272 "url" : "https://chrome-internal.googlesource.com/a/chrome/tools/buildspec.git",
273 "deps_file" : "branches/%d/DEPS",
274 "custom_deps" : {
275 },
276 "custom_vars": {'checkout_src_internal': True},
277 },
278]
279target_os = ['chromeos']
280cache_dir = %r
281''' % (latest_branch, chrome_cache)
282
283 logger.info('gclient config for chrome')
284 gclient_util.config(chrome_tree, spec=spec)
285
286 is_first_sync = not os.listdir(chrome_cache)
287 if is_first_sync:
288 logger.info('gclient sync for chrome (this takes hours; be patient)')
289 else:
290 logger.info('gclient sync for chrome')
291 gclient_util.sync(chrome_tree, with_branch_heads=True, with_tags=True)
292
293 # It's possible that some repos are removed from latest branch and thus their
294 # commit history is not fetched in recent gclient sync. So we call 'git
295 # fetch' for all existing git mirrors.
296 # TODO(kcwu): only sync repos not in DEPS files of latest branch
297 logger.info('additional sync for chrome mirror')
298 for git_repo_name in os.listdir(chrome_cache):
299 # another gclient is running or leftover of previous run; skip
300 if git_repo_name.startswith('_cache_tmp'):
301 continue
302 git_repo = os.path.join(chrome_cache, git_repo_name)
303 if not git_util.is_git_rev(git_repo):
304 continue
305 util.check_call('git', 'fetch', cwd=git_repo)
306
307
308def sync_chrome_code(opts, path_factory):
309 # The sync step is identical to the initial gclient config step.
310 setup_chrome_repos(opts, path_factory)
311
312
313def setup_android_repos(opts, path_factory, branch):
314 android_mirror = path_factory.get_android_mirror(branch)
315 android_tree = path_factory.get_android_tree(branch)
316 subvolume_or_makedirs(opts, android_mirror)
317 subvolume_or_makedirs(opts, android_tree)
318
319 manifest_url = ('persistent-https://googleplex-android.git.corp.google.com'
320 '/platform/manifest')
321 repo_url = 'https://gerrit.googlesource.com/git-repo'
322
323 if os.path.exists(os.path.join(android_mirror, '.repo', 'manifests')):
324 logger.warning(
325 '%s has already been initialized, assume it is setup properly',
326 android_mirror)
327 else:
328 logger.info('repo init for android mirror branch=%s', branch)
329 repo_util.init(
330 android_mirror,
331 manifest_url=manifest_url,
332 repo_url=repo_url,
333 manifest_branch=branch,
334 mirror=True)
335
336 logger.info('repo init for android tree branch=%s', branch)
337 repo_util.init(
338 android_tree,
339 manifest_url=manifest_url,
340 repo_url=repo_url,
341 manifest_branch=branch,
342 reference=android_mirror)
343
344 logger.info('repo sync for android mirror (this takes hours; be patient)')
345 repo_util.sync(android_mirror, current_branch=True)
346
347 logger.info('repo sync for android tree branch=%s', branch)
348 repo_util.sync(android_tree, current_branch=True)
349
350
351def sync_android_code(opts, path_factory, branch):
352 del opts # unused
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800353 start_sync_time = int(time.time())
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800354 android_mirror = path_factory.get_android_mirror(branch)
355 android_tree = path_factory.get_android_tree(branch)
356
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800357 last_sync_time = read_last_sync_time(android_mirror)
358 removed = collect_removed_manifest_repos(android_mirror, last_sync_time)
359 write_extra_manifest_to_mirror(android_mirror, removed)
360 logger.info('since last sync, %d repo got removed', len(removed))
361
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800362 logger.info('repo sync for android mirror branch=%s', branch)
363 repo_util.sync(android_mirror, current_branch=True)
Kuang-che Wu67be74b2018-10-15 14:17:26 +0800364 write_sync_time(android_mirror, start_sync_time)
Kuang-che Wu41e8b592018-09-25 17:01:30 +0800365
366 logger.info('repo sync for android tree branch=%s', branch)
367 repo_util.sync(android_tree, current_branch=True)
368
369
370def cmd_init(opts):
371 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
372 CHECKOUT_TEMPLATE_NAME)
373
374 if opts.chromeos:
375 setup_chromeos_repos(opts, path_factory)
376 if opts.chrome:
377 setup_chrome_repos(opts, path_factory)
378 for branch in opts.android:
379 setup_android_repos(opts, path_factory, branch)
380
381
382def enumerate_android_branches_available(base):
383 branches = []
384 for name in os.listdir(base):
385 if name.startswith('android.'):
386 branches.append(name.partition('.')[2])
387 return branches
388
389
390def cmd_sync(opts):
391 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
392 CHECKOUT_TEMPLATE_NAME)
393
394 sync_all = False
395 if not opts.chromeos and not opts.chrome and not opts.android:
396 logger.info('sync trees for all')
397 sync_all = True
398
399 if sync_all or opts.chromeos:
400 sync_chromeos_code(opts, path_factory)
401 if sync_all or opts.chrome:
402 sync_chrome_code(opts, path_factory)
403
404 if sync_all:
405 android_branches = enumerate_android_branches_available(opts.mirror_base)
406 else:
407 android_branches = opts.android
408 for branch in android_branches:
409 sync_android_code(opts, path_factory, branch)
410
411
412def cmd_new(opts):
413 work_dir = os.path.join(opts.work_base, opts.session)
414 if not os.path.exists(work_dir):
415 os.makedirs(work_dir)
416
417 template_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
418 CHECKOUT_TEMPLATE_NAME)
419 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
420 opts.session)
421
422 prepare_all = False
423 if not opts.chromeos and not opts.chrome and not opts.android:
424 logger.info('prepare trees for all')
425 prepare_all = True
426
427 chromeos_template = template_factory.get_chromeos_tree()
428 if (prepare_all and os.path.exists(chromeos_template)) or opts.chromeos:
429 logger.info('prepare tree for chromeos, %s',
430 path_factory.get_chromeos_tree())
431 snapshot_or_copytree(chromeos_template, path_factory.get_chromeos_tree())
432
433 chrome_template = template_factory.get_chrome_tree()
434 if (prepare_all and os.path.exists(chrome_template)) or opts.chrome:
435 logger.info('prepare tree for chrome, %s', path_factory.get_chrome_tree())
436 snapshot_or_copytree(chrome_template, path_factory.get_chrome_tree())
437
438 if prepare_all:
439 android_branches = enumerate_android_branches_available(opts.mirror_base)
440 else:
441 android_branches = opts.android
442 for branch in android_branches:
443 logger.info('prepare tree for android branch=%s, %s', branch,
444 path_factory.get_android_tree(branch))
445 snapshot_or_copytree(
446 template_factory.get_android_tree(branch),
447 path_factory.get_android_tree(branch))
448
449
450def delete_tree(path):
451 if is_btrfs_subvolume(path):
452 util.check_call('btrfs', 'subvolume', 'delete', path)
453 else:
454 util.check_call('rm', '-rf', path)
455
456
457def cmd_list(opts):
458 print('%-20s %s' % ('Session', 'Path'))
459 for name in os.listdir(opts.work_base):
460 if name == CHECKOUT_TEMPLATE_NAME:
461 continue
462 path = os.path.join(opts.work_base, name)
463 print('%-20s %s' % (name, path))
464
465
466def cmd_delete(opts):
467 assert opts.session
468 path_factory = DefaultProjectPathFactory(opts.mirror_base, opts.work_base,
469 opts.session)
470
471 chromeos_tree = path_factory.get_chromeos_tree()
472 if os.path.exists(chromeos_tree):
473 if os.path.exists(os.path.join(chromeos_tree, 'chromite')):
474 # ignore error
475 util.call('cros_sdk', '--unmount', cwd=chromeos_tree)
476 delete_tree(chromeos_tree)
477
478 chrome_tree = path_factory.get_chrome_tree()
479 if os.path.exists(chrome_tree):
480 delete_tree(chrome_tree)
481
482 android_branches = enumerate_android_branches_available(opts.mirror_base)
483 for branch in android_branches:
484 android_tree = path_factory.get_android_tree(branch)
485 if os.path.exists(android_tree):
486 delete_tree(android_tree)
487
488 os.rmdir(os.path.join(opts.work_base, opts.session))
489
490
491def create_parser():
492 parser = argparse.ArgumentParser(
493 formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__)
494 parser.add_argument(
495 '--mirror_base',
496 metavar='MIRROR_BASE',
497 default=configure.get('MIRROR_BASE', DEFAULT_MIRROR_BASE),
498 help='Directory for mirrors (default: %(default)s)')
499 parser.add_argument(
500 '--work_base',
501 metavar='WORK_BASE',
502 default=configure.get('WORK_BASE', DEFAULT_WORK_BASE),
503 help='Directory for bisection working directories (default: %(default)s)')
504 common.add_common_arguments(parser)
505 subparsers = parser.add_subparsers(
506 dest='command', title='commands', metavar='<command>')
507
508 parser_init = subparsers.add_parser(
509 'init', help='Mirror source trees and create template checkout')
510 parser_init.add_argument(
511 '--chrome', action='store_true', help='init chrome mirror and tree')
512 parser_init.add_argument(
513 '--chromeos', action='store_true', help='init chromeos mirror and tree')
514 parser_init.add_argument(
515 '--android',
516 metavar='BRANCH',
517 action='append',
518 default=[],
519 help='init android mirror and tree of BRANCH')
520 parser_init.add_argument(
521 '--btrfs',
522 action='store_true',
523 help='create btrfs subvolume for source tree')
524 parser_init.set_defaults(func=cmd_init)
525
526 parser_sync = subparsers.add_parser(
527 'sync',
528 help='Sync source trees',
529 description='Sync all if no projects are specified '
530 '(--chrome, --chromeos, or --android)')
531 parser_sync.add_argument(
532 '--chrome', action='store_true', help='sync chrome mirror and tree')
533 parser_sync.add_argument(
534 '--chromeos', action='store_true', help='sync chromeos mirror and tree')
535 parser_sync.add_argument(
536 '--android',
537 metavar='BRANCH',
538 action='append',
539 default=[],
540 help='sync android mirror and tree of BRANCH')
541 parser_sync.set_defaults(func=cmd_sync)
542
543 parser_new = subparsers.add_parser(
544 'new',
545 help='Create new source checkout for bisect',
546 description='Create for all if no projects are specified '
547 '(--chrome, --chromeos, or --android)')
548 parser_new.add_argument('--session', required=True)
549 parser_new.add_argument(
550 '--chrome', action='store_true', help='create chrome checkout')
551 parser_new.add_argument(
552 '--chromeos', action='store_true', help='create chromeos checkout')
553 parser_new.add_argument(
554 '--android',
555 metavar='BRANCH',
556 action='append',
557 default=[],
558 help='create android checkout of BRANCH')
559 parser_new.set_defaults(func=cmd_new)
560
561 parser_list = subparsers.add_parser(
562 'list', help='List existing sessions with source checkout')
563 parser_list.set_defaults(func=cmd_list)
564
565 parser_delete = subparsers.add_parser('delete', help='Delete source checkout')
566 parser_delete.add_argument('--session', required=True)
567 parser_delete.set_defaults(func=cmd_delete)
568
569 return parser
570
571
572def main():
573 common.init()
574 parser = create_parser()
575 opts = parser.parse_args()
576 common.config_logging(opts)
577
578 opts.func(opts)
579
580
581if __name__ == '__main__':
582 main()