blob: ad1e1a8e9feed90b978665fc549beb46a5bab0db [file] [log] [blame]
Mike Frysingerd6925b52012-07-16 16:11:00 -04001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Brian Harring3fec5a82012-03-01 05:57:03 -08002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Main builder code for Chromium OS.
6
7Used by Chromium OS buildbot configuration for all Chromium OS builds including
8full and pre-flight-queue builds.
9"""
10
Mike Frysinger383367e2014-09-16 15:06:17 -040011from __future__ import print_function
12
Brian Harring3fec5a82012-03-01 05:57:03 -080013import distutils.version
14import glob
Aviv Keshet669eb5e2014-06-23 08:53:01 -070015import json
Mike Frysinger05c5faf2015-02-04 21:46:46 -050016import mock
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 Garrett4af20982015-05-29 19:02:23 -070024from chromite.cbuildbot import config_lib
Don Garrett88b8d782014-05-13 17:30:55 -070025from chromite.cbuildbot import constants
26from chromite.cbuildbot import manifest_version
27from chromite.cbuildbot import remote_try
28from chromite.cbuildbot import repository
29from chromite.cbuildbot import tee
Aviv Keshet420de512015-05-18 14:28:48 -070030from chromite.cbuildbot import topology
Prathmesh Prabhud51d7502014-12-21 01:42:55 -080031from chromite.cbuildbot import tree_status
Don Garrett88b8d782014-05-13 17:30:55 -070032from chromite.cbuildbot import trybot_patch_pool
Don Garrett88b8d782014-05-13 17:30:55 -070033from chromite.cbuildbot.stages import completion_stages
Aviv Keshet2982af52014-08-13 16:07:57 -070034from chromite.lib import cidb
Brian Harringc92a7012012-02-29 10:11:34 -080035from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080036from chromite.lib import cleanup
Brian Harringb6cf9142012-09-01 20:43:17 -070037from chromite.lib import commandline
Brian Harring1b8c4c82012-05-29 23:03:04 -070038from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070039from chromite.lib import cros_logging as logging
David James97d95872012-11-16 15:09:56 -080040from chromite.lib import git
Gabe Blackde694a32015-02-19 15:11:11 -080041from chromite.lib import graphite
Stefan Zagerd49d9ff2014-08-15 21:33:37 -070042from chromite.lib import gob_util
Brian Harringaf019fb2012-05-10 15:06:13 -070043from chromite.lib import osutils
David James6450a0a2012-12-04 07:59:53 -080044from chromite.lib import parallel
Don Garrettb4318362014-10-03 15:49:36 -070045from chromite.lib import retry_stats
Brian Harring3fec5a82012-03-01 05:57:03 -080046from chromite.lib import sudo
David James3432acd2013-11-27 10:02:18 -080047from chromite.lib import timeout_util
Paul Hobbsfcf10342015-12-29 15:52:31 -080048from chromite.lib import ts_mon_config
Brian Harring3fec5a82012-03-01 05:57:03 -080049
Ryan Cuiadd49122012-03-21 22:19:58 -070050
Brian Harring3fec5a82012-03-01 05:57:03 -080051_DEFAULT_LOG_DIR = 'cbuildbot_logs'
52_BUILDBOT_LOG_FILE = 'cbuildbot.log'
53_DEFAULT_EXT_BUILDROOT = 'trybot'
54_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Brian Harring351ce442012-03-09 16:38:14 -080055_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Ryan Cui1c13a252012-10-16 15:00:16 -070056_API_VERSION_ATTR = 'api_version'
Brian Harring3fec5a82012-03-01 05:57:03 -080057
58
Don Garrett4af20982015-05-29 19:02:23 -070059def _PrintValidConfigs(site_config, display_all=False):
Brian Harring3fec5a82012-03-01 05:57:03 -080060 """Print a list of valid buildbot configs.
61
Mike Frysinger02e1e072013-11-10 22:11:34 -050062 Args:
Don Garrett4af20982015-05-29 19:02:23 -070063 site_config: config_lib.SiteConfig containing all config info.
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070064 display_all: Print all configs. Otherwise, prints only configs with
65 trybot_list=True.
Brian Harring3fec5a82012-03-01 05:57:03 -080066 """
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070067 def _GetSortKey(config_name):
Don Garrett4af20982015-05-29 19:02:23 -070068 config_dict = site_config[config_name]
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070069 return (not config_dict['trybot_list'], config_dict['description'],
70 config_name)
71
Brian Harring3fec5a82012-03-01 05:57:03 -080072 COLUMN_WIDTH = 45
Mike Frysinger13b08882015-05-28 04:36:10 -040073 if not display_all:
74 print('Note: This is the common list; for all configs, use --all.')
Mike Frysinger383367e2014-09-16 15:06:17 -040075 print('config'.ljust(COLUMN_WIDTH), 'description')
76 print('------'.ljust(COLUMN_WIDTH), '-----------')
Don Garrett4af20982015-05-29 19:02:23 -070077 config_names = site_config.keys()
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070078 config_names.sort(key=_GetSortKey)
Brian Harring3fec5a82012-03-01 05:57:03 -080079 for name in config_names:
Don Garrett4af20982015-05-29 19:02:23 -070080 if display_all or site_config[name]['trybot_list']:
81 desc = site_config[name].get('description')
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070082 desc = desc if desc else ''
Mike Frysinger383367e2014-09-16 15:06:17 -040083 print(name.ljust(COLUMN_WIDTH), desc)
Brian Harring3fec5a82012-03-01 05:57:03 -080084
85
Brian Harring3fec5a82012-03-01 05:57:03 -080086def _ConfirmBuildRoot(buildroot):
87 """Confirm with user the inferred buildroot, and mark it as confirmed."""
Ralph Nathan446aee92015-03-23 14:44:56 -070088 logging.warning('Using default directory %s as buildroot', buildroot)
Brian Harring521e7242012-11-01 16:57:42 -070089 if not cros_build_lib.BooleanPrompt(default=False):
90 print('Please specify a different buildroot via the --buildroot option.')
Brian Harring3fec5a82012-03-01 05:57:03 -080091 sys.exit(0)
92
93 if not os.path.exists(buildroot):
94 os.mkdir(buildroot)
95
96 repository.CreateTrybotMarker(buildroot)
97
98
Ryan Cuieaa9efd2012-04-25 17:56:45 -070099def _ConfirmRemoteBuildbotRun():
100 """Confirm user wants to run with --buildbot --remote."""
Ralph Nathan446aee92015-03-23 14:44:56 -0700101 logging.warning(
David Jameseecba232014-06-11 11:35:11 -0700102 'You are about to launch a PRODUCTION job! This is *NOT* a '
103 'trybot run! Are you sure?')
Brian Harring521e7242012-11-01 16:57:42 -0700104 if not cros_build_lib.BooleanPrompt(default=False):
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700105 print('Please specify --pass-through="--debug".')
106 sys.exit(0)
107
108
Ryan Cui5ba7e152012-05-10 14:36:52 -0700109def _DetermineDefaultBuildRoot(sourceroot, internal_build):
Brian Harring3fec5a82012-03-01 05:57:03 -0800110 """Default buildroot to be under the directory that contains current checkout.
111
Mike Frysinger02e1e072013-11-10 22:11:34 -0500112 Args:
Brian Harring3fec5a82012-03-01 05:57:03 -0800113 internal_build: Whether the build is an internal build
Ryan Cui5ba7e152012-05-10 14:36:52 -0700114 sourceroot: Use specified sourceroot.
Brian Harring3fec5a82012-03-01 05:57:03 -0800115 """
Ryan Cui5ba7e152012-05-10 14:36:52 -0700116 if not repository.IsARepoRoot(sourceroot):
Brian Harring1b8c4c82012-05-29 23:03:04 -0700117 cros_build_lib.Die(
118 'Could not find root of local checkout at %s. Please specify '
119 'using the --sourceroot option.' % sourceroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800120
121 # Place trybot buildroot under the directory containing current checkout.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700122 top_level = os.path.dirname(os.path.realpath(sourceroot))
Brian Harring3fec5a82012-03-01 05:57:03 -0800123 if internal_build:
124 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
125 else:
126 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
127
128 return buildroot
129
130
131def _BackupPreviousLog(log_file, backup_limit=25):
132 """Rename previous log.
133
134 Args:
135 log_file: The absolute path to the previous log.
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800136 backup_limit: Maximum number of old logs to keep.
Brian Harring3fec5a82012-03-01 05:57:03 -0800137 """
138 if os.path.exists(log_file):
139 old_logs = sorted(glob.glob(log_file + '.*'),
140 key=distutils.version.LooseVersion)
141
142 if len(old_logs) >= backup_limit:
143 os.remove(old_logs[0])
144
145 last = 0
146 if old_logs:
147 last = int(old_logs.pop().rpartition('.')[2])
148
149 os.rename(log_file, log_file + '.' + str(last + 1))
150
Ryan Cui5616a512012-08-17 13:39:36 -0700151
Gaurav Shah298aa372014-01-31 09:27:24 -0800152def _IsDistributedBuilder(options, chrome_rev, build_config):
153 """Determines whether the builder should be a DistributedBuilder.
154
155 Args:
156 options: options passed on the commandline.
157 chrome_rev: Chrome revision to build.
158 build_config: Builder configuration dictionary.
159
160 Returns:
161 True if the builder should be a distributed_builder
162 """
Don Garrett0bc85672015-07-23 19:46:00 +0000163 if build_config['pre_cq']:
Gaurav Shah298aa372014-01-31 09:27:24 -0800164 return True
165 elif not options.buildbot:
166 return False
167 elif chrome_rev in (constants.CHROME_REV_TOT,
168 constants.CHROME_REV_LOCAL,
169 constants.CHROME_REV_SPEC):
170 # We don't do distributed logic to TOT Chrome PFQ's, nor local
171 # chrome roots (e.g. chrome try bots)
172 # TODO(davidjames): Update any builders that rely on this logic to use
173 # manifest_version=False instead.
174 return False
175 elif build_config['manifest_version']:
176 return True
177
178 return False
179
180
Don Garretta52a5b02015-06-02 14:52:57 -0700181def _RunBuildStagesWrapper(options, site_config, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800182 """Helper function that wraps RunBuildStages()."""
Ralph Nathan03047282015-03-23 11:09:32 -0700183 logging.info('cbuildbot was executed with args %s' %
184 cros_build_lib.CmdToStr(sys.argv))
Brian Harring3fec5a82012-03-01 05:57:03 -0800185
David Jamesa0a664e2013-02-13 09:52:01 -0800186 chrome_rev = build_config['chrome_rev']
187 if options.chrome_rev:
188 chrome_rev = options.chrome_rev
189 if chrome_rev == constants.CHROME_REV_TOT:
Stefan Zagerd49d9ff2014-08-15 21:33:37 -0700190 options.chrome_version = gob_util.GetTipOfTrunkRevision(
191 constants.CHROMIUM_GOB_URL)
David Jamesa0a664e2013-02-13 09:52:01 -0800192 options.chrome_rev = constants.CHROME_REV_SPEC
193
David James4a404a52013-02-19 13:07:59 -0800194 # If it's likely we'll need to build Chrome, fetch the source.
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500195 if build_config['sync_chrome'] is None:
David Jameseecba232014-06-11 11:35:11 -0700196 options.managed_chrome = (
197 chrome_rev != constants.CHROME_REV_LOCAL and
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500198 (not build_config['usepkg_build_packages'] or chrome_rev or
David James3cce4642013-05-10 17:50:23 -0700199 build_config['profile'] or options.rietveld_patches))
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500200 else:
201 options.managed_chrome = build_config['sync_chrome']
David James2333c182013-02-13 16:16:15 -0800202
203 if options.managed_chrome:
204 # Tell Chrome to fetch the source locally.
Matt Tennant628ffdd2013-11-27 14:44:39 -0800205 internal = constants.USE_CHROME_INTERNAL in build_config['useflags']
David James2333c182013-02-13 16:16:15 -0800206 chrome_src = 'chrome-src-internal' if internal else 'chrome-src'
207 options.chrome_root = os.path.join(options.cache_dir, 'distfiles', 'target',
208 chrome_src)
David James9e27e662013-02-14 13:42:43 -0800209 elif options.rietveld_patches:
David James4a404a52013-02-19 13:07:59 -0800210 cros_build_lib.Die('This builder does not support Rietveld patches.')
David James2333c182013-02-13 16:16:15 -0800211
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700212 metadata_dump_dict = {}
213 if options.metadata_dump:
214 with open(options.metadata_dump, 'r') as metadata_file:
215 metadata_dump_dict = json.loads(metadata_file.read())
216
Matt Tennant95a42ad2013-12-27 15:38:36 -0800217 # We are done munging options values, so freeze options object now to avoid
218 # further abuse of it.
219 # TODO(mtennant): one by one identify each options value override and see if
220 # it can be handled another way. Try to push this freeze closer and closer
221 # to the start of the script (e.g. in or after _PostParseCheck).
222 options.Freeze()
223
Matt Tennant0940c382014-01-21 20:43:55 -0800224 with parallel.Manager() as manager:
Don Garretta52a5b02015-06-02 14:52:57 -0700225 builder_run = cbuildbot_run.BuilderRun(
226 options, site_config, build_config, manager)
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700227 if metadata_dump_dict:
228 builder_run.attrs.metadata.UpdateWithDict(metadata_dump_dict)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500229
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500230 if builder_run.config.builder_class_name is None:
Don Garrett56e6ed32015-06-23 16:52:20 -0700231 # TODO: This should get relocated to chromeos_config.
Mike Frysingere4d68c22015-02-04 21:26:24 -0500232 if _IsDistributedBuilder(options, chrome_rev, build_config):
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500233 builder_cls_name = 'simple_builders.DistributedBuilder'
Mike Frysingere4d68c22015-02-04 21:26:24 -0500234 else:
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500235 builder_cls_name = 'simple_builders.SimpleBuilder'
236 builder_cls = builders.GetBuilderClass(builder_cls_name)
237 builder = builder_cls(builder_run)
Matt Tennant0940c382014-01-21 20:43:55 -0800238 else:
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500239 builder = builders.Builder(builder_run)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500240
Matt Tennant0940c382014-01-21 20:43:55 -0800241 if not builder.Run():
242 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800243
244
245# Parser related functions
Ryan Cui5ba7e152012-05-10 14:36:52 -0700246def _CheckLocalPatches(sourceroot, local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800247 """Do an early quick check of the passed-in patches.
248
249 If the branch of a project is not specified we append the current branch the
250 project is on.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700251
David Jamese3b06062013-11-09 18:52:02 -0800252 TODO(davidjames): The project:branch format isn't unique, so this means that
253 we can't differentiate what directory the user intended to apply patches to.
254 We should references by directory instead.
255
Ryan Cui5ba7e152012-05-10 14:36:52 -0700256 Args:
257 sourceroot: The checkout where patches are coming from.
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800258 local_patches: List of patches to check in project:branch format.
David Jamese3b06062013-11-09 18:52:02 -0800259
260 Returns:
261 A list of patches that have been verified, in project:branch format.
Brian Harring3fec5a82012-03-01 05:57:03 -0800262 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700263 verified_patches = []
David James97d95872012-11-16 15:09:56 -0800264 manifest = git.ManifestCheckout.Cached(sourceroot)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700265 for patch in local_patches:
David Jamese3b06062013-11-09 18:52:02 -0800266 project, _, branch = patch.partition(':')
267
Gaurav Shah7afb0562013-12-26 15:05:39 -0800268 checkouts = manifest.FindCheckouts(project, only_patchable=True)
David Jamese3b06062013-11-09 18:52:02 -0800269 if not checkouts:
270 cros_build_lib.Die('Project %s does not exist.' % (project,))
271 if len(checkouts) > 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700272 cros_build_lib.Die(
David Jamese3b06062013-11-09 18:52:02 -0800273 'We do not yet support local patching for projects that are checked '
274 'out to multiple directories. Try uploading your patch to gerrit '
275 'and referencing it via the -g option instead.'
276 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800277
David Jamese3b06062013-11-09 18:52:02 -0800278 ok = False
279 for checkout in checkouts:
280 project_dir = checkout.GetPath(absolute=True)
Brian Harring3fec5a82012-03-01 05:57:03 -0800281
David Jamese3b06062013-11-09 18:52:02 -0800282 # If no branch was specified, we use the project's current branch.
Brian Harring3fec5a82012-03-01 05:57:03 -0800283 if not branch:
David Jamese3b06062013-11-09 18:52:02 -0800284 local_branch = git.GetCurrentBranch(project_dir)
285 else:
286 local_branch = branch
Brian Harring3fec5a82012-03-01 05:57:03 -0800287
David Jamesf1a07612014-04-28 17:48:52 -0700288 if local_branch and git.DoesCommitExistInRepo(project_dir, local_branch):
David Jamese3b06062013-11-09 18:52:02 -0800289 verified_patches.append('%s:%s' % (project, local_branch))
290 ok = True
291
292 if not ok:
293 if branch:
294 cros_build_lib.Die('Project %s does not have branch %s'
David Jameseecba232014-06-11 11:35:11 -0700295 % (project, branch))
David Jamese3b06062013-11-09 18:52:02 -0800296 else:
297 cros_build_lib.Die('Project %s is not on a branch!' % (project,))
Brian Harring3fec5a82012-03-01 05:57:03 -0800298
Ryan Cuicedd8a52012-03-22 02:28:35 -0700299 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800300
301
Brian Harring3fec5a82012-03-01 05:57:03 -0800302def _CheckChromeVersionOption(_option, _opt_str, value, parser):
303 """Upgrade other options based on chrome_version being passed."""
304 value = value.strip()
305
306 if parser.values.chrome_rev is None and value:
307 parser.values.chrome_rev = constants.CHROME_REV_SPEC
308
309 parser.values.chrome_version = value
310
311
312def _CheckChromeRootOption(_option, _opt_str, value, parser):
313 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800314 if parser.values.chrome_rev is None:
315 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
316
Ryan Cui5ba7e152012-05-10 14:36:52 -0700317 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800318
319
320def _CheckChromeRevOption(_option, _opt_str, value, parser):
321 """Validate the chrome_rev option."""
322 value = value.strip()
323 if value not in constants.VALID_CHROME_REVISIONS:
324 raise optparse.OptionValueError('Invalid chrome rev specified')
325
326 parser.values.chrome_rev = value
327
328
David Jamesac8c2a72013-02-13 18:44:33 -0800329def FindCacheDir(_parser, _options):
Brian Harringae0a5322012-09-15 01:46:51 -0700330 return None
331
332
Ryan Cui5ba7e152012-05-10 14:36:52 -0700333class CustomGroup(optparse.OptionGroup):
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800334 """Custom option group which supports arguments passed-through to trybot."""
David Jameseecba232014-06-11 11:35:11 -0700335
Ryan Cui5ba7e152012-05-10 14:36:52 -0700336 def add_remote_option(self, *args, **kwargs):
337 """For arguments that are passed-through to remote trybot."""
338 return optparse.OptionGroup.add_option(self, *args,
339 remote_pass_through=True,
340 **kwargs)
341
342
Ryan Cui1c13a252012-10-16 15:00:16 -0700343class CustomOption(commandline.FilteringOption):
344 """Subclass FilteringOption class to implement pass-through and api."""
Ryan Cui5ba7e152012-05-10 14:36:52 -0700345
Ryan Cui1c13a252012-10-16 15:00:16 -0700346 ACTIONS = commandline.FilteringOption.ACTIONS + ('extend',)
347 STORE_ACTIONS = commandline.FilteringOption.STORE_ACTIONS + ('extend',)
348 TYPED_ACTIONS = commandline.FilteringOption.TYPED_ACTIONS + ('extend',)
349 ALWAYS_TYPED_ACTIONS = (commandline.FilteringOption.ALWAYS_TYPED_ACTIONS +
350 ('extend',))
Ryan Cui79319ab2012-05-21 12:59:18 -0700351
Ryan Cui5ba7e152012-05-10 14:36:52 -0700352 def __init__(self, *args, **kwargs):
353 # The remote_pass_through argument specifies whether we should directly
354 # pass the argument (with its value) onto the remote trybot.
355 self.pass_through = kwargs.pop('remote_pass_through', False)
Ryan Cui1c13a252012-10-16 15:00:16 -0700356 self.api_version = int(kwargs.pop('api', '0'))
357 commandline.FilteringOption.__init__(self, *args, **kwargs)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700358
359 def take_action(self, action, dest, opt, value, values, parser):
Ryan Cui79319ab2012-05-21 12:59:18 -0700360 if action == 'extend':
Mike Frysingerd6925b52012-07-16 16:11:00 -0400361 # If there is extra spaces between each argument, we get '' which later
362 # code barfs on, so skip those. e.g. We see this with the forms:
363 # cbuildbot -p 'proj:branch ' ...
364 # cbuildbot -p ' proj:branch' ...
365 # cbuildbot -p 'proj:branch proj2:branch' ...
366 lvalue = value.split()
Ryan Cui79319ab2012-05-21 12:59:18 -0700367 values.ensure_value(dest, []).extend(lvalue)
Ryan Cui79319ab2012-05-21 12:59:18 -0700368
Ryan Cui1c13a252012-10-16 15:00:16 -0700369 commandline.FilteringOption.take_action(
370 self, action, dest, opt, value, values, parser)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700371
372
Ryan Cui1c13a252012-10-16 15:00:16 -0700373class CustomParser(commandline.FilteringParser):
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800374 """Custom option parser which supports arguments passed-trhough to trybot"""
Matt Tennante8179042013-10-01 15:47:32 -0700375
Brian Harringb6cf9142012-09-01 20:43:17 -0700376 DEFAULT_OPTION_CLASS = CustomOption
377
378 def add_remote_option(self, *args, **kwargs):
379 """For arguments that are passed-through to remote trybot."""
Ryan Cui1c13a252012-10-16 15:00:16 -0700380 return self.add_option(*args, remote_pass_through=True, **kwargs)
Brian Harringb6cf9142012-09-01 20:43:17 -0700381
382
Brian Harring3fec5a82012-03-01 05:57:03 -0800383def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700384 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800385 # Parse options
David Jameseecba232014-06-11 11:35:11 -0700386 usage = 'usage: %prog [options] buildbot_config [buildbot_config ...]'
Brian Harringae0a5322012-09-15 01:46:51 -0700387 parser = CustomParser(usage=usage, caching=FindCacheDir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800388
389 # Main options
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400390 parser.add_option('-l', '--list', action='store_true', dest='list',
391 default=False,
392 help='List the suggested trybot configs to use (see --all)')
Brian Harring3fec5a82012-03-01 05:57:03 -0800393 parser.add_option('-a', '--all', action='store_true', dest='print_all',
394 default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400395 help='List all of the buildbot configs available w/--list')
396
397 parser.add_option('--local', default=False, action='store_true',
David Jameseecba232014-06-11 11:35:11 -0700398 help=('Specifies that this tryjob should be run locally. '
399 'Implies --debug.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400400 parser.add_option('--remote', default=False, action='store_true',
Ryan Cui88b901c2013-06-21 11:35:30 -0700401 help='Specifies that this tryjob should be run remotely.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400402
Ryan Cuie1e4e662012-05-21 16:39:46 -0700403 parser.add_remote_option('-b', '--branch',
David Jameseecba232014-06-11 11:35:11 -0700404 help=('The manifest branch to test. The branch to '
405 'check the buildroot out to.'))
Ryan Cui5ba7e152012-05-10 14:36:52 -0700406 parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
David Jameseecba232014-06-11 11:35:11 -0700407 help=('Root directory where source is checked out to, and '
408 'where the build occurs. For external build configs, '
409 "defaults to 'trybot' directory at top level of your "
410 'repo-managed checkout.'))
Prathmesh Prabhu867c1172015-06-02 17:57:59 -0700411 parser.add_option('--bootstrap-dir', type='path', default=None,
412 help='Bootstrapping cbuildbot may involve checking out '
413 'multiple copies of chromite. All these checkouts '
414 'will be contained in the directory specified here. '
415 'Default:%s' % osutils.GetGlobalTempDir())
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700416 parser.add_remote_option('--chrome_rev', default=None, type='string',
417 action='callback', dest='chrome_rev',
418 callback=_CheckChromeRevOption,
419 help=('Revision of Chrome to use, of type [%s]'
420 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700421 parser.add_remote_option('--profile', default=None, type='string',
422 action='store', dest='profile',
423 help='Name of profile to sub-specify board variant.')
Don Garrettb85658c2015-06-30 19:07:22 -0700424 parser.add_option('-c', '--config_repo',
425 help=('Cloneable path to the git repository containing '
426 'the site configuration to use.'))
Brian Harring3fec5a82012-03-01 05:57:03 -0800427
Ryan Cuif4f84be2012-07-09 18:50:41 -0700428 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400429 # Patch selection options.
430 #
431
432 group = CustomGroup(
433 parser,
434 'Patch Options')
435
436 group.add_remote_option('-g', '--gerrit-patches', action='extend',
437 default=[], type='string',
438 metavar="'Id1 *int_Id2...IdN'",
David Jameseecba232014-06-11 11:35:11 -0700439 help=('Space-separated list of short-form Gerrit '
440 "Change-Id's or change numbers to patch. "
441 "Please prepend '*' to internal Change-Id's"))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400442 group.add_remote_option('-G', '--rietveld-patches', action='extend',
443 default=[], type='string',
444 metavar="'id1[:subdir1]...idN[:subdirN]'",
David Jameseecba232014-06-11 11:35:11 -0700445 help=('Space-separated list of short-form Rietveld '
446 'issue numbers to patch. If no subdir is '
447 'specified, the src directory is used.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400448 group.add_option('-p', '--local-patches', action='extend', default=[],
449 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
David Jameseecba232014-06-11 11:35:11 -0700450 help=('Space-separated list of project branches with '
451 'patches to apply. Projects are specified by name. '
452 'If no branch is specified the current branch of the '
453 'project will be used.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400454
455 parser.add_option_group(group)
456
457 #
458 # Remote trybot options.
459 #
460
461 group = CustomGroup(
462 parser,
463 'Remote Trybot Options (--remote)')
464
Paul Hobbs5cd050d2015-06-30 16:52:28 -0700465 group.add_option('--use-buildbucket', default=False, action='store_true',
466 help=('Use buildbucket instead of git to request'
467 'the tryjob(s).'))
468
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400469 group.add_remote_option('--hwtest', dest='hwtest', action='store_true',
David Jameseecba232014-06-11 11:35:11 -0700470 default=False,
471 help='Run the HWTest stage (tests on real hardware)')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400472 group.add_option('--remote-description', default=None,
David Jameseecba232014-06-11 11:35:11 -0700473 help=('Attach an optional description to a --remote run '
474 'to make it easier to identify the results when it '
475 'finishes'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400476 group.add_option('--slaves', action='extend', default=[],
David Jameseecba232014-06-11 11:35:11 -0700477 help=('Specify specific remote tryslaves to run on (e.g. '
478 'build149-m2); if the bot is busy, it will be queued'))
Don Garrett4bb21682014-03-03 16:16:23 -0800479 group.add_remote_option('--channel', dest='channels', action='extend',
480 default=[],
David Jameseecba232014-06-11 11:35:11 -0700481 help=('Specify a channel for a payloads trybot. Can '
482 'be specified multiple times. No valid for '
483 'non-payloads configs.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400484 group.add_option('--test-tryjob', action='store_true',
485 default=False,
David Jameseecba232014-06-11 11:35:11 -0700486 help=('Submit a tryjob to the test repository. Will not '
487 'show up on the production trybot waterfall.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400488
489 parser.add_option_group(group)
490
491 #
Ryan Cui88b901c2013-06-21 11:35:30 -0700492 # Branch creation options.
493 #
494
495 group = CustomGroup(
496 parser,
497 'Branch Creation Options (used with branch-util)')
498
499 group.add_remote_option('--branch-name',
500 help='The branch to create or delete.')
501 group.add_remote_option('--delete-branch', default=False, action='store_true',
502 help='Delete the branch specified in --branch-name.')
503 group.add_remote_option('--rename-to', type='string',
504 help='Rename a branch to the specified name.')
505 group.add_remote_option('--force-create', default=False, action='store_true',
506 help='Overwrites an existing branch.')
Prathmesh Prabhue5f4d472015-05-07 16:52:10 -0700507 group.add_remote_option('--skip-remote-push', default=False,
508 action='store_true',
509 help='Do not actually push to remote git repos. '
510 'Used for end-to-end testing branching.')
Ryan Cui88b901c2013-06-21 11:35:30 -0700511
512 parser.add_option_group(group)
513
514 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400515 # Advanced options.
Ryan Cuif4f84be2012-07-09 18:50:41 -0700516 #
517
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700518 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800519 parser,
520 'Advanced Options',
521 'Caution: use these options at your own risk.')
522
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400523 group.add_remote_option('--bootstrap-args', action='append', default=[],
David Jameseecba232014-06-11 11:35:11 -0700524 help=('Args passed directly to the bootstrap re-exec '
525 'to skip verification by the bootstrap code'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700526 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
527 default=False, help='This is running on a buildbot')
Prathmesh Prabhu51d774f2015-07-17 15:11:49 -0700528 group.add_remote_option('--no-buildbot-tags', action='store_false',
529 dest='enable_buildbot_tags', default=True,
530 help='Suppress buildbot specific tags from log '
531 'output. This is used to hide recursive '
532 'cbuilbot runs on the waterfall.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700533 group.add_remote_option('--buildnumber', help='build number', type='int',
534 default=0)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700535 group.add_option('--chrome_root', default=None, type='path',
536 action='callback', callback=_CheckChromeRootOption,
537 dest='chrome_root', help='Local checkout of Chrome to use.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700538 group.add_remote_option('--chrome_version', default=None, type='string',
539 action='callback', dest='chrome_version',
540 callback=_CheckChromeVersionOption,
David Jameseecba232014-06-11 11:35:11 -0700541 help=('Used with SPEC logic to force a particular '
Stefan Zagerd49d9ff2014-08-15 21:33:37 -0700542 'git revision of chrome rather than the '
David Jameseecba232014-06-11 11:35:11 -0700543 'latest.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700544 group.add_remote_option('--clobber', action='store_true', dest='clobber',
545 default=False,
546 help='Clears an old checkout before syncing')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400547 group.add_remote_option('--latest-toolchain', action='store_true',
548 default=False,
549 help='Use the latest toolchain.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700550 parser.add_option('--log_dir', dest='log_dir', type='path',
Brian Harring3fec5a82012-03-01 05:57:03 -0800551 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700552 group.add_remote_option('--maxarchives', dest='max_archive_builds',
553 default=3, type='int',
David Jameseecba232014-06-11 11:35:11 -0700554 help='Change the local saved build count limit.')
Ryan Cuibbd3d4b2012-08-17 12:20:37 -0700555 parser.add_remote_option('--manifest-repo-url',
556 help=('Overrides the default manifest repo url.'))
David James565bc9a2013-04-08 14:54:45 -0700557 group.add_remote_option('--compilecheck', action='store_true', default=False,
558 help='Only verify compilation and unit tests.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700559 group.add_remote_option('--noarchive', action='store_false', dest='archive',
560 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700561 group.add_remote_option('--nobootstrap', action='store_false',
562 dest='bootstrap', default=True,
David Jameseecba232014-06-11 11:35:11 -0700563 help=("Don't checkout and run from a standalone "
564 'chromite repo.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700565 group.add_remote_option('--nobuild', action='store_false', dest='build',
566 default=True,
567 help="Don't actually build (for cbuildbot dev)")
568 group.add_remote_option('--noclean', action='store_false', dest='clean',
569 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700570 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
571 default=True,
572 help='Disable cbuildbots usage of cgroups.')
Ryan Cui3ea98e02013-08-07 16:01:48 -0700573 group.add_remote_option('--nochromesdk', action='store_false',
574 dest='chrome_sdk', default=True,
David Jameseecba232014-06-11 11:35:11 -0700575 help=("Don't run the ChromeSDK stage which builds "
576 'Chrome outside of the chroot.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700577 group.add_remote_option('--noprebuilts', action='store_false',
578 dest='prebuilts', default=True,
579 help="Don't upload prebuilts.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700580 group.add_remote_option('--nopatch', action='store_false',
581 dest='postsync_patch', default=True,
582 help=("Don't run PatchChanges stage. This does not "
David Jameseecba232014-06-11 11:35:11 -0700583 'disable patching in of chromite patches '
584 'during BootstrapStage.'))
Don Garrett82c0ae82014-02-03 18:25:11 -0800585 group.add_remote_option('--nopaygen', action='store_false',
586 dest='paygen', default=True,
587 help="Don't generate payloads.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700588 group.add_remote_option('--noreexec', action='store_false',
589 dest='postsync_reexec', default=True,
590 help="Don't reexec into the buildroot after syncing.")
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400591 group.add_remote_option('--nosdk', action='store_true',
592 default=False,
593 help='Re-create the SDK from scratch.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700594 group.add_remote_option('--nosync', action='store_false', dest='sync',
595 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700596 group.add_remote_option('--notests', action='store_false', dest='tests',
597 default=True,
David Jameseecba232014-06-11 11:35:11 -0700598 help=('Override values from buildconfig and run no '
599 'tests.'))
Nam T. Nguyenc93f1342014-07-11 14:40:54 -0700600 group.add_remote_option('--noimagetests', action='store_false',
601 dest='image_test', default=True,
602 help=('Override values from buildconfig and run no '
603 'image tests.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700604 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
605 default=True,
David Jameseecba232014-06-11 11:35:11 -0700606 help=('Override values from buildconfig and never '
607 'uprev.'))
David Jamesdac7a912013-11-18 11:14:44 -0800608 group.add_option('--reference-repo', action='store', default=None,
609 dest='reference_repo',
David Jameseecba232014-06-11 11:35:11 -0700610 help=('Reuse git data stored in an existing repo '
611 'checkout. This can drastically reduce the network '
612 'time spent setting up the trybot checkout. By '
613 "default, if this option isn't given but cbuildbot "
614 'is invoked from a repo checkout, cbuildbot will '
615 'use the repo root.'))
Ryan Cuicedd8a52012-03-22 02:28:35 -0700616 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700617 help='Skip stages already successfully completed.')
618 group.add_remote_option('--timeout', action='store', type='int', default=0,
David Jameseecba232014-06-11 11:35:11 -0700619 help=('Specify the maximum amount of time this job '
620 'can run for, at which point the build will be '
621 'aborted. If set to zero, then there is no '
622 'timeout.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700623 group.add_remote_option('--version', dest='force_version', default=None,
David Jameseecba232014-06-11 11:35:11 -0700624 help=('Used with manifest logic. Forces use of this '
625 'version rather than create or get latest. '
626 'Examples: 4815.0.0-rc1, 4815.1.2'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400627
628 parser.add_option_group(group)
629
630 #
631 # Internal options.
632 #
633
634 group = CustomGroup(
635 parser,
Mike Frysinger34db8692013-11-11 14:54:08 -0500636 'Internal Chromium OS Build Team Options',
637 'Caution: these are for meant for the Chromium OS build team only')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400638
639 group.add_remote_option('--archive-base', type='gs_path',
David Jameseecba232014-06-11 11:35:11 -0700640 help=('Base GS URL (gs://<bucket_name>/<path>) to '
641 'upload archive artifacts to'))
642 group.add_remote_option(
643 '--cq-gerrit-query', dest='cq_gerrit_override', default=None,
644 help=('If given, this gerrit query will be used to find what patches to '
645 "test, rather than the normal 'CommitQueue>=1 AND Verified=1 AND "
646 "CodeReview=2' query it defaults to. Use with care- note "
647 'additionally this setting only has an effect if the buildbot '
648 "target is a cq target, and we're in buildbot mode."))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400649 group.add_option('--pass-through', dest='pass_through_args', action='append',
650 type='string', default=[])
651 group.add_option('--reexec-api-version', dest='output_api_version',
Ryan Cuif4f84be2012-07-09 18:50:41 -0700652 action='store_true', default=False,
David Jameseecba232014-06-11 11:35:11 -0700653 help=('Used for handling forwards/backwards compatibility '
654 'with --resume and --bootstrap'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400655 group.add_option('--remote-trybot', dest='remote_trybot',
656 action='store_true', default=False,
657 help='Indicates this is running on a remote trybot machine')
658 group.add_remote_option('--remote-patches', action='extend', default=[],
David Jameseecba232014-06-11 11:35:11 -0700659 help=('Patches uploaded by the trybot client when '
660 'run using the -p option'))
Brian Harringf611e6e2012-07-17 18:47:44 -0700661 # Note the default here needs to be hardcoded to 3; that is the last version
662 # that lacked this functionality.
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400663 group.add_option('--remote-version', default=3, type=int, action='store',
David Jameseecba232014-06-11 11:35:11 -0700664 help=('Used for compatibility checks w/tryjobs running in '
665 'older chromite instances'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400666 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT)
667 group.add_remote_option('--test-bootstrap', action='store_true',
668 default=False,
David Jameseecba232014-06-11 11:35:11 -0700669 help=('Causes cbuildbot to bootstrap itself twice, '
670 'in the sequence A->B->C: A(unpatched) patches '
671 'and bootstraps B; B patches and bootstraps C'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400672 group.add_remote_option('--validation_pool', default=None,
David Jameseecba232014-06-11 11:35:11 -0700673 help=('Path to a pickled validation pool. Intended '
674 'for use only with the commit queue.'))
Aviv Keshet007a24a2014-06-23 08:10:55 -0700675 group.add_remote_option('--metadata_dump', default=None,
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700676 help=('Path to a json dumped metadata file. This '
677 'will be used as the initial metadata.'))
Aviv Keshetacf4cfb2014-07-30 12:31:22 -0700678 group.add_remote_option('--master-build-id', default=None, type=int,
679 api=constants.REEXEC_API_MASTER_BUILD_ID,
680 help=('cidb build id of the master build to this '
681 'slave build.'))
Aviv Kesheta0159be2013-12-12 13:56:28 -0800682 group.add_remote_option('--mock-tree-status', dest='mock_tree_status',
683 default=None, action='store',
David Jameseecba232014-06-11 11:35:11 -0700684 help=('Override the tree status value that would be '
685 'returned from the the actual tree. Example '
686 'values: open, closed, throttled. When used '
687 'in conjunction with --debug, the tree status '
688 'will not be ignored as it usually is in a '
689 '--debug run.'))
690 group.add_remote_option(
691 '--mock-slave-status', dest='mock_slave_status', default=None,
692 action='store', metavar='MOCK_SLAVE_STATUS_PICKLE_FILE',
693 help=('Override the result of the _FetchSlaveStatuses method of '
694 'MasterSlaveSyncCompletionStage, by specifying a file with a '
695 'pickle of the result to be returned.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400696
697 parser.add_option_group(group)
Ryan Cuif4f84be2012-07-09 18:50:41 -0700698
699 #
Brian Harring3fec5a82012-03-01 05:57:03 -0800700 # Debug options
Ryan Cuif4f84be2012-07-09 18:50:41 -0700701 #
Brian Harringfec89fe2012-09-23 07:30:54 -0700702 # Temporary hack; in place till --dry-run replaces --debug.
703 # pylint: disable=W0212
Brian Harring009db502012-10-10 02:21:37 -0700704 group = parser.debug_group
Brian Harringfec89fe2012-09-23 07:30:54 -0700705 debug = [x for x in group.option_list if x._long_opts == ['--debug']][0]
David Jameseecba232014-06-11 11:35:11 -0700706 debug.help += ' Currently functions as --dry-run in addition.'
Brian Harringfec89fe2012-09-23 07:30:54 -0700707 debug.pass_through = True
Brian Harring3fec5a82012-03-01 05:57:03 -0800708 group.add_option('--notee', action='store_false', dest='tee', default=True,
David Jameseecba232014-06-11 11:35:11 -0700709 help=('Disable logging and internal tee process. Primarily '
710 'used for debugging cbuildbot itself.'))
Brian Harring3fec5a82012-03-01 05:57:03 -0800711 return parser
712
713
Ryan Cui85867972012-02-23 18:21:49 -0800714def _FinishParsing(options, args):
715 """Perform some parsing tasks that need to take place after optparse.
716
717 This function needs to be easily testable! Keep it free of
718 environment-dependent code. Put more detailed usage validation in
719 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800720
721 Args:
Matt Tennant759e2352013-09-27 15:14:44 -0700722 options: The options object returned by optparse
723 args: The args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800724 """
Ryan Cui41023d92012-11-13 19:59:50 -0800725 # Populate options.pass_through_args.
726 accepted, _ = commandline.FilteringParser.FilterArgs(
727 options.parsed_args, lambda x: x.opt_inst.pass_through)
728 options.pass_through_args.extend(accepted)
Brian Harring07039b52012-05-13 17:56:47 -0700729
Brian Harring3fec5a82012-03-01 05:57:03 -0800730 if options.chrome_root:
731 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700732 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
733 constants.CHROME_REV_LOCAL)
David Jamesa0a664e2013-02-13 09:52:01 -0800734 elif options.chrome_rev == constants.CHROME_REV_LOCAL:
735 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
736 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800737
738 if options.chrome_version:
739 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700740 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
741 constants.CHROME_REV_SPEC)
David Jamesa0a664e2013-02-13 09:52:01 -0800742 elif options.chrome_rev == constants.CHROME_REV_SPEC:
743 cros_build_lib.Die(
744 'Chrome rev must not be %s if chrome_version is not set.'
745 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800746
David James9e27e662013-02-14 13:42:43 -0800747 patches = bool(options.gerrit_patches or options.local_patches or
748 options.rietveld_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700749 if options.remote:
750 if options.local:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700751 cros_build_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -0700752
Don Garrett5af1d262014-05-16 15:49:37 -0700753 # options.channels is a convenient way to detect payloads builds.
Prathmesh Prabhu0bc7f122015-07-25 17:09:26 -0700754 if (not options.list and not options.buildbot and not options.channels and
755 not patches):
Gaurav Shahed0399e2014-02-03 13:36:22 -0800756 prompt = ('No patches were provided; are you sure you want to just '
757 'run a remote build of %s?' % (
758 options.branch if options.branch else 'ToT'))
759 if not cros_build_lib.BooleanPrompt(prompt=prompt, default=False):
Brian Harring7cc4b932012-11-01 16:58:55 -0700760 cros_build_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800761
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700762 # --debug needs to be explicitly passed through for remote invocations.
763 release_mode_with_patches = (options.buildbot and patches and
764 '--debug' not in options.pass_through_args)
765 else:
766 if len(args) > 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700767 cros_build_lib.Die('Multiple configs not supported if not running with '
Brian Harringf1aad832012-07-18 10:46:39 -0700768 '--remote. Got %r', args)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700769
Ryan Cui79319ab2012-05-21 12:59:18 -0700770 if options.slaves:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700771 cros_build_lib.Die('Cannot use --slaves if not running with --remote.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700772
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700773 release_mode_with_patches = (options.buildbot and patches and
774 not options.debug)
775
David James5734ea32012-08-15 20:23:49 -0700776 # When running in release mode, make sure we are running with checked-in code.
777 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
778 # a release image with checked-in code for CrOS packages.
779 if release_mode_with_patches:
780 cros_build_lib.Die(
781 'Cannot provide patches when running with --buildbot!')
782
Ryan Cuiba41ad32012-03-08 17:15:29 -0800783 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700784 cros_build_lib.Die(
785 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800786
Ryan Cui85867972012-02-23 18:21:49 -0800787 # Record whether --debug was set explicitly vs. it was inferred.
788 options.debug_forced = False
789 if options.debug:
790 options.debug_forced = True
Ryan Cui88b901c2013-06-21 11:35:30 -0700791 if not options.debug:
Ryan Cui16ca5812012-03-08 20:34:27 -0800792 # We don't set debug by default for
793 # 1. --buildbot invocations.
794 # 2. --remote invocations, because it needs to push changes to the tryjob
795 # repo.
796 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -0800797
Ryan Cui1c13a252012-10-16 15:00:16 -0700798 # Record the configs targeted.
799 options.build_targets = args[:]
800
Ryan Cui88b901c2013-06-21 11:35:30 -0700801 if constants.BRANCH_UTIL_CONFIG in options.build_targets:
Ryan Cui7bd8db62013-08-08 16:29:51 -0700802 if options.remote:
803 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800804 'Running %s as a remote tryjob is not yet supported.',
805 constants.BRANCH_UTIL_CONFIG)
Ryan Cui88b901c2013-06-21 11:35:30 -0700806 if len(options.build_targets) > 1:
807 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800808 'Cannot run %s with any other configs.',
809 constants.BRANCH_UTIL_CONFIG)
Ryan Cui88b901c2013-06-21 11:35:30 -0700810 if not options.branch_name:
811 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800812 'Must specify --branch-name with the %s config.',
813 constants.BRANCH_UTIL_CONFIG)
814 if options.branch and options.branch != options.branch_name:
Ryan Cui88b901c2013-06-21 11:35:30 -0700815 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800816 'If --branch is specified with the %s config, it must'
817 ' have the same value as --branch-name.',
818 constants.BRANCH_UTIL_CONFIG)
819
820 exclusive_opts = {'--version': options.force_version,
821 '--delete-branch': options.delete_branch,
David Jameseecba232014-06-11 11:35:11 -0700822 '--rename-to': options.rename_to}
Matt Tennanta130ea32013-12-19 09:38:39 -0800823 if 1 != sum(1 for x in exclusive_opts.values() if x):
824 cros_build_lib.Die('When using the %s config, you must'
825 ' specifiy one and only one of the following'
826 ' options: %s.', constants.BRANCH_UTIL_CONFIG,
827 ', '.join(exclusive_opts.keys()))
828
829 # When deleting or renaming a branch, the --branch and --nobootstrap
830 # options are implied.
831 if options.delete_branch or options.rename_to:
832 if not options.branch:
Ralph Nathan03047282015-03-23 11:09:32 -0700833 logging.info('Automatically enabling sync to branch %s for this %s '
834 'flow.', options.branch_name,
835 constants.BRANCH_UTIL_CONFIG)
Matt Tennanta130ea32013-12-19 09:38:39 -0800836 options.branch = options.branch_name
837 if options.bootstrap:
Ralph Nathan03047282015-03-23 11:09:32 -0700838 logging.info('Automatically disabling bootstrap step for this %s flow.',
839 constants.BRANCH_UTIL_CONFIG)
Matt Tennanta130ea32013-12-19 09:38:39 -0800840 options.bootstrap = False
841
Ryan Cui88b901c2013-06-21 11:35:30 -0700842 elif any([options.delete_branch, options.rename_to, options.branch_name]):
843 cros_build_lib.Die(
844 'Cannot specify --delete-branch, --rename-to or --branch-name when not '
845 'running the %s config', constants.BRANCH_UTIL_CONFIG)
846
Brian Harring3fec5a82012-03-01 05:57:03 -0800847
Brian Harring1d7ba942012-04-24 06:37:18 -0700848# pylint: disable=W0613
Don Garrett4af20982015-05-29 19:02:23 -0700849def _PostParseCheck(parser, options, args, site_config):
Ryan Cui85867972012-02-23 18:21:49 -0800850 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800851
Ryan Cui85867972012-02-23 18:21:49 -0800852 Args:
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800853 parser: Option parser that was used to parse arguments.
854 options: The options returned by optparse.
855 args: The args returned by optparse.
Don Garrett4af20982015-05-29 19:02:23 -0700856 site_config: config_lib.SiteConfig containing all config info.
Ryan Cui85867972012-02-23 18:21:49 -0800857 """
Don Garrett0a873e02015-06-30 17:55:10 -0700858 if not args:
859 parser.error('Invalid usage: no configuration targets provided.'
860 'Use -h to see usage. Use -l to list supported configs.')
861
Ryan Cuie1e4e662012-05-21 16:39:46 -0700862 if not options.branch:
David James97d95872012-11-16 15:09:56 -0800863 options.branch = git.GetChromiteTrackingBranch()
Ryan Cuie1e4e662012-05-21 16:39:46 -0700864
Brian Harringae0a5322012-09-15 01:46:51 -0700865 if not repository.IsARepoRoot(options.sourceroot):
866 if options.local_patches:
867 raise Exception('Could not find repo checkout at %s!'
868 % options.sourceroot)
869
David Jamesac8c2a72013-02-13 18:44:33 -0800870 # Because the default cache dir depends on other options, FindCacheDir
871 # always returns None, and we setup the default here.
Brian Harringae0a5322012-09-15 01:46:51 -0700872 if options.cache_dir is None:
873 # Note, options.sourceroot is set regardless of the path
874 # actually existing.
David Jamesac8c2a72013-02-13 18:44:33 -0800875 if options.buildroot is not None:
Brian Harringae0a5322012-09-15 01:46:51 -0700876 options.cache_dir = os.path.join(options.buildroot, '.cache')
David Jamesac8c2a72013-02-13 18:44:33 -0800877 elif os.path.exists(options.sourceroot):
878 options.cache_dir = os.path.join(options.sourceroot, '.cache')
Brian Harringae0a5322012-09-15 01:46:51 -0700879 else:
880 options.cache_dir = parser.FindCacheDir(parser, options)
881 options.cache_dir = os.path.abspath(options.cache_dir)
Brian Harring8c1d7b12012-10-04 17:36:32 -0700882 parser.ConfigureCacheDir(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700883
Yu-Ju Hong2c066762013-10-28 14:05:08 -0700884 osutils.SafeMakedirsNonRoot(options.cache_dir)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700885
Brian Harring609dc4e2012-05-07 02:17:44 -0700886 if options.local_patches:
Brian Harring1d7ba942012-04-24 06:37:18 -0700887 options.local_patches = _CheckLocalPatches(
Brian Harring609dc4e2012-05-07 02:17:44 -0700888 options.sourceroot, options.local_patches)
Brian Harring1d7ba942012-04-24 06:37:18 -0700889
890 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
891 if (default and not any([options.local, options.buildbot,
892 options.remote, options.remote_trybot])):
Ralph Nathan03047282015-03-23 11:09:32 -0700893 logging.info('CBUILDBOT_DEFAULT_MODE=%s env var detected, using it.'
894 % default)
Brian Harring1d7ba942012-04-24 06:37:18 -0700895 default = default.lower()
896 if default == 'local':
897 options.local = True
898 elif default == 'remote':
899 options.remote = True
900 elif default == 'buildbot':
901 options.buildbot = True
902 else:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700903 cros_build_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
904 % default)
Ryan Cui85867972012-02-23 18:21:49 -0800905
Matt Tennant763497d2014-01-17 16:45:54 -0800906 # Ensure that all args are legitimate config targets.
Chris Sosa55cdc942014-04-16 13:08:37 -0700907 invalid_targets = []
Matt Tennant763497d2014-01-17 16:45:54 -0800908 for arg in args:
Don Garrett4af20982015-05-29 19:02:23 -0700909 if arg not in site_config:
Chris Sosa55cdc942014-04-16 13:08:37 -0700910 invalid_targets.append(arg)
Ralph Nathan59900422015-03-24 10:41:17 -0700911 logging.error('No such configuraton target: "%s".', arg)
Don Garrett4bb21682014-03-03 16:16:23 -0800912 continue
913
Don Garrett4af20982015-05-29 19:02:23 -0700914 build_config = site_config[arg]
915
Don Garrett5af1d262014-05-16 15:49:37 -0700916 is_payloads_build = build_config.build_type == constants.PAYLOADS_TYPE
917
918 if options.channels and not is_payloads_build:
Don Garrett4bb21682014-03-03 16:16:23 -0800919 cros_build_lib.Die('--channel must only be used with a payload config,'
920 ' not target (%s).' % arg)
Matt Tennant763497d2014-01-17 16:45:54 -0800921
Don Garrett5af1d262014-05-16 15:49:37 -0700922 if not options.channels and is_payloads_build:
923 cros_build_lib.Die('payload configs (%s) require --channel to do anything'
924 ' useful.' % arg)
925
Matt Tennant2c192032014-01-16 13:49:28 -0800926 # The --version option is not compatible with an external target unless the
927 # --buildbot option is specified. More correctly, only "paladin versions"
928 # will work with external targets, and those are only used with --buildbot.
929 # If --buildbot is specified, then user should know what they are doing and
930 # only specify a version that will work. See crbug.com/311648.
Don Garrett4bb21682014-03-03 16:16:23 -0800931 if (options.force_version and
932 not (options.buildbot or build_config.internal)):
933 cros_build_lib.Die('Cannot specify --version without --buildbot for an'
934 ' external target (%s).' % arg)
Matt Tennant2c192032014-01-16 13:49:28 -0800935
Chris Sosa55cdc942014-04-16 13:08:37 -0700936 if invalid_targets:
937 cros_build_lib.Die('One or more invalid configuration targets specified. '
938 'You can check the available configs by running '
939 '`cbuildbot --list --all`')
Matt Tennant763497d2014-01-17 16:45:54 -0800940
Ryan Cui85867972012-02-23 18:21:49 -0800941
Don Garrett0a873e02015-06-30 17:55:10 -0700942def _ParseCommandLine(parser, argv):
Ryan Cui85867972012-02-23 18:21:49 -0800943 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800944 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -0700945
Matt Tennant763497d2014-01-17 16:45:54 -0800946 # Strip out null arguments.
947 # TODO(rcui): Remove when buildbot is fixed
948 args = [arg for arg in args if arg]
949
Brian Harring37e559b2012-05-22 20:47:32 -0700950 if options.output_api_version:
Mike Frysinger383367e2014-09-16 15:06:17 -0400951 print(constants.REEXEC_API_VERSION)
Brian Harring37e559b2012-05-22 20:47:32 -0700952 sys.exit(0)
953
Ryan Cui85867972012-02-23 18:21:49 -0800954 _FinishParsing(options, args)
955 return options, args
956
957
Aviv Keshet420de512015-05-18 14:28:48 -0700958_ENVIRONMENT_PROD = 'prod'
959_ENVIRONMENT_DEBUG = 'debug'
960_ENVIRONMENT_STANDALONE = 'standalone'
961
962
963def _GetRunEnvironment(options, build_config):
964 """Determine whether this is a prod/debug/standalone run."""
965 # TODO(akeshet): This is a temporary workaround to make sure that the cidb
966 # is not used on waterfalls that the db schema does not support (in particular
967 # the chromeos.chrome waterfall).
968 # See crbug.com/406940
969 waterfall = os.environ.get('BUILDBOT_MASTERNAME', '')
970 if not waterfall in constants.CIDB_KNOWN_WATERFALLS:
971 return _ENVIRONMENT_STANDALONE
972
973 # TODO(akeshet): Clean up this code once we have better defined flags to
974 # specify on-or-off waterfall and on-or-off production runs of cbuildbot.
975 # See crbug.com/331417
976
977 # --buildbot runs should use the production services, unless the --debug flag
978 # is also present.
979 if options.buildbot:
980 if options.debug:
981 return _ENVIRONMENT_DEBUG
982 else:
983 return _ENVIRONMENT_PROD
984
985 # --remote-trybot runs should use the debug services, with the exception of
986 # pre-cq builds, which should use the production services.
987 if options.remote_trybot:
988 if build_config['pre_cq']:
989 return _ENVIRONMENT_PROD
990 else:
991 return _ENVIRONMENT_DEBUG
992
993 # If neither --buildbot nor --remote-trybot flag was used, don't use external
994 # services.
995 return _ENVIRONMENT_STANDALONE
996
997
Gabe Blackde694a32015-02-19 15:11:11 -0800998def _SetupConnections(options, build_config):
999 """Set up CIDB and graphite connections using the appropriate Setup call.
Aviv Keshet2982af52014-08-13 16:07:57 -07001000
1001 Args:
1002 options: Command line options structure.
Aviv Keshet64133022014-08-25 15:50:52 -07001003 build_config: Config object for this build.
Aviv Keshet2982af52014-08-13 16:07:57 -07001004 """
Aviv Keshet420de512015-05-18 14:28:48 -07001005 # Outline:
1006 # 1) Based on options and build_config, decide whether we are a production
1007 # run, debug run, or standalone run.
1008 # 2) Set up cidb instance accordingly.
1009 # 3) Update topology info from cidb, so that any other service set up can use
1010 # topology.
1011 # 4) Set up any other services.
1012 run_type = _GetRunEnvironment(options, build_config)
1013
1014 if run_type == _ENVIRONMENT_PROD:
1015 cidb.CIDBConnectionFactory.SetupProdCidb()
Paul Hobbsfcf10342015-12-29 15:52:31 -08001016 ts_mon_config.setup_ts_mon_global_state()
Aviv Keshet420de512015-05-18 14:28:48 -07001017 elif run_type == _ENVIRONMENT_DEBUG:
1018 cidb.CIDBConnectionFactory.SetupDebugCidb()
1019 else:
Aviv Keshet62d1a0e2014-08-22 21:16:13 -07001020 cidb.CIDBConnectionFactory.SetupNoCidb()
Aviv Keshet62d1a0e2014-08-22 21:16:13 -07001021
Aviv Keshet420de512015-05-18 14:28:48 -07001022 db = cidb.CIDBConnectionFactory.GetCIDBConnectionForBuilder()
1023 topology.FetchTopologyFromCIDB(db)
Aviv Keshet64133022014-08-25 15:50:52 -07001024
Aviv Keshet420de512015-05-18 14:28:48 -07001025 if run_type == _ENVIRONMENT_PROD:
1026 graphite.ESMetadataFactory.SetupProd()
1027 graphite.StatsFactory.SetupProd()
1028 elif run_type == _ENVIRONMENT_DEBUG:
1029 graphite.ESMetadataFactory.SetupReadOnly()
1030 graphite.StatsFactory.SetupDebug()
1031 else:
1032 graphite.ESMetadataFactory.SetupReadOnly()
1033 graphite.StatsFactory.SetupMock()
Aviv Keshet2982af52014-08-13 16:07:57 -07001034
1035
Don Garrettbfb33532015-07-07 16:56:43 -07001036def _FetchInitialBootstrapConfigRepo(repo_url, branch_name):
1037 """Fetch the TOT site config repo, if necessary to start bootstrap."""
1038
1039 # If we are part of a repo checkout, the manifest stages control things.
1040 if git.FindRepoDir(constants.SOURCE_ROOT):
1041 return
1042
1043 # We must be part of a bootstrap chromite checkout, probably on a buildbot.
1044
1045 # If the config directory already exists, we have started the bootstrap
1046 # process. Assume the boostrap stage did the right thing, and leave the config
1047 # directory alone.
1048 if os.path.exists(constants.SITE_CONFIG_DIR):
1049 return
1050
1051 # We are part of a clean chromite checkout (buildbot always cleans chromite
1052 # before launching us), so create the initial site config checkout.
1053 logging.info('Fetching Config Repo: %s', repo_url)
1054 git.Clone(constants.SITE_CONFIG_DIR, repo_url)
1055
1056 if branch_name:
1057 git.RunGit(constants.SITE_CONFIG_DIR, ['checkout', branch_name])
1058
Don Garrett05fa8102015-09-10 14:48:05 -07001059 # Clear the cached SiteConfig, if there was one.
1060 config_lib.ClearConfigCache()
Don Garrettbfb33532015-07-07 16:56:43 -07001061
Matt Tennant759e2352013-09-27 15:14:44 -07001062# TODO(build): This function is too damn long.
Ryan Cui85867972012-02-23 18:21:49 -08001063def main(argv):
David James59a0a2b2013-03-22 14:04:44 -07001064 # Turn on strict sudo checks.
1065 cros_build_lib.STRICT_SUDO = True
1066
Ryan Cui85867972012-02-23 18:21:49 -08001067 # Set umask to 022 so files created by buildbot are readable.
Mike Frysinger60ec1012013-10-21 00:11:10 -04001068 os.umask(0o22)
Ryan Cui85867972012-02-23 18:21:49 -08001069
Ryan Cui85867972012-02-23 18:21:49 -08001070 parser = _CreateParser()
Don Garrett0a873e02015-06-30 17:55:10 -07001071 options, args = _ParseCommandLine(parser, argv)
1072
Don Garrettbfb33532015-07-07 16:56:43 -07001073 if options.buildbot and options.config_repo:
1074 _FetchInitialBootstrapConfigRepo(options.config_repo, options.branch)
Don Garrettde81cc72015-07-07 13:23:28 -07001075
1076 if options.config_repo:
Don Garrettbfb33532015-07-07 16:56:43 -07001077 # Ensure expected config file is present.
1078 if not os.path.exists(constants.SITE_CONFIG_FILE):
1079 cros_build_lib.Die('Unabled to find: %s', constants.SITE_CONFIG_FILE)
Don Garrettde81cc72015-07-07 13:23:28 -07001080
Don Garrettb85658c2015-06-30 19:07:22 -07001081 # Fetch our site_config now, because we need it to do anything else.
Don Garrettde81cc72015-07-07 13:23:28 -07001082 site_config = config_lib.GetConfig()
Don Garrettb85658c2015-06-30 19:07:22 -07001083
Don Garrett0a873e02015-06-30 17:55:10 -07001084 if options.list:
1085 _PrintValidConfigs(site_config, options.print_all)
1086 sys.exit(0)
Brian Harring3fec5a82012-03-01 05:57:03 -08001087
Don Garrett4af20982015-05-29 19:02:23 -07001088 _PostParseCheck(parser, options, args, site_config)
Brian Harring3fec5a82012-03-01 05:57:03 -08001089
Mike Frysinger8fd67dc2012-12-03 23:51:18 -05001090 cros_build_lib.AssertOutsideChroot()
Zdenek Behan98ec2fb2012-08-31 17:12:18 +02001091
Prathmesh Prabhu51d774f2015-07-17 15:11:49 -07001092 if options.enable_buildbot_tags:
1093 logging.EnableBuildbotMarkers()
Brian Harring3fec5a82012-03-01 05:57:03 -08001094 if options.remote:
Ralph Nathan23a12212015-03-25 10:27:54 -07001095 logging.getLogger().setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001096
Brian Harring3fec5a82012-03-01 05:57:03 -08001097 # Verify configs are valid.
Dan Shi0bdb7132013-07-30 16:22:12 -07001098 # If hwtest flag is enabled, post a warning that HWTest step may fail if the
1099 # specified board is not a released platform or it is a generic overlay.
Brian Harring3fec5a82012-03-01 05:57:03 -08001100 for bot in args:
Don Garrett4af20982015-05-29 19:02:23 -07001101 build_config = site_config[bot]
Aviv Kesheta96a2a92013-02-05 17:21:51 -08001102 if options.hwtest:
Ralph Nathan446aee92015-03-23 14:44:56 -07001103 logging.warning(
Dan Shi0bdb7132013-07-30 16:22:12 -07001104 'If %s is not a released platform or it is a generic overlay, '
1105 'the HWTest step will most likely not run; please ask the lab '
1106 'team for help if this is unexpected.' % build_config['boards'])
Brian Harring3fec5a82012-03-01 05:57:03 -08001107
1108 # Verify gerrit patches are valid.
Mike Frysinger383367e2014-09-16 15:06:17 -04001109 print('Verifying patches...')
Mike Frysingerb80d0192015-02-04 22:08:59 -05001110 patch_pool = trybot_patch_pool.TrybotPatchPool.FromOptions(
1111 gerrit_patches=options.gerrit_patches,
1112 local_patches=options.local_patches,
1113 sourceroot=options.sourceroot,
1114 remote_patches=options.remote_patches)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001115
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001116 # --debug need to be explicitly passed through for remote invocations.
1117 if options.buildbot and '--debug' not in options.pass_through_args:
1118 _ConfirmRemoteBuildbotRun()
1119
Mike Frysinger383367e2014-09-16 15:06:17 -04001120 print('Submitting tryjob...')
Paul Hobbs5cd050d2015-06-30 16:52:28 -07001121 _SetupConnections(options, build_config)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001122 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cuia25d8eb2012-07-11 14:54:27 -07001123 tryjob.Submit(testjob=options.test_tryjob, dryrun=False)
Mike Frysinger383367e2014-09-16 15:06:17 -04001124 print('Tryjob submitted!')
1125 print(('Go to %s to view the status of your job.'
1126 % tryjob.GetTrybotWaterfallLink()))
Brian Harring3fec5a82012-03-01 05:57:03 -08001127 sys.exit(0)
Matt Tennant759e2352013-09-27 15:14:44 -07001128
Ryan Cui54da0702012-04-19 18:38:08 -07001129 elif (not options.buildbot and not options.remote_trybot
1130 and not options.resume and not options.local):
Mike Frysinger5672a2a2014-05-31 22:29:57 -04001131 cros_build_lib.Die('Please use --remote or --local to run trybots')
Brian Harring3fec5a82012-03-01 05:57:03 -08001132
Matt Tennant759e2352013-09-27 15:14:44 -07001133 # Only one config arg is allowed in this mode, which was confirmed earlier.
Ryan Cui8be16062012-04-24 12:05:26 -07001134 bot_id = args[-1]
Don Garrett4af20982015-05-29 19:02:23 -07001135 build_config = site_config[bot_id]
Brian Harring3fec5a82012-03-01 05:57:03 -08001136
Don Garrettbbd7b552014-05-16 13:15:21 -07001137 # TODO: Re-enable this block when reference_repo support handles this
1138 # properly. (see chromium:330775)
1139 # if options.reference_repo is None:
1140 # repo_path = os.path.join(options.sourceroot, '.repo')
1141 # # If we're being run from a repo checkout, reuse the repo's git pool to
1142 # # cut down on sync time.
1143 # if os.path.exists(repo_path):
1144 # options.reference_repo = options.sourceroot
1145
1146 if options.reference_repo:
David Jamesdac7a912013-11-18 11:14:44 -08001147 if not os.path.exists(options.reference_repo):
1148 parser.error('Reference path %s does not exist'
1149 % (options.reference_repo,))
1150 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1151 parser.error('Reference path %s does not look to be the base of a '
1152 'repo checkout; no .repo exists in the root.'
1153 % (options.reference_repo,))
1154
Brian Harringf11bf682012-05-14 15:53:43 -07001155 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001156 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001157 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1158 'be used together. Cgroup support is required for '
1159 'buildbot/remote-trybot mode.')
Mike Frysingera78a56e2012-11-20 06:02:30 -05001160 if not cgroups.Cgroup.IsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001161 parser.error('Option --buildbot/--remote-trybot was given, but this '
1162 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001163
David Jamesaad5cc72012-10-26 15:03:13 -07001164 missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
Brian Harring351ce442012-03-09 16:38:14 -08001165 if missing:
David Jameseecba232014-06-11 11:35:11 -07001166 parser.error('Option --buildbot/--remote-trybot requires the following '
Ryan Cuid4a24212012-04-04 18:08:12 -07001167 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001168 % (', '.join(missing)))
1169
David Jamesdac7a912013-11-18 11:14:44 -08001170 if options.reference_repo:
1171 options.reference_repo = os.path.abspath(options.reference_repo)
1172
Brian Harring3fec5a82012-03-01 05:57:03 -08001173 if not options.buildroot:
1174 if options.buildbot:
Gaurav Shah59abcb52014-12-09 15:27:11 -08001175 parser.error('Please specify a buildroot with the --buildroot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001176
Ryan Cui5ba7e152012-05-10 14:36:52 -07001177 options.buildroot = _DetermineDefaultBuildRoot(options.sourceroot,
1178 build_config['internal'])
Brian Harring470f6112012-03-02 11:47:10 -08001179 # We use a marker file in the buildroot to indicate the user has
1180 # consented to using this directory.
1181 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1182 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001183
1184 # Sanity check of buildroot- specifically that it's not pointing into the
1185 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001186 if (not repository.IsARepoRoot(options.buildroot) and
David James13a69c92013-05-09 10:37:42 -07001187 git.FindRepoDir(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001188 parser.error('Configured buildroot %s points into a repository checkout, '
1189 'rather than the root of it. This is not supported.'
1190 % options.buildroot)
1191
Chris Sosab5ea3b42012-10-25 15:25:20 -07001192 if not options.log_dir:
1193 options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1194
Brian Harringd166aaf2012-05-14 18:31:53 -07001195 log_file = None
1196 if options.tee:
Chris Sosab5ea3b42012-10-25 15:25:20 -07001197 log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
1198 osutils.SafeMakedirs(options.log_dir)
Brian Harringd166aaf2012-05-14 18:31:53 -07001199 _BackupPreviousLog(log_file)
1200
Brian Harring1b8c4c82012-05-29 23:03:04 -07001201 with cros_build_lib.ContextManagerStack() as stack:
Aaron Gable881fccb2013-09-27 18:35:24 -07001202 # TODO(ferringb): update this once
1203 # https://chromium-review.googlesource.com/25359
David Jamescebc7272013-07-17 16:45:05 -07001204 # is landed- it's sensitive to the manifest-versions cache path.
1205 options.preserve_paths = set(['manifest-versions', '.cache',
Prathmesh Prabhuf0964912015-06-01 23:29:54 +00001206 'manifest-versions-internal'])
David Jamescebc7272013-07-17 16:45:05 -07001207 if log_file is not None:
1208 # We don't want the critical section to try to clean up the tee process,
1209 # so we run Tee (forked off) outside of it. This prevents a deadlock
1210 # because the Tee process only exits when its pipe is closed, and the
1211 # critical section accidentally holds on to that file handle.
1212 stack.Add(tee.Tee, log_file)
1213 options.preserve_paths.add(_DEFAULT_LOG_DIR)
1214
Brian Harringc2d09d92012-05-13 22:03:15 -07001215 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1216 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001217
Brian Harringc2d09d92012-05-13 22:03:15 -07001218 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001219 # If we're in resume mode, use our parents tempdir rather than
1220 # nesting another layer.
David James4bc13702013-03-26 08:08:04 -07001221 stack.Add(osutils.TempDir, prefix='cbuildbot-tmp', set_global=True)
David Jameseecba232014-06-11 11:35:11 -07001222 logging.debug('Cbuildbot tempdir is %r.', os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001223
Brian Harringc2d09d92012-05-13 22:03:15 -07001224 if options.cgroups:
1225 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001226
Brian Harringc2d09d92012-05-13 22:03:15 -07001227 # Mark everything between EnforcedCleanupSection and here as having to
1228 # be rolled back via the contextmanager cleanup handlers. This
1229 # ensures that sudo bits cannot outlive cbuildbot, that anything
1230 # cgroups would kill gets killed, etc.
David Jamesfb3aac92013-10-16 13:26:52 -07001231 stack.Add(critical_section.ForkWatchdog)
Brian Harringd166aaf2012-05-14 18:31:53 -07001232
Brian Harringc2d09d92012-05-13 22:03:15 -07001233 if not options.buildbot:
Don Garrett6747eba2015-06-25 16:00:16 -07001234 build_config = config_lib.OverrideConfigForTrybot(
Don Garrett4bb21682014-03-03 16:16:23 -08001235 build_config, options)
Brian Harringc2d09d92012-05-13 22:03:15 -07001236
Aviv Kesheta0159be2013-12-12 13:56:28 -08001237 if options.mock_tree_status is not None:
Prathmesh Prabhud51d7502014-12-21 01:42:55 -08001238 stack.Add(mock.patch.object, tree_status, '_GetStatus',
Aviv Kesheta0159be2013-12-12 13:56:28 -08001239 return_value=options.mock_tree_status)
1240
Aviv Keshetcf9c2722014-02-25 15:15:10 -08001241 if options.mock_slave_status is not None:
1242 with open(options.mock_slave_status, 'r') as f:
Aviv Keshet4e750022014-03-07 16:50:34 -08001243 mock_statuses = pickle.load(f)
1244 for key, value in mock_statuses.iteritems():
1245 mock_statuses[key] = manifest_version.BuilderStatus(**value)
Yu-Ju Hongd0fda382014-05-09 15:28:24 -07001246 stack.Add(mock.patch.object,
1247 completion_stages.MasterSlaveSyncCompletionStage,
1248 '_FetchSlaveStatuses',
1249 return_value=mock_statuses)
Aviv Keshetcf9c2722014-02-25 15:15:10 -08001250
Gabe Blackde694a32015-02-19 15:11:11 -08001251 _SetupConnections(options, build_config)
Don Garrettb4318362014-10-03 15:49:36 -07001252 retry_stats.SetupStats()
Aviv Keshet2982af52014-08-13 16:07:57 -07001253
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001254 # For master-slave builds: Update slave's timeout using master's published
1255 # deadline.
1256 if options.buildbot and options.master_build_id is not None:
1257 slave_timeout = None
1258 if cidb.CIDBConnectionFactory.IsCIDBSetup():
1259 cidb_handle = cidb.CIDBConnectionFactory.GetCIDBConnectionForBuilder()
1260 if cidb_handle:
1261 slave_timeout = cidb_handle.GetTimeToDeadline(options.master_build_id)
1262
1263 if slave_timeout is not None:
1264 # Cut me some slack. We artificially add a a small time here to the
1265 # slave_timeout because '0' is handled specially, and because we don't
1266 # want to timeout while trying to set things up.
1267 slave_timeout = slave_timeout + 20
1268 if options.timeout == 0 or slave_timeout < options.timeout:
1269 logging.info('Updating slave build timeout to %d seconds enforced '
Ralph Nathan03047282015-03-23 11:09:32 -07001270 'by the master', slave_timeout)
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001271 options.timeout = slave_timeout
1272 else:
1273 logging.warning('Could not get master deadline for master-slave build. '
1274 'Can not set slave timeout.')
1275
1276 if options.timeout > 0:
1277 stack.Add(timeout_util.FatalTimeout, options.timeout)
1278
Don Garretta52a5b02015-06-02 14:52:57 -07001279 _RunBuildStagesWrapper(options, site_config, build_config)