blob: 4f0f0faa6a1db3a95a67050e3fd499b6b547223d [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Mike Frysingerd6925b52012-07-16 16:11:00 -04002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Brian Harring3fec5a82012-03-01 05:57:03 -08003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Main builder code for Chromium OS.
7
8Used by Chromium OS buildbot configuration for all Chromium OS builds including
9full and pre-flight-queue builds.
10"""
11
Mike Frysinger383367e2014-09-16 15:06:17 -040012from __future__ import print_function
13
Aviv Keshet593014d2017-07-18 17:28:25 -070014import distutils.version # pylint: disable=import-error,no-name-in-module
Brian Harring3fec5a82012-03-01 05:57:03 -080015import glob
Aviv Keshet669eb5e2014-06-23 08:53:01 -070016import json
Mike Frysingerb0b0caa2015-11-07 01:05:18 -050017import optparse # pylint: disable=deprecated-module
Brian Harring3fec5a82012-03-01 05:57:03 -080018import os
Aviv Keshetcf9c2722014-02-25 15:15:10 -080019import pickle
Brian Harring3fec5a82012-03-01 05:57:03 -080020import sys
21
Mike Frysingere4d68c22015-02-04 21:26:24 -050022from chromite.cbuildbot import builders
Don Garrett88b8d782014-05-13 17:30:55 -070023from chromite.cbuildbot import cbuildbot_run
Don Garrett88b8d782014-05-13 17:30:55 -070024from chromite.cbuildbot import repository
25from chromite.cbuildbot import tee
Aviv Keshet420de512015-05-18 14:28:48 -070026from chromite.cbuildbot import topology
Don Garrett88b8d782014-05-13 17:30:55 -070027from chromite.cbuildbot.stages import completion_stages
Ningning Xiaf342b952017-02-15 14:13:33 -080028from chromite.lib import builder_status_lib
Aviv Keshet2982af52014-08-13 16:07:57 -070029from chromite.lib import cidb
Brian Harringc92a7012012-02-29 10:11:34 -080030from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080031from chromite.lib import cleanup
Brian Harringb6cf9142012-09-01 20:43:17 -070032from chromite.lib import commandline
Ningning Xia6a718052016-12-22 10:08:15 -080033from chromite.lib import config_lib
34from chromite.lib import constants
Brian Harring1b8c4c82012-05-29 23:03:04 -070035from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070036from chromite.lib import cros_logging as logging
Ningning Xia6a718052016-12-22 10:08:15 -080037from chromite.lib import failures_lib
David James97d95872012-11-16 15:09:56 -080038from chromite.lib import git
Stefan Zagerd49d9ff2014-08-15 21:33:37 -070039from chromite.lib import gob_util
Brian Harringaf019fb2012-05-10 15:06:13 -070040from chromite.lib import osutils
David James6450a0a2012-12-04 07:59:53 -080041from chromite.lib import parallel
Don Garrettb4318362014-10-03 15:49:36 -070042from chromite.lib import retry_stats
Brian Harring3fec5a82012-03-01 05:57:03 -080043from chromite.lib import sudo
David James3432acd2013-11-27 10:02:18 -080044from chromite.lib import timeout_util
Drew Davenportd7c22c12017-06-07 16:16:54 -060045from chromite.lib import tree_status
Paul Hobbsfcf10342015-12-29 15:52:31 -080046from chromite.lib import ts_mon_config
Dhanya Ganesh39a48a82018-12-06 16:01:11 -070047from chromite.lib.buildstore import BuildStore
Brian Harring3fec5a82012-03-01 05:57:03 -080048
Ryan Cuiadd49122012-03-21 22:19:58 -070049
Brian Harring3fec5a82012-03-01 05:57:03 -080050_DEFAULT_LOG_DIR = 'cbuildbot_logs'
51_BUILDBOT_LOG_FILE = 'cbuildbot.log'
52_DEFAULT_EXT_BUILDROOT = 'trybot'
53_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Brian Harring351ce442012-03-09 16:38:14 -080054_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Ryan Cui1c13a252012-10-16 15:00:16 -070055_API_VERSION_ATTR = 'api_version'
Brian Harring3fec5a82012-03-01 05:57:03 -080056
57
Brian Harring3fec5a82012-03-01 05:57:03 -080058def _BackupPreviousLog(log_file, backup_limit=25):
59 """Rename previous log.
60
61 Args:
62 log_file: The absolute path to the previous log.
Aviv Keshet9e4236b2013-12-13 13:07:50 -080063 backup_limit: Maximum number of old logs to keep.
Brian Harring3fec5a82012-03-01 05:57:03 -080064 """
65 if os.path.exists(log_file):
66 old_logs = sorted(glob.glob(log_file + '.*'),
67 key=distutils.version.LooseVersion)
68
69 if len(old_logs) >= backup_limit:
70 os.remove(old_logs[0])
71
72 last = 0
73 if old_logs:
74 last = int(old_logs.pop().rpartition('.')[2])
75
76 os.rename(log_file, log_file + '.' + str(last + 1))
77
Ryan Cui5616a512012-08-17 13:39:36 -070078
Gaurav Shah298aa372014-01-31 09:27:24 -080079def _IsDistributedBuilder(options, chrome_rev, build_config):
80 """Determines whether the builder should be a DistributedBuilder.
81
82 Args:
83 options: options passed on the commandline.
84 chrome_rev: Chrome revision to build.
85 build_config: Builder configuration dictionary.
86
87 Returns:
88 True if the builder should be a distributed_builder
89 """
Don Garrett0bc85672015-07-23 19:46:00 +000090 if build_config['pre_cq']:
Gaurav Shah298aa372014-01-31 09:27:24 -080091 return True
92 elif not options.buildbot:
93 return False
94 elif chrome_rev in (constants.CHROME_REV_TOT,
95 constants.CHROME_REV_LOCAL,
96 constants.CHROME_REV_SPEC):
97 # We don't do distributed logic to TOT Chrome PFQ's, nor local
98 # chrome roots (e.g. chrome try bots)
99 # TODO(davidjames): Update any builders that rely on this logic to use
100 # manifest_version=False instead.
101 return False
102 elif build_config['manifest_version']:
103 return True
104
105 return False
106
107
Don Garretta52a5b02015-06-02 14:52:57 -0700108def _RunBuildStagesWrapper(options, site_config, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800109 """Helper function that wraps RunBuildStages()."""
Lann Martinffb95162018-08-28 12:02:54 -0600110 logging.info('cbuildbot was executed with args %s',
Ralph Nathan03047282015-03-23 11:09:32 -0700111 cros_build_lib.CmdToStr(sys.argv))
Brian Harring3fec5a82012-03-01 05:57:03 -0800112
David Jamesa0a664e2013-02-13 09:52:01 -0800113 chrome_rev = build_config['chrome_rev']
114 if options.chrome_rev:
115 chrome_rev = options.chrome_rev
116 if chrome_rev == constants.CHROME_REV_TOT:
Stefan Zagerd49d9ff2014-08-15 21:33:37 -0700117 options.chrome_version = gob_util.GetTipOfTrunkRevision(
118 constants.CHROMIUM_GOB_URL)
David Jamesa0a664e2013-02-13 09:52:01 -0800119 options.chrome_rev = constants.CHROME_REV_SPEC
120
David James4a404a52013-02-19 13:07:59 -0800121 # If it's likely we'll need to build Chrome, fetch the source.
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500122 if build_config['sync_chrome'] is None:
David Jameseecba232014-06-11 11:35:11 -0700123 options.managed_chrome = (
124 chrome_rev != constants.CHROME_REV_LOCAL and
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500125 (not build_config['usepkg_build_packages'] or chrome_rev or
Mike Frysinger8b1bd822017-08-11 16:11:42 -0400126 build_config['profile']))
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500127 else:
128 options.managed_chrome = build_config['sync_chrome']
David James2333c182013-02-13 16:16:15 -0800129
130 if options.managed_chrome:
131 # Tell Chrome to fetch the source locally.
Matt Tennant628ffdd2013-11-27 14:44:39 -0800132 internal = constants.USE_CHROME_INTERNAL in build_config['useflags']
David James2333c182013-02-13 16:16:15 -0800133 chrome_src = 'chrome-src-internal' if internal else 'chrome-src'
YH Linb1ea83c2016-10-13 15:47:09 -0700134 target_name = 'target'
135 if options.branch:
136 # Tie the cache per branch
137 target_name = 'target-%s' % options.branch
138 options.chrome_root = os.path.join(options.cache_dir, 'distfiles',
139 target_name, chrome_src)
140 # Create directory if in need
141 osutils.SafeMakedirsNonRoot(options.chrome_root)
David James2333c182013-02-13 16:16:15 -0800142
Matt Tennant95a42ad2013-12-27 15:38:36 -0800143 # We are done munging options values, so freeze options object now to avoid
144 # further abuse of it.
145 # TODO(mtennant): one by one identify each options value override and see if
146 # it can be handled another way. Try to push this freeze closer and closer
147 # to the start of the script (e.g. in or after _PostParseCheck).
148 options.Freeze()
149
Don Garrett5ba2c452018-01-30 16:34:41 -0800150 metadata_dump_dict = {
151 # A detected default has been set before now if it wasn't explicit.
152 'branch': options.branch,
153 }
154 if options.metadata_dump:
155 with open(options.metadata_dump, 'r') as metadata_file:
156 metadata_dump_dict = json.loads(metadata_file.read())
157
Matt Tennant0940c382014-01-21 20:43:55 -0800158 with parallel.Manager() as manager:
Don Garretta52a5b02015-06-02 14:52:57 -0700159 builder_run = cbuildbot_run.BuilderRun(
160 options, site_config, build_config, manager)
Dhanya Ganesh39a48a82018-12-06 16:01:11 -0700161 buildstore = BuildStore()
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700162 if metadata_dump_dict:
163 builder_run.attrs.metadata.UpdateWithDict(metadata_dump_dict)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500164
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500165 if builder_run.config.builder_class_name is None:
Don Garrett56e6ed32015-06-23 16:52:20 -0700166 # TODO: This should get relocated to chromeos_config.
Mike Frysingere4d68c22015-02-04 21:26:24 -0500167 if _IsDistributedBuilder(options, chrome_rev, build_config):
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500168 builder_cls_name = 'simple_builders.DistributedBuilder'
Mike Frysingere4d68c22015-02-04 21:26:24 -0500169 else:
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500170 builder_cls_name = 'simple_builders.SimpleBuilder'
171 builder_cls = builders.GetBuilderClass(builder_cls_name)
Dhanya Ganesh39a48a82018-12-06 16:01:11 -0700172 builder = builder_cls(builder_run, buildstore)
Matt Tennant0940c382014-01-21 20:43:55 -0800173 else:
Dhanya Ganesh39a48a82018-12-06 16:01:11 -0700174 builder = builders.Builder(builder_run, buildstore)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500175
Matt Tennant0940c382014-01-21 20:43:55 -0800176 if not builder.Run():
177 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800178
179
Brian Harring3fec5a82012-03-01 05:57:03 -0800180def _CheckChromeVersionOption(_option, _opt_str, value, parser):
181 """Upgrade other options based on chrome_version being passed."""
182 value = value.strip()
183
184 if parser.values.chrome_rev is None and value:
185 parser.values.chrome_rev = constants.CHROME_REV_SPEC
186
187 parser.values.chrome_version = value
188
189
190def _CheckChromeRootOption(_option, _opt_str, value, parser):
191 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800192 if parser.values.chrome_rev is None:
193 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
194
Ryan Cui5ba7e152012-05-10 14:36:52 -0700195 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800196
197
David Jamesac8c2a72013-02-13 18:44:33 -0800198def FindCacheDir(_parser, _options):
Brian Harringae0a5322012-09-15 01:46:51 -0700199 return None
200
201
Ryan Cui5ba7e152012-05-10 14:36:52 -0700202class CustomGroup(optparse.OptionGroup):
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800203 """Custom option group which supports arguments passed-through to trybot."""
David Jameseecba232014-06-11 11:35:11 -0700204
Ryan Cui5ba7e152012-05-10 14:36:52 -0700205 def add_remote_option(self, *args, **kwargs):
206 """For arguments that are passed-through to remote trybot."""
207 return optparse.OptionGroup.add_option(self, *args,
208 remote_pass_through=True,
209 **kwargs)
210
211
Ryan Cui1c13a252012-10-16 15:00:16 -0700212class CustomOption(commandline.FilteringOption):
213 """Subclass FilteringOption class to implement pass-through and api."""
Ryan Cui5ba7e152012-05-10 14:36:52 -0700214
Ryan Cui5ba7e152012-05-10 14:36:52 -0700215 def __init__(self, *args, **kwargs):
216 # The remote_pass_through argument specifies whether we should directly
217 # pass the argument (with its value) onto the remote trybot.
218 self.pass_through = kwargs.pop('remote_pass_through', False)
Ryan Cui1c13a252012-10-16 15:00:16 -0700219 self.api_version = int(kwargs.pop('api', '0'))
220 commandline.FilteringOption.__init__(self, *args, **kwargs)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700221
Ryan Cui5ba7e152012-05-10 14:36:52 -0700222
Ryan Cui1c13a252012-10-16 15:00:16 -0700223class CustomParser(commandline.FilteringParser):
Gregory Meinke5a25ac72019-01-31 13:20:51 -0700224 """Custom option parser which supports arguments passed-through to trybot"""
Matt Tennante8179042013-10-01 15:47:32 -0700225
Brian Harringb6cf9142012-09-01 20:43:17 -0700226 DEFAULT_OPTION_CLASS = CustomOption
227
228 def add_remote_option(self, *args, **kwargs):
229 """For arguments that are passed-through to remote trybot."""
Ryan Cui1c13a252012-10-16 15:00:16 -0700230 return self.add_option(*args, remote_pass_through=True, **kwargs)
Brian Harringb6cf9142012-09-01 20:43:17 -0700231
232
Don Garrett86881cb2017-02-15 15:41:55 -0800233def CreateParser():
234 """Expose _CreateParser publicly."""
235 # Name _CreateParser is needed for commandline library.
236 return _CreateParser()
237
238
Brian Harring3fec5a82012-03-01 05:57:03 -0800239def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700240 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800241 # Parse options
David Jameseecba232014-06-11 11:35:11 -0700242 usage = 'usage: %prog [options] buildbot_config [buildbot_config ...]'
Brian Harringae0a5322012-09-15 01:46:51 -0700243 parser = CustomParser(usage=usage, caching=FindCacheDir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800244
245 # Main options
Ryan Cuie1e4e662012-05-21 16:39:46 -0700246 parser.add_remote_option('-b', '--branch',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900247 help='The manifest branch to test. The branch to '
248 'check the buildroot out to.')
249 parser.add_option('-r', '--buildroot', type='path', dest='buildroot',
250 help='Root directory where source is checked out to, and '
251 'where the build occurs. For external build configs, '
252 "defaults to 'trybot' directory at top level of your "
253 'repo-managed checkout.')
Don Garrett10210fa2018-06-29 18:25:41 -0700254 parser.add_option('--workspace', type='path',
255 api=constants.REEXEC_API_WORKSPACE,
256 help='Root directory for a secondary checkout .')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900257 parser.add_option('--bootstrap-dir', type='path',
Prathmesh Prabhu867c1172015-06-02 17:57:59 -0700258 help='Bootstrapping cbuildbot may involve checking out '
259 'multiple copies of chromite. All these checkouts '
260 'will be contained in the directory specified here. '
261 'Default:%s' % osutils.GetGlobalTempDir())
Hidehiko Abe863d7882017-03-09 22:27:28 +0900262 parser.add_remote_option('--android_rev', type='choice',
David Riley486b2612016-02-22 19:59:26 -0800263 choices=constants.VALID_ANDROID_REVISIONS,
264 help=('Revision of Android to use, of type [%s]'
265 % '|'.join(constants.VALID_ANDROID_REVISIONS)))
Hidehiko Abe863d7882017-03-09 22:27:28 +0900266 parser.add_remote_option('--chrome_rev', type='choice',
David Riley486b2612016-02-22 19:59:26 -0800267 choices=constants.VALID_CHROME_REVISIONS,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700268 help=('Revision of Chrome to use, of type [%s]'
269 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Hidehiko Abe863d7882017-03-09 22:27:28 +0900270 parser.add_remote_option('--profile',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700271 help='Name of profile to sub-specify board variant.')
Hidehiko Abe95d7cf62017-03-07 23:34:30 +0900272 # TODO(crbug.com/279618): Running GOMA is under development. Following
273 # flags are added for development purpose due to repository dependency,
274 # but not officially supported yet.
275 parser.add_option('--goma_dir', type='path',
276 api=constants.REEXEC_API_GOMA,
277 help='Specify a directory containing goma. When this is '
278 'set, GOMA is used to build Chrome.')
279 parser.add_option('--goma_client_json', type='path',
280 api=constants.REEXEC_API_GOMA,
281 help='Specify a service-account-goma-client.json path. '
282 'The file is needed on bots to run GOMA.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800283
Don Garrett211df8c2017-09-06 13:33:02 -0700284 group = CustomGroup(
285 parser,
286 'Deprecated Options')
287
288 parser.add_option('--local', action='store_true', default=False,
Don Garrettcc0ee522017-09-13 14:28:42 -0700289 help='Deprecated. See cros tryjob.')
Don Garrett211df8c2017-09-06 13:33:02 -0700290 parser.add_option('--remote', action='store_true', default=False,
Don Garrettcc0ee522017-09-13 14:28:42 -0700291 help='Deprecated. See cros tryjob.')
Don Garrett211df8c2017-09-06 13:33:02 -0700292
Ryan Cuif4f84be2012-07-09 18:50:41 -0700293 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400294 # Patch selection options.
295 #
296
297 group = CustomGroup(
298 parser,
299 'Patch Options')
300
Mike Frysingerdad205d2017-08-11 16:00:14 -0400301 group.add_remote_option('-g', '--gerrit-patches', action='split_extend',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900302 type='string', default=[],
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400303 metavar="'Id1 *int_Id2...IdN'",
Hidehiko Abe863d7882017-03-09 22:27:28 +0900304 help='Space-separated list of short-form Gerrit '
305 "Change-Id's or change numbers to patch. "
306 "Please prepend '*' to internal Change-Id's")
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400307
Mike Frysinger68893242017-08-11 14:16:39 -0400308 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400309
310 #
311 # Remote trybot options.
312 #
313
314 group = CustomGroup(
315 parser,
Don Garrett211df8c2017-09-06 13:33:02 -0700316 'Options used to configure tryjob behavior.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900317 group.add_remote_option('--hwtest', action='store_true', default=False,
David Jameseecba232014-06-11 11:35:11 -0700318 help='Run the HWTest stage (tests on real hardware)')
Mike Frysingerdad205d2017-08-11 16:00:14 -0400319 group.add_remote_option('--channel', action='split_extend', dest='channels',
Don Garrett4bb21682014-03-03 16:16:23 -0800320 default=[],
Hidehiko Abe863d7882017-03-09 22:27:28 +0900321 help='Specify a channel for a payloads trybot. Can '
322 'be specified multiple times. No valid for '
323 'non-payloads configs.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400324
Mike Frysinger68893242017-08-11 14:16:39 -0400325 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400326
327 #
Ryan Cui88b901c2013-06-21 11:35:30 -0700328 # Branch creation options.
329 #
330
331 group = CustomGroup(
332 parser,
333 'Branch Creation Options (used with branch-util)')
334
335 group.add_remote_option('--branch-name',
336 help='The branch to create or delete.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900337 group.add_remote_option('--delete-branch', action='store_true', default=False,
Ryan Cui88b901c2013-06-21 11:35:30 -0700338 help='Delete the branch specified in --branch-name.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900339 group.add_remote_option('--rename-to',
Ryan Cui88b901c2013-06-21 11:35:30 -0700340 help='Rename a branch to the specified name.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900341 group.add_remote_option('--force-create', action='store_true', default=False,
Ryan Cui88b901c2013-06-21 11:35:30 -0700342 help='Overwrites an existing branch.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900343 group.add_remote_option('--skip-remote-push', action='store_true',
344 default=False,
Prathmesh Prabhue5f4d472015-05-07 16:52:10 -0700345 help='Do not actually push to remote git repos. '
346 'Used for end-to-end testing branching.')
Ryan Cui88b901c2013-06-21 11:35:30 -0700347
Mike Frysinger68893242017-08-11 14:16:39 -0400348 parser.add_argument_group(group)
Ryan Cui88b901c2013-06-21 11:35:30 -0700349
350 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400351 # Advanced options.
Ryan Cuif4f84be2012-07-09 18:50:41 -0700352 #
353
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700354 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800355 parser,
356 'Advanced Options',
357 'Caution: use these options at your own risk.')
358
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400359 group.add_remote_option('--bootstrap-args', action='append', default=[],
Hidehiko Abe863d7882017-03-09 22:27:28 +0900360 help='Args passed directly to the bootstrap re-exec '
361 'to skip verification by the bootstrap code')
362 group.add_remote_option('--buildbot', action='store_true', dest='buildbot',
Bernie Thompson63f30062016-12-21 15:24:25 -0800363 default=False,
364 help='This is running on a buildbot. '
365 'This can be used to make a build operate '
366 'like an official builder, e.g. generate '
367 'new version numbers and archive official '
368 'artifacts and such. This should only be '
369 'used if you are confident in what you are '
370 'doing, as it will make automated commits.')
Don Garrett07d46262017-04-13 12:06:44 -0700371 parser.add_remote_option('--repo-cache', type='path', dest='_repo_cache',
372 help='Present for backwards compatibility, ignored.')
Prathmesh Prabhu51d774f2015-07-17 15:11:49 -0700373 group.add_remote_option('--no-buildbot-tags', action='store_false',
374 dest='enable_buildbot_tags', default=True,
375 help='Suppress buildbot specific tags from log '
376 'output. This is used to hide recursive '
377 'cbuilbot runs on the waterfall.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900378 group.add_remote_option('--buildnumber', type='int', default=0,
379 help='build number')
380 group.add_option('--chrome_root', action='callback', type='path',
381 callback=_CheckChromeRootOption,
382 help='Local checkout of Chrome to use.')
383 group.add_remote_option('--chrome_version', action='callback', type='string',
384 dest='chrome_version',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700385 callback=_CheckChromeVersionOption,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900386 help='Used with SPEC logic to force a particular '
387 'git revision of chrome rather than the '
388 'latest.')
389 group.add_remote_option('--clobber', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700390 help='Clears an old checkout before syncing')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400391 group.add_remote_option('--latest-toolchain', action='store_true',
392 default=False,
393 help='Use the latest toolchain.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700394 parser.add_option('--log_dir', dest='log_dir', type='path',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900395 help='Directory where logs are stored.')
396 group.add_remote_option('--maxarchives', type='int',
397 dest='max_archive_builds', default=3,
David Jameseecba232014-06-11 11:35:11 -0700398 help='Change the local saved build count limit.')
Ryan Cuibbd3d4b2012-08-17 12:20:37 -0700399 parser.add_remote_option('--manifest-repo-url',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900400 help='Overrides the default manifest repo url.')
David James565bc9a2013-04-08 14:54:45 -0700401 group.add_remote_option('--compilecheck', action='store_true', default=False,
402 help='Only verify compilation and unit tests.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700403 group.add_remote_option('--noarchive', action='store_false', dest='archive',
404 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700405 group.add_remote_option('--nobootstrap', action='store_false',
406 dest='bootstrap', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900407 help="Don't checkout and run from a standalone "
408 'chromite repo.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700409 group.add_remote_option('--nobuild', action='store_false', dest='build',
410 default=True,
411 help="Don't actually build (for cbuildbot dev)")
412 group.add_remote_option('--noclean', action='store_false', dest='clean',
413 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700414 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
415 default=True,
416 help='Disable cbuildbots usage of cgroups.')
Ryan Cui3ea98e02013-08-07 16:01:48 -0700417 group.add_remote_option('--nochromesdk', action='store_false',
418 dest='chrome_sdk', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900419 help="Don't run the ChromeSDK stage which builds "
420 'Chrome outside of the chroot.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700421 group.add_remote_option('--noprebuilts', action='store_false',
422 dest='prebuilts', default=True,
423 help="Don't upload prebuilts.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700424 group.add_remote_option('--nopatch', action='store_false',
425 dest='postsync_patch', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900426 help="Don't run PatchChanges stage. This does not "
427 'disable patching in of chromite patches '
428 'during BootstrapStage.')
Don Garrett82c0ae82014-02-03 18:25:11 -0800429 group.add_remote_option('--nopaygen', action='store_false',
430 dest='paygen', default=True,
431 help="Don't generate payloads.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700432 group.add_remote_option('--noreexec', action='store_false',
433 dest='postsync_reexec', default=True,
434 help="Don't reexec into the buildroot after syncing.")
Hidehiko Abe863d7882017-03-09 22:27:28 +0900435 group.add_remote_option('--nosdk', action='store_true', default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400436 help='Re-create the SDK from scratch.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700437 group.add_remote_option('--nosync', action='store_false', dest='sync',
438 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700439 group.add_remote_option('--notests', action='store_false', dest='tests',
440 default=True,
xixuan7774ba82017-06-22 16:04:00 -0700441 help='Override values from buildconfig, run no '
442 'tests, and build no autotest and artifacts.')
443 group.add_remote_option('--novmtests', action='store_false', dest='vmtests',
444 default=True,
445 help='Override values from buildconfig, run no '
446 'vmtests.')
Nam T. Nguyenc93f1342014-07-11 14:40:54 -0700447 group.add_remote_option('--noimagetests', action='store_false',
448 dest='image_test', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900449 help='Override values from buildconfig and run no '
450 'image tests.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700451 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
452 default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900453 help='Override values from buildconfig and never '
454 'uprev.')
455 group.add_option('--reference-repo',
456 help='Reuse git data stored in an existing repo '
457 'checkout. This can drastically reduce the network '
458 'time spent setting up the trybot checkout. By '
459 "default, if this option isn't given but cbuildbot "
460 'is invoked from a repo checkout, cbuildbot will '
461 'use the repo root.')
Ryan Cuicedd8a52012-03-22 02:28:35 -0700462 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700463 help='Skip stages already successfully completed.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900464 group.add_remote_option('--timeout', type='int', default=0,
465 help='Specify the maximum amount of time this job '
466 'can run for, at which point the build will be '
467 'aborted. If set to zero, then there is no '
468 'timeout.')
469 group.add_remote_option('--version', dest='force_version',
470 help='Used with manifest logic. Forces use of this '
471 'version rather than create or get latest. '
472 'Examples: 4815.0.0-rc1, 4815.1.2')
473 group.add_remote_option('--git-cache-dir', type='path',
Don Garrettbb79be92016-09-27 11:14:07 -0700474 api=constants.REEXEC_API_GIT_CACHE_DIR,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900475 help='Specify the cache directory to store the '
476 'project caches populated by the git-cache '
477 'tool. Bootstrap the projects based on the git '
478 'cache files instead of fetching them directly '
479 'from the GoB servers.')
Ningning Xia9ab36022017-07-28 16:49:25 -0700480 group.add_remote_option('--sanity-check-build', action='store_true',
481 default=False, dest='sanity_check_build',
482 api=constants.REEXEC_API_SANITY_CHECK_BUILD,
483 help='Run the build as a sanity check build.')
Don Garretta90f0142018-02-28 14:25:19 -0800484 group.add_remote_option('--debug-cidb', action='store_true', default=False,
485 help='Force Debug CIDB to be used.')
Gregory Meinke5a25ac72019-01-31 13:20:51 -0700486 # cbuildbot ChromeOS Findit options
487 group.add_remote_option('--cbb_build_packages', action='split_extend',
488 dest='cbb_build_packages',
489 default=[],
490 help='Specify an explicit list of packages to build '
491 'for integration with Findit.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400492
Mike Frysinger68893242017-08-11 14:16:39 -0400493 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400494
495 #
496 # Internal options.
497 #
498
499 group = CustomGroup(
500 parser,
Mike Frysinger34db8692013-11-11 14:54:08 -0500501 'Internal Chromium OS Build Team Options',
502 'Caution: these are for meant for the Chromium OS build team only')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400503
504 group.add_remote_option('--archive-base', type='gs_path',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900505 help='Base GS URL (gs://<bucket_name>/<path>) to '
506 'upload archive artifacts to')
David Jameseecba232014-06-11 11:35:11 -0700507 group.add_remote_option(
Hidehiko Abe863d7882017-03-09 22:27:28 +0900508 '--cq-gerrit-query', dest='cq_gerrit_override',
509 help='If given, this gerrit query will be used to find what patches to '
510 "test, rather than the normal 'CommitQueue>=1 AND Verified=1 AND "
511 "CodeReview=2' query it defaults to. Use with care- note "
512 'additionally this setting only has an effect if the buildbot '
513 "target is a cq target, and we're in buildbot mode.")
514 group.add_option('--pass-through', action='append', type='string',
515 dest='pass_through_args', default=[])
516 group.add_option('--reexec-api-version', action='store_true',
517 dest='output_api_version', default=False,
518 help='Used for handling forwards/backwards compatibility '
519 'with --resume and --bootstrap')
520 group.add_option('--remote-trybot', action='store_true', default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400521 help='Indicates this is running on a remote trybot machine')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900522 group.add_option('--buildbucket-id',
Don Garrettb01a8e62017-12-11 17:47:18 -0800523 api=constants.REEXEC_API_GOMA, # Approximate.
Hidehiko Abe863d7882017-03-09 22:27:28 +0900524 help='The unique ID in buildbucket of current build '
525 'generated by buildbucket.')
Mike Frysingerdad205d2017-08-11 16:00:14 -0400526 group.add_remote_option('--remote-patches', action='split_extend', default=[],
Hidehiko Abe863d7882017-03-09 22:27:28 +0900527 help='Patches uploaded by the trybot client when '
528 'run using the -p option')
Brian Harringf611e6e2012-07-17 18:47:44 -0700529 # Note the default here needs to be hardcoded to 3; that is the last version
530 # that lacked this functionality.
Hidehiko Abe863d7882017-03-09 22:27:28 +0900531 group.add_option('--remote-version', type='int', default=3,
Don Garrettbb965dc2017-09-14 17:24:18 -0700532 help='Deprecated and ignored.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400533 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT)
Paul Hobbs3cbdf332017-07-05 22:55:32 -0700534 group.add_option('--ts-mon-task-num', type='int', default=0,
Don Garrett5cd946b2017-07-20 13:42:20 -0700535 api=constants.REEXEC_API_TSMON_TASK_NUM,
Paul Hobbs3cbdf332017-07-05 22:55:32 -0700536 help='The task number of this process. Defaults to 0. '
537 'This argument is useful for running multiple copies '
538 'of cbuildbot without their metrics colliding.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400539 group.add_remote_option('--test-bootstrap', action='store_true',
540 default=False,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900541 help='Causes cbuildbot to bootstrap itself twice, '
542 'in the sequence A->B->C: A(unpatched) patches '
543 'and bootstraps B; B patches and bootstraps C')
544 group.add_remote_option('--validation_pool',
545 help='Path to a pickled validation pool. Intended '
546 'for use only with the commit queue.')
547 group.add_remote_option('--metadata_dump',
548 help='Path to a json dumped metadata file. This '
549 'will be used as the initial metadata.')
550 group.add_remote_option('--master-build-id', type='int',
Aviv Keshetacf4cfb2014-07-30 12:31:22 -0700551 api=constants.REEXEC_API_MASTER_BUILD_ID,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900552 help='cidb build id of the master build to this '
553 'slave build.')
554 group.add_remote_option('--mock-tree-status',
555 help='Override the tree status value that would be '
556 'returned from the the actual tree. Example '
557 'values: open, closed, throttled. When used '
558 'in conjunction with --debug, the tree status '
559 'will not be ignored as it usually is in a '
560 '--debug run.')
Ningning Xia6c381652017-10-24 16:03:29 -0700561 # TODO(nxia): crbug.com/778838
562 # cbuildbot doesn't use pickle files anymore, remove this.
Hidehiko Abe863d7882017-03-09 22:27:28 +0900563 group.add_remote_option('--mock-slave-status',
564 metavar='MOCK_SLAVE_STATUS_PICKLE_FILE',
565 help='Override the result of the _FetchSlaveStatuses '
566 'method of MasterSlaveSyncCompletionStage, by '
567 'specifying a file with a pickle of the result '
568 'to be returned.')
Benjamin Gordon0443cb82018-04-17 12:38:49 -0600569 group.add_option('--previous-build-state', type='string', default='',
570 api=constants.REEXEC_API_PREVIOUS_BUILD_STATE,
571 help='A base64-encoded BuildSummary object describing the '
572 'previous build run on the same build machine.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400573
Mike Frysinger68893242017-08-11 14:16:39 -0400574 parser.add_argument_group(group)
Ryan Cuif4f84be2012-07-09 18:50:41 -0700575
576 #
Brian Harring3fec5a82012-03-01 05:57:03 -0800577 # Debug options
Ryan Cuif4f84be2012-07-09 18:50:41 -0700578 #
Brian Harringfec89fe2012-09-23 07:30:54 -0700579 # Temporary hack; in place till --dry-run replaces --debug.
Mike Frysinger27e21b72018-07-12 14:20:21 -0400580 # pylint: disable=protected-access
Brian Harring009db502012-10-10 02:21:37 -0700581 group = parser.debug_group
Brian Harringfec89fe2012-09-23 07:30:54 -0700582 debug = [x for x in group.option_list if x._long_opts == ['--debug']][0]
David Jameseecba232014-06-11 11:35:11 -0700583 debug.help += ' Currently functions as --dry-run in addition.'
Brian Harringfec89fe2012-09-23 07:30:54 -0700584 debug.pass_through = True
Brian Harring3fec5a82012-03-01 05:57:03 -0800585 group.add_option('--notee', action='store_false', dest='tee', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900586 help='Disable logging and internal tee process. Primarily '
587 'used for debugging cbuildbot itself.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800588 return parser
589
590
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400591def _FinishParsing(options):
Ryan Cui85867972012-02-23 18:21:49 -0800592 """Perform some parsing tasks that need to take place after optparse.
593
594 This function needs to be easily testable! Keep it free of
595 environment-dependent code. Put more detailed usage validation in
596 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800597
598 Args:
Matt Tennant759e2352013-09-27 15:14:44 -0700599 options: The options object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800600 """
Ryan Cui41023d92012-11-13 19:59:50 -0800601 # Populate options.pass_through_args.
602 accepted, _ = commandline.FilteringParser.FilterArgs(
603 options.parsed_args, lambda x: x.opt_inst.pass_through)
604 options.pass_through_args.extend(accepted)
Brian Harring07039b52012-05-13 17:56:47 -0700605
Don Garrettcc0ee522017-09-13 14:28:42 -0700606 if options.local or options.remote:
607 cros_build_lib.Die('Deprecated usage. Please use cros tryjob instead.')
608
Don Garrett211df8c2017-09-06 13:33:02 -0700609 if not options.buildroot:
610 cros_build_lib.Die('A buildroot is required to build.')
611
Brian Harring3fec5a82012-03-01 05:57:03 -0800612 if options.chrome_root:
613 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700614 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
615 constants.CHROME_REV_LOCAL)
David Jamesa0a664e2013-02-13 09:52:01 -0800616 elif options.chrome_rev == constants.CHROME_REV_LOCAL:
617 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
618 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800619
620 if options.chrome_version:
621 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700622 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
623 constants.CHROME_REV_SPEC)
David Jamesa0a664e2013-02-13 09:52:01 -0800624 elif options.chrome_rev == constants.CHROME_REV_SPEC:
625 cros_build_lib.Die(
626 'Chrome rev must not be %s if chrome_version is not set.'
627 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800628
Don Garrett211df8c2017-09-06 13:33:02 -0700629 patches = bool(options.gerrit_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700630
David James5734ea32012-08-15 20:23:49 -0700631 # When running in release mode, make sure we are running with checked-in code.
632 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
633 # a release image with checked-in code for CrOS packages.
Don Garrett211df8c2017-09-06 13:33:02 -0700634 if options.buildbot and patches and not options.debug:
David James5734ea32012-08-15 20:23:49 -0700635 cros_build_lib.Die(
636 'Cannot provide patches when running with --buildbot!')
637
Ryan Cuiba41ad32012-03-08 17:15:29 -0800638 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700639 cros_build_lib.Die(
640 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800641
Ryan Cui85867972012-02-23 18:21:49 -0800642 # Record whether --debug was set explicitly vs. it was inferred.
Don Garrett211df8c2017-09-06 13:33:02 -0700643 options.debug_forced = options.debug
644 # We force --debug to be set for builds that are not 'official'.
645 options.debug = options.debug or not options.buildbot
Brian Harring3fec5a82012-03-01 05:57:03 -0800646
Don Garrett9f3fb692017-11-14 14:05:22 -0800647 if options.build_config_name in (constants.BRANCH_UTIL_CONFIG,
648 'branch-util-tryjob'):
Ryan Cui88b901c2013-06-21 11:35:30 -0700649 if not options.branch_name:
650 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800651 'Must specify --branch-name with the %s config.',
652 constants.BRANCH_UTIL_CONFIG)
Don Garrette7e08fc2017-10-04 16:50:31 -0700653 if (options.branch and options.branch != 'master' and
654 options.branch != options.branch_name):
Ryan Cui88b901c2013-06-21 11:35:30 -0700655 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800656 'If --branch is specified with the %s config, it must'
657 ' have the same value as --branch-name.',
658 constants.BRANCH_UTIL_CONFIG)
659
660 exclusive_opts = {'--version': options.force_version,
661 '--delete-branch': options.delete_branch,
David Jameseecba232014-06-11 11:35:11 -0700662 '--rename-to': options.rename_to}
Mike Frysingerf904d222018-07-14 00:36:04 -0400663 if sum(1 for x in exclusive_opts.values() if x) != 1:
Matt Tennanta130ea32013-12-19 09:38:39 -0800664 cros_build_lib.Die('When using the %s config, you must'
665 ' specifiy one and only one of the following'
666 ' options: %s.', constants.BRANCH_UTIL_CONFIG,
667 ', '.join(exclusive_opts.keys()))
668
669 # When deleting or renaming a branch, the --branch and --nobootstrap
670 # options are implied.
671 if options.delete_branch or options.rename_to:
672 if not options.branch:
Ralph Nathan03047282015-03-23 11:09:32 -0700673 logging.info('Automatically enabling sync to branch %s for this %s '
674 'flow.', options.branch_name,
675 constants.BRANCH_UTIL_CONFIG)
Matt Tennanta130ea32013-12-19 09:38:39 -0800676 options.branch = options.branch_name
677 if options.bootstrap:
Ralph Nathan03047282015-03-23 11:09:32 -0700678 logging.info('Automatically disabling bootstrap step for this %s flow.',
679 constants.BRANCH_UTIL_CONFIG)
Matt Tennanta130ea32013-12-19 09:38:39 -0800680 options.bootstrap = False
681
Ryan Cui88b901c2013-06-21 11:35:30 -0700682 elif any([options.delete_branch, options.rename_to, options.branch_name]):
683 cros_build_lib.Die(
684 'Cannot specify --delete-branch, --rename-to or --branch-name when not '
685 'running the %s config', constants.BRANCH_UTIL_CONFIG)
686
Brian Harring3fec5a82012-03-01 05:57:03 -0800687
Mike Frysinger27e21b72018-07-12 14:20:21 -0400688# pylint: disable=unused-argument
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400689def _PostParseCheck(parser, options, site_config):
Ryan Cui85867972012-02-23 18:21:49 -0800690 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800691
Ryan Cui85867972012-02-23 18:21:49 -0800692 Args:
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800693 parser: Option parser that was used to parse arguments.
694 options: The options returned by optparse.
Don Garrett4af20982015-05-29 19:02:23 -0700695 site_config: config_lib.SiteConfig containing all config info.
Ryan Cui85867972012-02-23 18:21:49 -0800696 """
Don Garrett0a873e02015-06-30 17:55:10 -0700697
Ryan Cuie1e4e662012-05-21 16:39:46 -0700698 if not options.branch:
David James97d95872012-11-16 15:09:56 -0800699 options.branch = git.GetChromiteTrackingBranch()
Ryan Cuie1e4e662012-05-21 16:39:46 -0700700
David Jamesac8c2a72013-02-13 18:44:33 -0800701 # Because the default cache dir depends on other options, FindCacheDir
702 # always returns None, and we setup the default here.
Brian Harringae0a5322012-09-15 01:46:51 -0700703 if options.cache_dir is None:
704 # Note, options.sourceroot is set regardless of the path
705 # actually existing.
Don Garrett211df8c2017-09-06 13:33:02 -0700706 options.cache_dir = os.path.join(options.buildroot, '.cache')
Brian Harringae0a5322012-09-15 01:46:51 -0700707 options.cache_dir = os.path.abspath(options.cache_dir)
Brian Harring8c1d7b12012-10-04 17:36:32 -0700708 parser.ConfigureCacheDir(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700709
Yu-Ju Hong2c066762013-10-28 14:05:08 -0700710 osutils.SafeMakedirsNonRoot(options.cache_dir)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700711
Matt Tennant763497d2014-01-17 16:45:54 -0800712 # Ensure that all args are legitimate config targets.
Don Garrettf0761152017-10-19 19:38:27 -0700713 if options.build_config_name not in site_config:
714 cros_build_lib.Die('Unkonwn build config: "%s"' % options.build_config_name)
Don Garrett4bb21682014-03-03 16:16:23 -0800715
Don Garrettf0761152017-10-19 19:38:27 -0700716 build_config = site_config[options.build_config_name]
717 is_payloads_build = build_config.build_type == constants.PAYLOADS_TYPE
Don Garrett4af20982015-05-29 19:02:23 -0700718
Don Garrettf0761152017-10-19 19:38:27 -0700719 if options.channels and not is_payloads_build:
720 cros_build_lib.Die('--channel must only be used with a payload config,'
721 ' not target (%s).' % options.build_config_name)
Don Garrett5af1d262014-05-16 15:49:37 -0700722
Don Garrettf0761152017-10-19 19:38:27 -0700723 if not options.channels and is_payloads_build:
724 cros_build_lib.Die('payload configs (%s) require --channel to do anything'
725 ' useful.' % options.build_config_name)
Matt Tennant763497d2014-01-17 16:45:54 -0800726
Don Garrett370839f2017-10-19 18:32:34 -0700727 # If the build config explicitly forces the debug flag, set the debug flag
728 # as if it was set from the command line.
729 if build_config.debug:
730 options.debug = True
731
Don Garrett8bd52562017-11-20 14:16:37 -0800732 if not (config_lib.isTryjobConfig(build_config) or options.buildbot):
Don Garrett02d2f582017-11-08 14:01:24 -0800733 cros_build_lib.Die(
734 'Refusing to run non-tryjob config as a tryjob.\n'
Don Garrett8bd52562017-11-20 14:16:37 -0800735 'Please "repo sync && cros tryjob --list %s" for alternatives.\n'
Don Garrettf6661792017-11-15 13:13:23 -0800736 'See go/cros-explicit-tryjob-build-configs-psa.',
Don Garrett02d2f582017-11-08 14:01:24 -0800737 build_config.name)
738
Don Garrettf0761152017-10-19 19:38:27 -0700739 # The --version option is not compatible with an external target unless the
740 # --buildbot option is specified. More correctly, only "paladin versions"
741 # will work with external targets, and those are only used with --buildbot.
742 # If --buildbot is specified, then user should know what they are doing and
743 # only specify a version that will work. See crbug.com/311648.
744 if (options.force_version and
745 not (options.buildbot or build_config.internal)):
746 cros_build_lib.Die('Cannot specify --version without --buildbot for an'
747 ' external target (%s).' % options.build_config_name)
Matt Tennant763497d2014-01-17 16:45:54 -0800748
Ryan Cui85867972012-02-23 18:21:49 -0800749
Don Garrett597ddff2017-02-17 18:29:37 -0800750def ParseCommandLine(parser, argv):
Ryan Cui85867972012-02-23 18:21:49 -0800751 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800752 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -0700753
Don Garrettf0761152017-10-19 19:38:27 -0700754 # Handle the request for the reexec command line API version number.
Brian Harring37e559b2012-05-22 20:47:32 -0700755 if options.output_api_version:
Mike Frysinger383367e2014-09-16 15:06:17 -0400756 print(constants.REEXEC_API_VERSION)
Brian Harring37e559b2012-05-22 20:47:32 -0700757 sys.exit(0)
758
Don Garrettf0761152017-10-19 19:38:27 -0700759 # Record the configs targeted. Strip out null arguments.
760 build_config_names = [x for x in args if x]
761 if len(build_config_names) != 1:
762 cros_build_lib.Die('Expected exactly one build config. Got: %r',
763 build_config_names)
764 options.build_config_name = build_config_names[-1]
765
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400766 _FinishParsing(options)
767 return options
Ryan Cui85867972012-02-23 18:21:49 -0800768
769
Aviv Keshet420de512015-05-18 14:28:48 -0700770_ENVIRONMENT_PROD = 'prod'
771_ENVIRONMENT_DEBUG = 'debug'
772_ENVIRONMENT_STANDALONE = 'standalone'
773
774
775def _GetRunEnvironment(options, build_config):
776 """Determine whether this is a prod/debug/standalone run."""
Don Garretta90f0142018-02-28 14:25:19 -0800777 if options.debug_cidb:
778 return _ENVIRONMENT_DEBUG
779
Don Garrett63765c42017-11-03 16:54:20 -0700780 # One of these arguments should always be set if running on a real builder.
781 # If we aren't on a real builder, we are standalone.
782 if not options.buildbot and not options.remote_trybot:
Aviv Keshet420de512015-05-18 14:28:48 -0700783 return _ENVIRONMENT_STANDALONE
784
Don Garrett63765c42017-11-03 16:54:20 -0700785 if build_config['debug_cidb']:
786 return _ENVIRONMENT_DEBUG
Aviv Keshet420de512015-05-18 14:28:48 -0700787
Don Garrett63765c42017-11-03 16:54:20 -0700788 return _ENVIRONMENT_PROD
Aviv Keshet420de512015-05-18 14:28:48 -0700789
790
Gabe Blackde694a32015-02-19 15:11:11 -0800791def _SetupConnections(options, build_config):
Aviv Keshet55491242017-07-13 17:04:07 -0700792 """Set up CIDB connections using the appropriate Setup call.
Aviv Keshet2982af52014-08-13 16:07:57 -0700793
794 Args:
795 options: Command line options structure.
Aviv Keshet64133022014-08-25 15:50:52 -0700796 build_config: Config object for this build.
Aviv Keshet2982af52014-08-13 16:07:57 -0700797 """
Aviv Keshet420de512015-05-18 14:28:48 -0700798 # Outline:
799 # 1) Based on options and build_config, decide whether we are a production
800 # run, debug run, or standalone run.
801 # 2) Set up cidb instance accordingly.
802 # 3) Update topology info from cidb, so that any other service set up can use
803 # topology.
804 # 4) Set up any other services.
805 run_type = _GetRunEnvironment(options, build_config)
806
807 if run_type == _ENVIRONMENT_PROD:
808 cidb.CIDBConnectionFactory.SetupProdCidb()
Paul Hobbs3cbdf332017-07-05 22:55:32 -0700809 context = ts_mon_config.SetupTsMonGlobalState(
Ben Pastenec8e4e792018-05-14 20:20:25 +0000810 'cbuildbot', indirect=True, task_num=options.ts_mon_task_num)
Aviv Keshet420de512015-05-18 14:28:48 -0700811 elif run_type == _ENVIRONMENT_DEBUG:
812 cidb.CIDBConnectionFactory.SetupDebugCidb()
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700813 context = ts_mon_config.TrivialContextManager()
Aviv Keshet420de512015-05-18 14:28:48 -0700814 else:
Aviv Keshet62d1a0e2014-08-22 21:16:13 -0700815 cidb.CIDBConnectionFactory.SetupNoCidb()
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700816 context = ts_mon_config.TrivialContextManager()
Aviv Keshet62d1a0e2014-08-22 21:16:13 -0700817
Aviv Keshet420de512015-05-18 14:28:48 -0700818 db = cidb.CIDBConnectionFactory.GetCIDBConnectionForBuilder()
819 topology.FetchTopologyFromCIDB(db)
Aviv Keshet64133022014-08-25 15:50:52 -0700820
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700821 return context
822
Aviv Keshet2982af52014-08-13 16:07:57 -0700823
Dean Liaoe5b0aca2018-01-24 15:27:26 +0800824class _MockMethodWithReturnValue(object):
825 """A method mocker which just returns the specific value."""
826 def __init__(self, return_value):
827 self.return_value = return_value
828
829 def __call__(self, *args, **kwargs):
830 return self.return_value
831
832
833class _ObjectMethodPatcher(object):
834 """A simplified mock.object.patch.
835
836 It is a context manager that patches an object's method with specified
837 return value.
838 """
839 def __init__(self, target, attr, return_value=None):
840 """Constructor.
841
842 Args:
843 target: object to patch.
844 attr: method name of the object to patch.
845 return_value: the return value when calling target.attr
846 """
847 self.target = target
848 self.attr = attr
849 self.return_value = return_value
850 self.original_attr = None
851 self.new_attr = _MockMethodWithReturnValue(self.return_value)
852
853 def __enter__(self):
854 self.original_attr = self.target.__dict__[self.attr]
855 setattr(self.target, self.attr, self.new_attr)
856
857 def __exit__(self, *args):
858 if self.target and self.original_attr:
859 setattr(self.target, self.attr, self.original_attr)
860
861
Matt Tennant759e2352013-09-27 15:14:44 -0700862# TODO(build): This function is too damn long.
Ryan Cui85867972012-02-23 18:21:49 -0800863def main(argv):
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400864 # We get false positives with the options object.
865 # pylint: disable=attribute-defined-outside-init
866
David James59a0a2b2013-03-22 14:04:44 -0700867 # Turn on strict sudo checks.
868 cros_build_lib.STRICT_SUDO = True
869
Ryan Cui85867972012-02-23 18:21:49 -0800870 # Set umask to 022 so files created by buildbot are readable.
Mike Frysinger60ec1012013-10-21 00:11:10 -0400871 os.umask(0o22)
Ryan Cui85867972012-02-23 18:21:49 -0800872
Ryan Cui85867972012-02-23 18:21:49 -0800873 parser = _CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400874 options = ParseCommandLine(parser, argv)
Don Garrett0a873e02015-06-30 17:55:10 -0700875
Don Garrettb85658c2015-06-30 19:07:22 -0700876 # Fetch our site_config now, because we need it to do anything else.
Don Garrettde81cc72015-07-07 13:23:28 -0700877 site_config = config_lib.GetConfig()
Don Garrettb85658c2015-06-30 19:07:22 -0700878
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400879 _PostParseCheck(parser, options, site_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800880
Mike Frysinger8fd67dc2012-12-03 23:51:18 -0500881 cros_build_lib.AssertOutsideChroot()
Zdenek Behan98ec2fb2012-08-31 17:12:18 +0200882
Prathmesh Prabhu51d774f2015-07-17 15:11:49 -0700883 if options.enable_buildbot_tags:
884 logging.EnableBuildbotMarkers()
Matt Tennant759e2352013-09-27 15:14:44 -0700885
Don Garrett0c6e0272017-12-13 17:05:21 -0800886 if (options.buildbot and
887 not options.debug and
888 not options.build_config_name == constants.BRANCH_UTIL_CONFIG and
889 not cros_build_lib.HostIsCIBuilder()):
890 # --buildbot can only be used on a real builder, unless it's debug, or
891 # 'branch-util'.
892 cros_build_lib.Die('This host is not a supported build machine.')
Ningning Xiac691e432016-08-11 14:52:59 -0700893
Matt Tennant759e2352013-09-27 15:14:44 -0700894 # Only one config arg is allowed in this mode, which was confirmed earlier.
Don Garrettf0761152017-10-19 19:38:27 -0700895 build_config = site_config[options.build_config_name]
Brian Harring3fec5a82012-03-01 05:57:03 -0800896
Don Garrettbbd7b552014-05-16 13:15:21 -0700897 # TODO: Re-enable this block when reference_repo support handles this
898 # properly. (see chromium:330775)
899 # if options.reference_repo is None:
900 # repo_path = os.path.join(options.sourceroot, '.repo')
901 # # If we're being run from a repo checkout, reuse the repo's git pool to
902 # # cut down on sync time.
903 # if os.path.exists(repo_path):
904 # options.reference_repo = options.sourceroot
905
906 if options.reference_repo:
David Jamesdac7a912013-11-18 11:14:44 -0800907 if not os.path.exists(options.reference_repo):
908 parser.error('Reference path %s does not exist'
909 % (options.reference_repo,))
910 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
911 parser.error('Reference path %s does not look to be the base of a '
912 'repo checkout; no .repo exists in the root.'
913 % (options.reference_repo,))
914
Brian Harringf11bf682012-05-14 15:53:43 -0700915 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -0800916 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -0700917 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
918 'be used together. Cgroup support is required for '
919 'buildbot/remote-trybot mode.')
Mike Frysingera78a56e2012-11-20 06:02:30 -0500920 if not cgroups.Cgroup.IsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -0700921 parser.error('Option --buildbot/--remote-trybot was given, but this '
922 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800923
David Jamesaad5cc72012-10-26 15:03:13 -0700924 missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
Brian Harring351ce442012-03-09 16:38:14 -0800925 if missing:
David Jameseecba232014-06-11 11:35:11 -0700926 parser.error('Option --buildbot/--remote-trybot requires the following '
Ryan Cuid4a24212012-04-04 18:08:12 -0700927 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -0800928 % (', '.join(missing)))
929
David Jamesdac7a912013-11-18 11:14:44 -0800930 if options.reference_repo:
931 options.reference_repo = os.path.abspath(options.reference_repo)
932
Brian Harring3fec5a82012-03-01 05:57:03 -0800933 # Sanity check of buildroot- specifically that it's not pointing into the
934 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -0800935 if (not repository.IsARepoRoot(options.buildroot) and
David James13a69c92013-05-09 10:37:42 -0700936 git.FindRepoDir(options.buildroot)):
Don Garrett211df8c2017-09-06 13:33:02 -0700937 cros_build_lib.Die(
938 'Configured buildroot %s is a subdir of an existing repo checkout.'
939 % options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800940
Chris Sosab5ea3b42012-10-25 15:25:20 -0700941 if not options.log_dir:
942 options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
943
Brian Harringd166aaf2012-05-14 18:31:53 -0700944 log_file = None
945 if options.tee:
Chris Sosab5ea3b42012-10-25 15:25:20 -0700946 log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
947 osutils.SafeMakedirs(options.log_dir)
Brian Harringd166aaf2012-05-14 18:31:53 -0700948 _BackupPreviousLog(log_file)
949
Brian Harring1b8c4c82012-05-29 23:03:04 -0700950 with cros_build_lib.ContextManagerStack() as stack:
Lann Martin8cc2eab2018-09-05 17:17:57 -0600951 # Preserve chromite; we might be running from there!
952 options.preserve_paths = set(['chromite'])
David Jamescebc7272013-07-17 16:45:05 -0700953 if log_file is not None:
954 # We don't want the critical section to try to clean up the tee process,
955 # so we run Tee (forked off) outside of it. This prevents a deadlock
956 # because the Tee process only exits when its pipe is closed, and the
957 # critical section accidentally holds on to that file handle.
958 stack.Add(tee.Tee, log_file)
959 options.preserve_paths.add(_DEFAULT_LOG_DIR)
960
Brian Harringc2d09d92012-05-13 22:03:15 -0700961 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
962 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -0700963
Brian Harringc2d09d92012-05-13 22:03:15 -0700964 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -0700965 # If we're in resume mode, use our parents tempdir rather than
966 # nesting another layer.
David James4bc13702013-03-26 08:08:04 -0700967 stack.Add(osutils.TempDir, prefix='cbuildbot-tmp', set_global=True)
David Jameseecba232014-06-11 11:35:11 -0700968 logging.debug('Cbuildbot tempdir is %r.', os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -0700969
Brian Harringc2d09d92012-05-13 22:03:15 -0700970 if options.cgroups:
971 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -0800972
Brian Harringc2d09d92012-05-13 22:03:15 -0700973 # Mark everything between EnforcedCleanupSection and here as having to
974 # be rolled back via the contextmanager cleanup handlers. This
975 # ensures that sudo bits cannot outlive cbuildbot, that anything
976 # cgroups would kill gets killed, etc.
David Jamesfb3aac92013-10-16 13:26:52 -0700977 stack.Add(critical_section.ForkWatchdog)
Brian Harringd166aaf2012-05-14 18:31:53 -0700978
Aviv Kesheta0159be2013-12-12 13:56:28 -0800979 if options.mock_tree_status is not None:
Dean Liaoe5b0aca2018-01-24 15:27:26 +0800980 stack.Add(_ObjectMethodPatcher, tree_status, '_GetStatus',
Aviv Kesheta0159be2013-12-12 13:56:28 -0800981 return_value=options.mock_tree_status)
982
Aviv Keshetcf9c2722014-02-25 15:15:10 -0800983 if options.mock_slave_status is not None:
984 with open(options.mock_slave_status, 'r') as f:
Aviv Keshet4e750022014-03-07 16:50:34 -0800985 mock_statuses = pickle.load(f)
986 for key, value in mock_statuses.iteritems():
Ningning Xiaf342b952017-02-15 14:13:33 -0800987 mock_statuses[key] = builder_status_lib.BuilderStatus(**value)
Dean Liaoe5b0aca2018-01-24 15:27:26 +0800988 stack.Add(_ObjectMethodPatcher,
Yu-Ju Hongd0fda382014-05-09 15:28:24 -0700989 completion_stages.MasterSlaveSyncCompletionStage,
990 '_FetchSlaveStatuses',
991 return_value=mock_statuses)
Aviv Keshetcf9c2722014-02-25 15:15:10 -0800992
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700993 stack.Add(_SetupConnections, options, build_config)
Don Garrettb4318362014-10-03 15:49:36 -0700994 retry_stats.SetupStats()
Aviv Keshet2982af52014-08-13 16:07:57 -0700995
Aviv Keshet446f07f2016-03-08 11:32:31 -0800996 timeout_display_message = None
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -0800997 # For master-slave builds: Update slave's timeout using master's published
998 # deadline.
999 if options.buildbot and options.master_build_id is not None:
1000 slave_timeout = None
1001 if cidb.CIDBConnectionFactory.IsCIDBSetup():
1002 cidb_handle = cidb.CIDBConnectionFactory.GetCIDBConnectionForBuilder()
1003 if cidb_handle:
1004 slave_timeout = cidb_handle.GetTimeToDeadline(options.master_build_id)
1005
1006 if slave_timeout is not None:
Prathmesh Prabhue49f2aa2017-04-25 12:02:18 -07001007 # We artificially set a minimum slave_timeout because '0' is handled
1008 # specially, and because we don't want to timeout while trying to set
1009 # things up.
1010 slave_timeout = max(slave_timeout, 20)
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001011 if options.timeout == 0 or slave_timeout < options.timeout:
1012 logging.info('Updating slave build timeout to %d seconds enforced '
Ralph Nathan03047282015-03-23 11:09:32 -07001013 'by the master', slave_timeout)
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001014 options.timeout = slave_timeout
Aviv Keshet84017582016-05-18 16:59:59 -07001015 timeout_display_message = (
1016 'This build has reached the timeout deadline set by the master. '
1017 'Either this stage or a previous one took too long (see stage '
1018 'timing historical summary in ReportStage) or the build failed '
1019 'to start on time.')
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001020 else:
1021 logging.warning('Could not get master deadline for master-slave build. '
1022 'Can not set slave timeout.')
1023
1024 if options.timeout > 0:
Aviv Keshet446f07f2016-03-08 11:32:31 -08001025 stack.Add(timeout_util.FatalTimeout, options.timeout,
1026 timeout_display_message)
Ningning Xiaad483542016-05-24 12:27:21 -07001027 try:
1028 _RunBuildStagesWrapper(options, site_config, build_config)
1029 except failures_lib.ExitEarlyException as ex:
1030 # This build finished successfully. Do not re-raise ExitEarlyException.
1031 logging.info('One stage exited early: %s', ex)