blob: 55b90b273631724b728d153923d11722a5ad3344 [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
Brian Harring3fec5a82012-03-01 05:57:03 -080017import optparse
18import 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_config
Don Garrett88b8d782014-05-13 17:30:55 -070024from chromite.cbuildbot import cbuildbot_run
25from 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
Prathmesh Prabhud51d7502014-12-21 01:42:55 -080030from chromite.cbuildbot import tree_status
Don Garrett88b8d782014-05-13 17:30:55 -070031from chromite.cbuildbot import trybot_patch_pool
Don Garrett88b8d782014-05-13 17:30:55 -070032from chromite.cbuildbot.stages import completion_stages
Aviv Keshet2982af52014-08-13 16:07:57 -070033from chromite.lib import cidb
Brian Harringc92a7012012-02-29 10:11:34 -080034from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080035from chromite.lib import cleanup
Brian Harringb6cf9142012-09-01 20:43:17 -070036from chromite.lib import commandline
Brian Harring1b8c4c82012-05-29 23:03:04 -070037from chromite.lib import cros_build_lib
Ralph Nathan91874ca2015-03-19 13:29:41 -070038from chromite.lib import cros_logging as logging
David James97d95872012-11-16 15:09:56 -080039from chromite.lib import git
Gabe Blackde694a32015-02-19 15:11:11 -080040from chromite.lib import graphite
Stefan Zagerd49d9ff2014-08-15 21:33:37 -070041from chromite.lib import gob_util
Brian Harringaf019fb2012-05-10 15:06:13 -070042from chromite.lib import osutils
David James6450a0a2012-12-04 07:59:53 -080043from chromite.lib import parallel
Don Garrettb4318362014-10-03 15:49:36 -070044from chromite.lib import retry_stats
Brian Harring3fec5a82012-03-01 05:57:03 -080045from chromite.lib import sudo
David James3432acd2013-11-27 10:02:18 -080046from chromite.lib import timeout_util
Brian Harring3fec5a82012-03-01 05:57:03 -080047
Ryan Cuiadd49122012-03-21 22:19:58 -070048
Brian Harring3fec5a82012-03-01 05:57:03 -080049_DEFAULT_LOG_DIR = 'cbuildbot_logs'
50_BUILDBOT_LOG_FILE = 'cbuildbot.log'
51_DEFAULT_EXT_BUILDROOT = 'trybot'
52_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Brian Harring351ce442012-03-09 16:38:14 -080053_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Ryan Cui1c13a252012-10-16 15:00:16 -070054_API_VERSION_ATTR = 'api_version'
Brian Harring3fec5a82012-03-01 05:57:03 -080055
56
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070057def _PrintValidConfigs(display_all=False):
Brian Harring3fec5a82012-03-01 05:57:03 -080058 """Print a list of valid buildbot configs.
59
Mike Frysinger02e1e072013-11-10 22:11:34 -050060 Args:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070061 display_all: Print all configs. Otherwise, prints only configs with
62 trybot_list=True.
Brian Harring3fec5a82012-03-01 05:57:03 -080063 """
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070064 def _GetSortKey(config_name):
Don Garrett541bd692015-05-05 17:40:57 -070065 config_dict = cbuildbot_config.GetConfig()[config_name]
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070066 return (not config_dict['trybot_list'], config_dict['description'],
67 config_name)
68
Brian Harring3fec5a82012-03-01 05:57:03 -080069 COLUMN_WIDTH = 45
Mike Frysinger383367e2014-09-16 15:06:17 -040070 print()
71 print('config'.ljust(COLUMN_WIDTH), 'description')
72 print('------'.ljust(COLUMN_WIDTH), '-----------')
Don Garrett541bd692015-05-05 17:40:57 -070073 config_names = cbuildbot_config.GetConfig().keys()
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070074 config_names.sort(key=_GetSortKey)
Brian Harring3fec5a82012-03-01 05:57:03 -080075 for name in config_names:
Don Garrett541bd692015-05-05 17:40:57 -070076 if display_all or cbuildbot_config.GetConfig()[name]['trybot_list']:
77 desc = cbuildbot_config.GetConfig()[name].get('description')
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070078 desc = desc if desc else ''
Mike Frysinger383367e2014-09-16 15:06:17 -040079 print(name.ljust(COLUMN_WIDTH), desc)
Brian Harring3fec5a82012-03-01 05:57:03 -080080
Mike Frysinger383367e2014-09-16 15:06:17 -040081 print()
Matt Tennant763497d2014-01-17 16:45:54 -080082
Brian Harring3fec5a82012-03-01 05:57:03 -080083
84def _GetConfig(config_name):
Matt Tennant763497d2014-01-17 16:45:54 -080085 """Gets the configuration for the build if it exists, None otherwise."""
Don Garrett541bd692015-05-05 17:40:57 -070086 if cbuildbot_config.GetConfig().has_key(config_name):
87 return cbuildbot_config.GetConfig()[config_name]
Brian Harring3fec5a82012-03-01 05:57:03 -080088
89
Brian Harring3fec5a82012-03-01 05:57:03 -080090def _ConfirmBuildRoot(buildroot):
91 """Confirm with user the inferred buildroot, and mark it as confirmed."""
Ralph Nathan446aee92015-03-23 14:44:56 -070092 logging.warning('Using default directory %s as buildroot', buildroot)
Brian Harring521e7242012-11-01 16:57:42 -070093 if not cros_build_lib.BooleanPrompt(default=False):
94 print('Please specify a different buildroot via the --buildroot option.')
Brian Harring3fec5a82012-03-01 05:57:03 -080095 sys.exit(0)
96
97 if not os.path.exists(buildroot):
98 os.mkdir(buildroot)
99
100 repository.CreateTrybotMarker(buildroot)
101
102
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700103def _ConfirmRemoteBuildbotRun():
104 """Confirm user wants to run with --buildbot --remote."""
Ralph Nathan446aee92015-03-23 14:44:56 -0700105 logging.warning(
David Jameseecba232014-06-11 11:35:11 -0700106 'You are about to launch a PRODUCTION job! This is *NOT* a '
107 'trybot run! Are you sure?')
Brian Harring521e7242012-11-01 16:57:42 -0700108 if not cros_build_lib.BooleanPrompt(default=False):
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700109 print('Please specify --pass-through="--debug".')
110 sys.exit(0)
111
112
Ryan Cui5ba7e152012-05-10 14:36:52 -0700113def _DetermineDefaultBuildRoot(sourceroot, internal_build):
Brian Harring3fec5a82012-03-01 05:57:03 -0800114 """Default buildroot to be under the directory that contains current checkout.
115
Mike Frysinger02e1e072013-11-10 22:11:34 -0500116 Args:
Brian Harring3fec5a82012-03-01 05:57:03 -0800117 internal_build: Whether the build is an internal build
Ryan Cui5ba7e152012-05-10 14:36:52 -0700118 sourceroot: Use specified sourceroot.
Brian Harring3fec5a82012-03-01 05:57:03 -0800119 """
Ryan Cui5ba7e152012-05-10 14:36:52 -0700120 if not repository.IsARepoRoot(sourceroot):
Brian Harring1b8c4c82012-05-29 23:03:04 -0700121 cros_build_lib.Die(
122 'Could not find root of local checkout at %s. Please specify '
123 'using the --sourceroot option.' % sourceroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800124
125 # Place trybot buildroot under the directory containing current checkout.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700126 top_level = os.path.dirname(os.path.realpath(sourceroot))
Brian Harring3fec5a82012-03-01 05:57:03 -0800127 if internal_build:
128 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
129 else:
130 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
131
132 return buildroot
133
134
135def _BackupPreviousLog(log_file, backup_limit=25):
136 """Rename previous log.
137
138 Args:
139 log_file: The absolute path to the previous log.
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800140 backup_limit: Maximum number of old logs to keep.
Brian Harring3fec5a82012-03-01 05:57:03 -0800141 """
142 if os.path.exists(log_file):
143 old_logs = sorted(glob.glob(log_file + '.*'),
144 key=distutils.version.LooseVersion)
145
146 if len(old_logs) >= backup_limit:
147 os.remove(old_logs[0])
148
149 last = 0
150 if old_logs:
151 last = int(old_logs.pop().rpartition('.')[2])
152
153 os.rename(log_file, log_file + '.' + str(last + 1))
154
Ryan Cui5616a512012-08-17 13:39:36 -0700155
Gaurav Shah298aa372014-01-31 09:27:24 -0800156def _IsDistributedBuilder(options, chrome_rev, build_config):
157 """Determines whether the builder should be a DistributedBuilder.
158
159 Args:
160 options: options passed on the commandline.
161 chrome_rev: Chrome revision to build.
162 build_config: Builder configuration dictionary.
163
164 Returns:
165 True if the builder should be a distributed_builder
166 """
167 if build_config['pre_cq'] or options.pre_cq:
168 return True
169 elif not options.buildbot:
170 return False
171 elif chrome_rev in (constants.CHROME_REV_TOT,
172 constants.CHROME_REV_LOCAL,
173 constants.CHROME_REV_SPEC):
174 # We don't do distributed logic to TOT Chrome PFQ's, nor local
175 # chrome roots (e.g. chrome try bots)
176 # TODO(davidjames): Update any builders that rely on this logic to use
177 # manifest_version=False instead.
178 return False
179 elif build_config['manifest_version']:
180 return True
181
182 return False
183
184
David James944a48e2012-03-07 12:19:03 -0800185def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800186 """Helper function that wraps RunBuildStages()."""
Ralph Nathan03047282015-03-23 11:09:32 -0700187 logging.info('cbuildbot was executed with args %s' %
188 cros_build_lib.CmdToStr(sys.argv))
Brian Harring3fec5a82012-03-01 05:57:03 -0800189
David Jamesa0a664e2013-02-13 09:52:01 -0800190 chrome_rev = build_config['chrome_rev']
191 if options.chrome_rev:
192 chrome_rev = options.chrome_rev
193 if chrome_rev == constants.CHROME_REV_TOT:
Stefan Zagerd49d9ff2014-08-15 21:33:37 -0700194 options.chrome_version = gob_util.GetTipOfTrunkRevision(
195 constants.CHROMIUM_GOB_URL)
David Jamesa0a664e2013-02-13 09:52:01 -0800196 options.chrome_rev = constants.CHROME_REV_SPEC
197
David James4a404a52013-02-19 13:07:59 -0800198 # If it's likely we'll need to build Chrome, fetch the source.
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500199 if build_config['sync_chrome'] is None:
David Jameseecba232014-06-11 11:35:11 -0700200 options.managed_chrome = (
201 chrome_rev != constants.CHROME_REV_LOCAL and
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500202 (not build_config['usepkg_build_packages'] or chrome_rev or
David James3cce4642013-05-10 17:50:23 -0700203 build_config['profile'] or options.rietveld_patches))
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500204 else:
205 options.managed_chrome = build_config['sync_chrome']
David James2333c182013-02-13 16:16:15 -0800206
207 if options.managed_chrome:
208 # Tell Chrome to fetch the source locally.
Matt Tennant628ffdd2013-11-27 14:44:39 -0800209 internal = constants.USE_CHROME_INTERNAL in build_config['useflags']
David James2333c182013-02-13 16:16:15 -0800210 chrome_src = 'chrome-src-internal' if internal else 'chrome-src'
211 options.chrome_root = os.path.join(options.cache_dir, 'distfiles', 'target',
212 chrome_src)
David James9e27e662013-02-14 13:42:43 -0800213 elif options.rietveld_patches:
David James4a404a52013-02-19 13:07:59 -0800214 cros_build_lib.Die('This builder does not support Rietveld patches.')
David James2333c182013-02-13 16:16:15 -0800215
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700216 metadata_dump_dict = {}
217 if options.metadata_dump:
218 with open(options.metadata_dump, 'r') as metadata_file:
219 metadata_dump_dict = json.loads(metadata_file.read())
220
Matt Tennant95a42ad2013-12-27 15:38:36 -0800221 # We are done munging options values, so freeze options object now to avoid
222 # further abuse of it.
223 # TODO(mtennant): one by one identify each options value override and see if
224 # it can be handled another way. Try to push this freeze closer and closer
225 # to the start of the script (e.g. in or after _PostParseCheck).
226 options.Freeze()
227
Matt Tennant0940c382014-01-21 20:43:55 -0800228 with parallel.Manager() as manager:
229 builder_run = cbuildbot_run.BuilderRun(options, build_config, manager)
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700230 if metadata_dump_dict:
231 builder_run.attrs.metadata.UpdateWithDict(metadata_dump_dict)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500232
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500233 if builder_run.config.builder_class_name is None:
234 # TODO: This should get relocated to cbuildbot_config.
Mike Frysingere4d68c22015-02-04 21:26:24 -0500235 if _IsDistributedBuilder(options, chrome_rev, build_config):
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500236 builder_cls_name = 'simple_builders.DistributedBuilder'
Mike Frysingere4d68c22015-02-04 21:26:24 -0500237 else:
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500238 builder_cls_name = 'simple_builders.SimpleBuilder'
239 builder_cls = builders.GetBuilderClass(builder_cls_name)
240 builder = builder_cls(builder_run)
Matt Tennant0940c382014-01-21 20:43:55 -0800241 else:
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500242 builder = builders.Builder(builder_run)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500243
Matt Tennant0940c382014-01-21 20:43:55 -0800244 if not builder.Run():
245 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800246
247
248# Parser related functions
Ryan Cui5ba7e152012-05-10 14:36:52 -0700249def _CheckLocalPatches(sourceroot, local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800250 """Do an early quick check of the passed-in patches.
251
252 If the branch of a project is not specified we append the current branch the
253 project is on.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700254
David Jamese3b06062013-11-09 18:52:02 -0800255 TODO(davidjames): The project:branch format isn't unique, so this means that
256 we can't differentiate what directory the user intended to apply patches to.
257 We should references by directory instead.
258
Ryan Cui5ba7e152012-05-10 14:36:52 -0700259 Args:
260 sourceroot: The checkout where patches are coming from.
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800261 local_patches: List of patches to check in project:branch format.
David Jamese3b06062013-11-09 18:52:02 -0800262
263 Returns:
264 A list of patches that have been verified, in project:branch format.
Brian Harring3fec5a82012-03-01 05:57:03 -0800265 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700266 verified_patches = []
David James97d95872012-11-16 15:09:56 -0800267 manifest = git.ManifestCheckout.Cached(sourceroot)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700268 for patch in local_patches:
David Jamese3b06062013-11-09 18:52:02 -0800269 project, _, branch = patch.partition(':')
270
Gaurav Shah7afb0562013-12-26 15:05:39 -0800271 checkouts = manifest.FindCheckouts(project, only_patchable=True)
David Jamese3b06062013-11-09 18:52:02 -0800272 if not checkouts:
273 cros_build_lib.Die('Project %s does not exist.' % (project,))
274 if len(checkouts) > 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700275 cros_build_lib.Die(
David Jamese3b06062013-11-09 18:52:02 -0800276 'We do not yet support local patching for projects that are checked '
277 'out to multiple directories. Try uploading your patch to gerrit '
278 'and referencing it via the -g option instead.'
279 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800280
David Jamese3b06062013-11-09 18:52:02 -0800281 ok = False
282 for checkout in checkouts:
283 project_dir = checkout.GetPath(absolute=True)
Brian Harring3fec5a82012-03-01 05:57:03 -0800284
David Jamese3b06062013-11-09 18:52:02 -0800285 # If no branch was specified, we use the project's current branch.
Brian Harring3fec5a82012-03-01 05:57:03 -0800286 if not branch:
David Jamese3b06062013-11-09 18:52:02 -0800287 local_branch = git.GetCurrentBranch(project_dir)
288 else:
289 local_branch = branch
Brian Harring3fec5a82012-03-01 05:57:03 -0800290
David Jamesf1a07612014-04-28 17:48:52 -0700291 if local_branch and git.DoesCommitExistInRepo(project_dir, local_branch):
David Jamese3b06062013-11-09 18:52:02 -0800292 verified_patches.append('%s:%s' % (project, local_branch))
293 ok = True
294
295 if not ok:
296 if branch:
297 cros_build_lib.Die('Project %s does not have branch %s'
David Jameseecba232014-06-11 11:35:11 -0700298 % (project, branch))
David Jamese3b06062013-11-09 18:52:02 -0800299 else:
300 cros_build_lib.Die('Project %s is not on a branch!' % (project,))
Brian Harring3fec5a82012-03-01 05:57:03 -0800301
Ryan Cuicedd8a52012-03-22 02:28:35 -0700302 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800303
304
Brian Harring3fec5a82012-03-01 05:57:03 -0800305def _CheckChromeVersionOption(_option, _opt_str, value, parser):
306 """Upgrade other options based on chrome_version being passed."""
307 value = value.strip()
308
309 if parser.values.chrome_rev is None and value:
310 parser.values.chrome_rev = constants.CHROME_REV_SPEC
311
312 parser.values.chrome_version = value
313
314
315def _CheckChromeRootOption(_option, _opt_str, value, parser):
316 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800317 if parser.values.chrome_rev is None:
318 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
319
Ryan Cui5ba7e152012-05-10 14:36:52 -0700320 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800321
322
323def _CheckChromeRevOption(_option, _opt_str, value, parser):
324 """Validate the chrome_rev option."""
325 value = value.strip()
326 if value not in constants.VALID_CHROME_REVISIONS:
327 raise optparse.OptionValueError('Invalid chrome rev specified')
328
329 parser.values.chrome_rev = value
330
331
David Jamesac8c2a72013-02-13 18:44:33 -0800332def FindCacheDir(_parser, _options):
Brian Harringae0a5322012-09-15 01:46:51 -0700333 return None
334
335
Ryan Cui5ba7e152012-05-10 14:36:52 -0700336class CustomGroup(optparse.OptionGroup):
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800337 """Custom option group which supports arguments passed-through to trybot."""
David Jameseecba232014-06-11 11:35:11 -0700338
Ryan Cui5ba7e152012-05-10 14:36:52 -0700339 def add_remote_option(self, *args, **kwargs):
340 """For arguments that are passed-through to remote trybot."""
341 return optparse.OptionGroup.add_option(self, *args,
342 remote_pass_through=True,
343 **kwargs)
344
345
Ryan Cui1c13a252012-10-16 15:00:16 -0700346class CustomOption(commandline.FilteringOption):
347 """Subclass FilteringOption class to implement pass-through and api."""
Ryan Cui5ba7e152012-05-10 14:36:52 -0700348
Ryan Cui1c13a252012-10-16 15:00:16 -0700349 ACTIONS = commandline.FilteringOption.ACTIONS + ('extend',)
350 STORE_ACTIONS = commandline.FilteringOption.STORE_ACTIONS + ('extend',)
351 TYPED_ACTIONS = commandline.FilteringOption.TYPED_ACTIONS + ('extend',)
352 ALWAYS_TYPED_ACTIONS = (commandline.FilteringOption.ALWAYS_TYPED_ACTIONS +
353 ('extend',))
Ryan Cui79319ab2012-05-21 12:59:18 -0700354
Ryan Cui5ba7e152012-05-10 14:36:52 -0700355 def __init__(self, *args, **kwargs):
356 # The remote_pass_through argument specifies whether we should directly
357 # pass the argument (with its value) onto the remote trybot.
358 self.pass_through = kwargs.pop('remote_pass_through', False)
Ryan Cui1c13a252012-10-16 15:00:16 -0700359 self.api_version = int(kwargs.pop('api', '0'))
360 commandline.FilteringOption.__init__(self, *args, **kwargs)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700361
362 def take_action(self, action, dest, opt, value, values, parser):
Ryan Cui79319ab2012-05-21 12:59:18 -0700363 if action == 'extend':
Mike Frysingerd6925b52012-07-16 16:11:00 -0400364 # If there is extra spaces between each argument, we get '' which later
365 # code barfs on, so skip those. e.g. We see this with the forms:
366 # cbuildbot -p 'proj:branch ' ...
367 # cbuildbot -p ' proj:branch' ...
368 # cbuildbot -p 'proj:branch proj2:branch' ...
369 lvalue = value.split()
Ryan Cui79319ab2012-05-21 12:59:18 -0700370 values.ensure_value(dest, []).extend(lvalue)
Ryan Cui79319ab2012-05-21 12:59:18 -0700371
Ryan Cui1c13a252012-10-16 15:00:16 -0700372 commandline.FilteringOption.take_action(
373 self, action, dest, opt, value, values, parser)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700374
375
Ryan Cui1c13a252012-10-16 15:00:16 -0700376class CustomParser(commandline.FilteringParser):
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800377 """Custom option parser which supports arguments passed-trhough to trybot"""
Matt Tennante8179042013-10-01 15:47:32 -0700378
Brian Harringb6cf9142012-09-01 20:43:17 -0700379 DEFAULT_OPTION_CLASS = CustomOption
380
381 def add_remote_option(self, *args, **kwargs):
382 """For arguments that are passed-through to remote trybot."""
Ryan Cui1c13a252012-10-16 15:00:16 -0700383 return self.add_option(*args, remote_pass_through=True, **kwargs)
Brian Harringb6cf9142012-09-01 20:43:17 -0700384
385
Brian Harring3fec5a82012-03-01 05:57:03 -0800386def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700387 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800388 # Parse options
David Jameseecba232014-06-11 11:35:11 -0700389 usage = 'usage: %prog [options] buildbot_config [buildbot_config ...]'
Brian Harringae0a5322012-09-15 01:46:51 -0700390 parser = CustomParser(usage=usage, caching=FindCacheDir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800391
392 # Main options
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400393 parser.add_option('-l', '--list', action='store_true', dest='list',
394 default=False,
395 help='List the suggested trybot configs to use (see --all)')
Brian Harring3fec5a82012-03-01 05:57:03 -0800396 parser.add_option('-a', '--all', action='store_true', dest='print_all',
397 default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400398 help='List all of the buildbot configs available w/--list')
399
400 parser.add_option('--local', default=False, action='store_true',
David Jameseecba232014-06-11 11:35:11 -0700401 help=('Specifies that this tryjob should be run locally. '
402 'Implies --debug.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400403 parser.add_option('--remote', default=False, action='store_true',
Ryan Cui88b901c2013-06-21 11:35:30 -0700404 help='Specifies that this tryjob should be run remotely.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400405
Ryan Cuie1e4e662012-05-21 16:39:46 -0700406 parser.add_remote_option('-b', '--branch',
David Jameseecba232014-06-11 11:35:11 -0700407 help=('The manifest branch to test. The branch to '
408 'check the buildroot out to.'))
Ryan Cui5ba7e152012-05-10 14:36:52 -0700409 parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
David Jameseecba232014-06-11 11:35:11 -0700410 help=('Root directory where source is checked out to, and '
411 'where the build occurs. For external build configs, '
412 "defaults to 'trybot' directory at top level of your "
413 'repo-managed checkout.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700414 parser.add_remote_option('--chrome_rev', default=None, type='string',
415 action='callback', dest='chrome_rev',
416 callback=_CheckChromeRevOption,
417 help=('Revision of Chrome to use, of type [%s]'
418 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700419 parser.add_remote_option('--profile', default=None, type='string',
420 action='store', dest='profile',
421 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800422
Ryan Cuif4f84be2012-07-09 18:50:41 -0700423 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400424 # Patch selection options.
425 #
426
427 group = CustomGroup(
428 parser,
429 'Patch Options')
430
431 group.add_remote_option('-g', '--gerrit-patches', action='extend',
432 default=[], type='string',
433 metavar="'Id1 *int_Id2...IdN'",
David Jameseecba232014-06-11 11:35:11 -0700434 help=('Space-separated list of short-form Gerrit '
435 "Change-Id's or change numbers to patch. "
436 "Please prepend '*' to internal Change-Id's"))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400437 group.add_remote_option('-G', '--rietveld-patches', action='extend',
438 default=[], type='string',
439 metavar="'id1[:subdir1]...idN[:subdirN]'",
David Jameseecba232014-06-11 11:35:11 -0700440 help=('Space-separated list of short-form Rietveld '
441 'issue numbers to patch. If no subdir is '
442 'specified, the src directory is used.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400443 group.add_option('-p', '--local-patches', action='extend', default=[],
444 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
David Jameseecba232014-06-11 11:35:11 -0700445 help=('Space-separated list of project branches with '
446 'patches to apply. Projects are specified by name. '
447 'If no branch is specified the current branch of the '
448 'project will be used.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400449
450 parser.add_option_group(group)
451
452 #
453 # Remote trybot options.
454 #
455
456 group = CustomGroup(
457 parser,
458 'Remote Trybot Options (--remote)')
459
460 group.add_remote_option('--hwtest', dest='hwtest', action='store_true',
David Jameseecba232014-06-11 11:35:11 -0700461 default=False,
462 help='Run the HWTest stage (tests on real hardware)')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400463 group.add_option('--remote-description', default=None,
David Jameseecba232014-06-11 11:35:11 -0700464 help=('Attach an optional description to a --remote run '
465 'to make it easier to identify the results when it '
466 'finishes'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400467 group.add_option('--slaves', action='extend', default=[],
David Jameseecba232014-06-11 11:35:11 -0700468 help=('Specify specific remote tryslaves to run on (e.g. '
469 'build149-m2); if the bot is busy, it will be queued'))
Don Garrett4bb21682014-03-03 16:16:23 -0800470 group.add_remote_option('--channel', dest='channels', action='extend',
471 default=[],
David Jameseecba232014-06-11 11:35:11 -0700472 help=('Specify a channel for a payloads trybot. Can '
473 'be specified multiple times. No valid for '
474 'non-payloads configs.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400475 group.add_option('--test-tryjob', action='store_true',
476 default=False,
David Jameseecba232014-06-11 11:35:11 -0700477 help=('Submit a tryjob to the test repository. Will not '
478 'show up on the production trybot waterfall.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400479
480 parser.add_option_group(group)
481
482 #
Ryan Cui88b901c2013-06-21 11:35:30 -0700483 # Branch creation options.
484 #
485
486 group = CustomGroup(
487 parser,
488 'Branch Creation Options (used with branch-util)')
489
490 group.add_remote_option('--branch-name',
491 help='The branch to create or delete.')
492 group.add_remote_option('--delete-branch', default=False, action='store_true',
493 help='Delete the branch specified in --branch-name.')
494 group.add_remote_option('--rename-to', type='string',
495 help='Rename a branch to the specified name.')
496 group.add_remote_option('--force-create', default=False, action='store_true',
497 help='Overwrites an existing branch.')
Prathmesh Prabhue5f4d472015-05-07 16:52:10 -0700498 group.add_remote_option('--skip-remote-push', default=False,
499 action='store_true',
500 help='Do not actually push to remote git repos. '
501 'Used for end-to-end testing branching.')
Ryan Cui88b901c2013-06-21 11:35:30 -0700502
503 parser.add_option_group(group)
504
505 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400506 # Advanced options.
Ryan Cuif4f84be2012-07-09 18:50:41 -0700507 #
508
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700509 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800510 parser,
511 'Advanced Options',
512 'Caution: use these options at your own risk.')
513
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400514 group.add_remote_option('--bootstrap-args', action='append', default=[],
David Jameseecba232014-06-11 11:35:11 -0700515 help=('Args passed directly to the bootstrap re-exec '
516 'to skip verification by the bootstrap code'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700517 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
518 default=False, help='This is running on a buildbot')
519 group.add_remote_option('--buildnumber', help='build number', type='int',
520 default=0)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700521 group.add_option('--chrome_root', default=None, type='path',
522 action='callback', callback=_CheckChromeRootOption,
523 dest='chrome_root', help='Local checkout of Chrome to use.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700524 group.add_remote_option('--chrome_version', default=None, type='string',
525 action='callback', dest='chrome_version',
526 callback=_CheckChromeVersionOption,
David Jameseecba232014-06-11 11:35:11 -0700527 help=('Used with SPEC logic to force a particular '
Stefan Zagerd49d9ff2014-08-15 21:33:37 -0700528 'git revision of chrome rather than the '
David Jameseecba232014-06-11 11:35:11 -0700529 'latest.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700530 group.add_remote_option('--clobber', action='store_true', dest='clobber',
531 default=False,
532 help='Clears an old checkout before syncing')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400533 group.add_remote_option('--latest-toolchain', action='store_true',
534 default=False,
535 help='Use the latest toolchain.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700536 parser.add_option('--log_dir', dest='log_dir', type='path',
Brian Harring3fec5a82012-03-01 05:57:03 -0800537 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700538 group.add_remote_option('--maxarchives', dest='max_archive_builds',
539 default=3, type='int',
David Jameseecba232014-06-11 11:35:11 -0700540 help='Change the local saved build count limit.')
Ryan Cuibbd3d4b2012-08-17 12:20:37 -0700541 parser.add_remote_option('--manifest-repo-url',
542 help=('Overrides the default manifest repo url.'))
David James565bc9a2013-04-08 14:54:45 -0700543 group.add_remote_option('--compilecheck', action='store_true', default=False,
544 help='Only verify compilation and unit tests.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700545 group.add_remote_option('--noarchive', action='store_false', dest='archive',
546 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700547 group.add_remote_option('--nobootstrap', action='store_false',
548 dest='bootstrap', default=True,
David Jameseecba232014-06-11 11:35:11 -0700549 help=("Don't checkout and run from a standalone "
550 'chromite repo.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700551 group.add_remote_option('--nobuild', action='store_false', dest='build',
552 default=True,
553 help="Don't actually build (for cbuildbot dev)")
554 group.add_remote_option('--noclean', action='store_false', dest='clean',
555 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700556 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
557 default=True,
558 help='Disable cbuildbots usage of cgroups.')
Ryan Cui3ea98e02013-08-07 16:01:48 -0700559 group.add_remote_option('--nochromesdk', action='store_false',
560 dest='chrome_sdk', default=True,
David Jameseecba232014-06-11 11:35:11 -0700561 help=("Don't run the ChromeSDK stage which builds "
562 'Chrome outside of the chroot.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700563 group.add_remote_option('--noprebuilts', action='store_false',
564 dest='prebuilts', default=True,
565 help="Don't upload prebuilts.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700566 group.add_remote_option('--nopatch', action='store_false',
567 dest='postsync_patch', default=True,
568 help=("Don't run PatchChanges stage. This does not "
David Jameseecba232014-06-11 11:35:11 -0700569 'disable patching in of chromite patches '
570 'during BootstrapStage.'))
Don Garrett82c0ae82014-02-03 18:25:11 -0800571 group.add_remote_option('--nopaygen', action='store_false',
572 dest='paygen', default=True,
573 help="Don't generate payloads.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700574 group.add_remote_option('--noreexec', action='store_false',
575 dest='postsync_reexec', default=True,
576 help="Don't reexec into the buildroot after syncing.")
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400577 group.add_remote_option('--nosdk', action='store_true',
578 default=False,
579 help='Re-create the SDK from scratch.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700580 group.add_remote_option('--nosync', action='store_false', dest='sync',
581 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700582 group.add_remote_option('--notests', action='store_false', dest='tests',
583 default=True,
David Jameseecba232014-06-11 11:35:11 -0700584 help=('Override values from buildconfig and run no '
585 'tests.'))
Nam T. Nguyenc93f1342014-07-11 14:40:54 -0700586 group.add_remote_option('--noimagetests', action='store_false',
587 dest='image_test', default=True,
588 help=('Override values from buildconfig and run no '
589 'image tests.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700590 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
591 default=True,
David Jameseecba232014-06-11 11:35:11 -0700592 help=('Override values from buildconfig and never '
593 'uprev.'))
David Jamesdac7a912013-11-18 11:14:44 -0800594 group.add_option('--reference-repo', action='store', default=None,
595 dest='reference_repo',
David Jameseecba232014-06-11 11:35:11 -0700596 help=('Reuse git data stored in an existing repo '
597 'checkout. This can drastically reduce the network '
598 'time spent setting up the trybot checkout. By '
599 "default, if this option isn't given but cbuildbot "
600 'is invoked from a repo checkout, cbuildbot will '
601 'use the repo root.'))
Ryan Cuicedd8a52012-03-22 02:28:35 -0700602 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700603 help='Skip stages already successfully completed.')
604 group.add_remote_option('--timeout', action='store', type='int', default=0,
David Jameseecba232014-06-11 11:35:11 -0700605 help=('Specify the maximum amount of time this job '
606 'can run for, at which point the build will be '
607 'aborted. If set to zero, then there is no '
608 'timeout.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700609 group.add_remote_option('--version', dest='force_version', default=None,
David Jameseecba232014-06-11 11:35:11 -0700610 help=('Used with manifest logic. Forces use of this '
611 'version rather than create or get latest. '
612 'Examples: 4815.0.0-rc1, 4815.1.2'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400613
614 parser.add_option_group(group)
615
616 #
617 # Internal options.
618 #
619
620 group = CustomGroup(
621 parser,
Mike Frysinger34db8692013-11-11 14:54:08 -0500622 'Internal Chromium OS Build Team Options',
623 'Caution: these are for meant for the Chromium OS build team only')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400624
625 group.add_remote_option('--archive-base', type='gs_path',
David Jameseecba232014-06-11 11:35:11 -0700626 help=('Base GS URL (gs://<bucket_name>/<path>) to '
627 'upload archive artifacts to'))
628 group.add_remote_option(
629 '--cq-gerrit-query', dest='cq_gerrit_override', default=None,
630 help=('If given, this gerrit query will be used to find what patches to '
631 "test, rather than the normal 'CommitQueue>=1 AND Verified=1 AND "
632 "CodeReview=2' query it defaults to. Use with care- note "
633 'additionally this setting only has an effect if the buildbot '
634 "target is a cq target, and we're in buildbot mode."))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400635 group.add_option('--pass-through', dest='pass_through_args', action='append',
636 type='string', default=[])
David Jamesf421c6d2013-04-11 15:37:57 -0700637 group.add_remote_option('--pre-cq', action='store_true', default=False,
638 help='Mark CLs as tested by the PreCQ on success.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400639 group.add_option('--reexec-api-version', dest='output_api_version',
Ryan Cuif4f84be2012-07-09 18:50:41 -0700640 action='store_true', default=False,
David Jameseecba232014-06-11 11:35:11 -0700641 help=('Used for handling forwards/backwards compatibility '
642 'with --resume and --bootstrap'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400643 group.add_option('--remote-trybot', dest='remote_trybot',
644 action='store_true', default=False,
645 help='Indicates this is running on a remote trybot machine')
646 group.add_remote_option('--remote-patches', action='extend', default=[],
David Jameseecba232014-06-11 11:35:11 -0700647 help=('Patches uploaded by the trybot client when '
648 'run using the -p option'))
Brian Harringf611e6e2012-07-17 18:47:44 -0700649 # Note the default here needs to be hardcoded to 3; that is the last version
650 # that lacked this functionality.
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400651 group.add_option('--remote-version', default=3, type=int, action='store',
David Jameseecba232014-06-11 11:35:11 -0700652 help=('Used for compatibility checks w/tryjobs running in '
653 'older chromite instances'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400654 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT)
655 group.add_remote_option('--test-bootstrap', action='store_true',
656 default=False,
David Jameseecba232014-06-11 11:35:11 -0700657 help=('Causes cbuildbot to bootstrap itself twice, '
658 'in the sequence A->B->C: A(unpatched) patches '
659 'and bootstraps B; B patches and bootstraps C'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400660 group.add_remote_option('--validation_pool', default=None,
David Jameseecba232014-06-11 11:35:11 -0700661 help=('Path to a pickled validation pool. Intended '
662 'for use only with the commit queue.'))
Aviv Keshet007a24a2014-06-23 08:10:55 -0700663 group.add_remote_option('--metadata_dump', default=None,
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700664 help=('Path to a json dumped metadata file. This '
665 'will be used as the initial metadata.'))
Aviv Keshetacf4cfb2014-07-30 12:31:22 -0700666 group.add_remote_option('--master-build-id', default=None, type=int,
667 api=constants.REEXEC_API_MASTER_BUILD_ID,
668 help=('cidb build id of the master build to this '
669 'slave build.'))
Aviv Kesheta0159be2013-12-12 13:56:28 -0800670 group.add_remote_option('--mock-tree-status', dest='mock_tree_status',
671 default=None, action='store',
David Jameseecba232014-06-11 11:35:11 -0700672 help=('Override the tree status value that would be '
673 'returned from the the actual tree. Example '
674 'values: open, closed, throttled. When used '
675 'in conjunction with --debug, the tree status '
676 'will not be ignored as it usually is in a '
677 '--debug run.'))
678 group.add_remote_option(
679 '--mock-slave-status', dest='mock_slave_status', default=None,
680 action='store', metavar='MOCK_SLAVE_STATUS_PICKLE_FILE',
681 help=('Override the result of the _FetchSlaveStatuses method of '
682 'MasterSlaveSyncCompletionStage, by specifying a file with a '
683 'pickle of the result to be returned.'))
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400684
685 parser.add_option_group(group)
Ryan Cuif4f84be2012-07-09 18:50:41 -0700686
687 #
Brian Harring3fec5a82012-03-01 05:57:03 -0800688 # Debug options
Ryan Cuif4f84be2012-07-09 18:50:41 -0700689 #
Brian Harringfec89fe2012-09-23 07:30:54 -0700690 # Temporary hack; in place till --dry-run replaces --debug.
691 # pylint: disable=W0212
Brian Harring009db502012-10-10 02:21:37 -0700692 group = parser.debug_group
Brian Harringfec89fe2012-09-23 07:30:54 -0700693 debug = [x for x in group.option_list if x._long_opts == ['--debug']][0]
David Jameseecba232014-06-11 11:35:11 -0700694 debug.help += ' Currently functions as --dry-run in addition.'
Brian Harringfec89fe2012-09-23 07:30:54 -0700695 debug.pass_through = True
Brian Harring3fec5a82012-03-01 05:57:03 -0800696 group.add_option('--notee', action='store_false', dest='tee', default=True,
David Jameseecba232014-06-11 11:35:11 -0700697 help=('Disable logging and internal tee process. Primarily '
698 'used for debugging cbuildbot itself.'))
Brian Harring3fec5a82012-03-01 05:57:03 -0800699 return parser
700
701
Ryan Cui85867972012-02-23 18:21:49 -0800702def _FinishParsing(options, args):
703 """Perform some parsing tasks that need to take place after optparse.
704
705 This function needs to be easily testable! Keep it free of
706 environment-dependent code. Put more detailed usage validation in
707 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800708
709 Args:
Matt Tennant759e2352013-09-27 15:14:44 -0700710 options: The options object returned by optparse
711 args: The args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800712 """
Ryan Cui41023d92012-11-13 19:59:50 -0800713 # Populate options.pass_through_args.
714 accepted, _ = commandline.FilteringParser.FilterArgs(
715 options.parsed_args, lambda x: x.opt_inst.pass_through)
716 options.pass_through_args.extend(accepted)
Brian Harring07039b52012-05-13 17:56:47 -0700717
Brian Harring3fec5a82012-03-01 05:57:03 -0800718 if options.chrome_root:
719 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700720 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
721 constants.CHROME_REV_LOCAL)
David Jamesa0a664e2013-02-13 09:52:01 -0800722 elif options.chrome_rev == constants.CHROME_REV_LOCAL:
723 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
724 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800725
726 if options.chrome_version:
727 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700728 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
729 constants.CHROME_REV_SPEC)
David Jamesa0a664e2013-02-13 09:52:01 -0800730 elif options.chrome_rev == constants.CHROME_REV_SPEC:
731 cros_build_lib.Die(
732 'Chrome rev must not be %s if chrome_version is not set.'
733 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800734
David James9e27e662013-02-14 13:42:43 -0800735 patches = bool(options.gerrit_patches or options.local_patches or
736 options.rietveld_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700737 if options.remote:
738 if options.local:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700739 cros_build_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -0700740
Don Garrett5af1d262014-05-16 15:49:37 -0700741 # options.channels is a convenient way to detect payloads builds.
742 if not options.buildbot and not options.channels and not patches:
Gaurav Shahed0399e2014-02-03 13:36:22 -0800743 prompt = ('No patches were provided; are you sure you want to just '
744 'run a remote build of %s?' % (
745 options.branch if options.branch else 'ToT'))
746 if not cros_build_lib.BooleanPrompt(prompt=prompt, default=False):
Brian Harring7cc4b932012-11-01 16:58:55 -0700747 cros_build_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800748
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700749 # --debug needs to be explicitly passed through for remote invocations.
750 release_mode_with_patches = (options.buildbot and patches and
751 '--debug' not in options.pass_through_args)
752 else:
753 if len(args) > 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700754 cros_build_lib.Die('Multiple configs not supported if not running with '
Brian Harringf1aad832012-07-18 10:46:39 -0700755 '--remote. Got %r', args)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700756
Ryan Cui79319ab2012-05-21 12:59:18 -0700757 if options.slaves:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700758 cros_build_lib.Die('Cannot use --slaves if not running with --remote.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700759
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700760 release_mode_with_patches = (options.buildbot and patches and
761 not options.debug)
762
David James5734ea32012-08-15 20:23:49 -0700763 # When running in release mode, make sure we are running with checked-in code.
764 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
765 # a release image with checked-in code for CrOS packages.
766 if release_mode_with_patches:
767 cros_build_lib.Die(
768 'Cannot provide patches when running with --buildbot!')
769
Ryan Cuiba41ad32012-03-08 17:15:29 -0800770 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700771 cros_build_lib.Die(
772 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800773
Ryan Cui85867972012-02-23 18:21:49 -0800774 # Record whether --debug was set explicitly vs. it was inferred.
775 options.debug_forced = False
776 if options.debug:
777 options.debug_forced = True
Ryan Cui88b901c2013-06-21 11:35:30 -0700778 if not options.debug:
Ryan Cui16ca5812012-03-08 20:34:27 -0800779 # We don't set debug by default for
780 # 1. --buildbot invocations.
781 # 2. --remote invocations, because it needs to push changes to the tryjob
782 # repo.
783 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -0800784
Ryan Cui1c13a252012-10-16 15:00:16 -0700785 # Record the configs targeted.
786 options.build_targets = args[:]
787
Ryan Cui88b901c2013-06-21 11:35:30 -0700788 if constants.BRANCH_UTIL_CONFIG in options.build_targets:
Ryan Cui7bd8db62013-08-08 16:29:51 -0700789 if options.remote:
790 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800791 'Running %s as a remote tryjob is not yet supported.',
792 constants.BRANCH_UTIL_CONFIG)
Ryan Cui88b901c2013-06-21 11:35:30 -0700793 if len(options.build_targets) > 1:
794 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800795 'Cannot run %s with any other configs.',
796 constants.BRANCH_UTIL_CONFIG)
Ryan Cui88b901c2013-06-21 11:35:30 -0700797 if not options.branch_name:
798 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800799 'Must specify --branch-name with the %s config.',
800 constants.BRANCH_UTIL_CONFIG)
801 if options.branch and options.branch != options.branch_name:
Ryan Cui88b901c2013-06-21 11:35:30 -0700802 cros_build_lib.Die(
Matt Tennanta130ea32013-12-19 09:38:39 -0800803 'If --branch is specified with the %s config, it must'
804 ' have the same value as --branch-name.',
805 constants.BRANCH_UTIL_CONFIG)
806
807 exclusive_opts = {'--version': options.force_version,
808 '--delete-branch': options.delete_branch,
David Jameseecba232014-06-11 11:35:11 -0700809 '--rename-to': options.rename_to}
Matt Tennanta130ea32013-12-19 09:38:39 -0800810 if 1 != sum(1 for x in exclusive_opts.values() if x):
811 cros_build_lib.Die('When using the %s config, you must'
812 ' specifiy one and only one of the following'
813 ' options: %s.', constants.BRANCH_UTIL_CONFIG,
814 ', '.join(exclusive_opts.keys()))
815
816 # When deleting or renaming a branch, the --branch and --nobootstrap
817 # options are implied.
818 if options.delete_branch or options.rename_to:
819 if not options.branch:
Ralph Nathan03047282015-03-23 11:09:32 -0700820 logging.info('Automatically enabling sync to branch %s for this %s '
821 'flow.', options.branch_name,
822 constants.BRANCH_UTIL_CONFIG)
Matt Tennanta130ea32013-12-19 09:38:39 -0800823 options.branch = options.branch_name
824 if options.bootstrap:
Ralph Nathan03047282015-03-23 11:09:32 -0700825 logging.info('Automatically disabling bootstrap step for this %s flow.',
826 constants.BRANCH_UTIL_CONFIG)
Matt Tennanta130ea32013-12-19 09:38:39 -0800827 options.bootstrap = False
828
Ryan Cui88b901c2013-06-21 11:35:30 -0700829 elif any([options.delete_branch, options.rename_to, options.branch_name]):
830 cros_build_lib.Die(
831 'Cannot specify --delete-branch, --rename-to or --branch-name when not '
832 'running the %s config', constants.BRANCH_UTIL_CONFIG)
833
Brian Harring3fec5a82012-03-01 05:57:03 -0800834
Brian Harring1d7ba942012-04-24 06:37:18 -0700835# pylint: disable=W0613
Brian Harringae0a5322012-09-15 01:46:51 -0700836def _PostParseCheck(parser, options, args):
Ryan Cui85867972012-02-23 18:21:49 -0800837 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800838
Ryan Cui85867972012-02-23 18:21:49 -0800839 Args:
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800840 parser: Option parser that was used to parse arguments.
841 options: The options returned by optparse.
842 args: The args returned by optparse.
Ryan Cui85867972012-02-23 18:21:49 -0800843 """
Ryan Cuie1e4e662012-05-21 16:39:46 -0700844 if not options.branch:
David James97d95872012-11-16 15:09:56 -0800845 options.branch = git.GetChromiteTrackingBranch()
Ryan Cuie1e4e662012-05-21 16:39:46 -0700846
Brian Harringae0a5322012-09-15 01:46:51 -0700847 if not repository.IsARepoRoot(options.sourceroot):
848 if options.local_patches:
849 raise Exception('Could not find repo checkout at %s!'
850 % options.sourceroot)
851
David Jamesac8c2a72013-02-13 18:44:33 -0800852 # Because the default cache dir depends on other options, FindCacheDir
853 # always returns None, and we setup the default here.
Brian Harringae0a5322012-09-15 01:46:51 -0700854 if options.cache_dir is None:
855 # Note, options.sourceroot is set regardless of the path
856 # actually existing.
David Jamesac8c2a72013-02-13 18:44:33 -0800857 if options.buildroot is not None:
Brian Harringae0a5322012-09-15 01:46:51 -0700858 options.cache_dir = os.path.join(options.buildroot, '.cache')
David Jamesac8c2a72013-02-13 18:44:33 -0800859 elif os.path.exists(options.sourceroot):
860 options.cache_dir = os.path.join(options.sourceroot, '.cache')
Brian Harringae0a5322012-09-15 01:46:51 -0700861 else:
862 options.cache_dir = parser.FindCacheDir(parser, options)
863 options.cache_dir = os.path.abspath(options.cache_dir)
Brian Harring8c1d7b12012-10-04 17:36:32 -0700864 parser.ConfigureCacheDir(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700865
Yu-Ju Hong2c066762013-10-28 14:05:08 -0700866 osutils.SafeMakedirsNonRoot(options.cache_dir)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700867
Brian Harring609dc4e2012-05-07 02:17:44 -0700868 if options.local_patches:
Brian Harring1d7ba942012-04-24 06:37:18 -0700869 options.local_patches = _CheckLocalPatches(
Brian Harring609dc4e2012-05-07 02:17:44 -0700870 options.sourceroot, options.local_patches)
Brian Harring1d7ba942012-04-24 06:37:18 -0700871
872 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
873 if (default and not any([options.local, options.buildbot,
874 options.remote, options.remote_trybot])):
Ralph Nathan03047282015-03-23 11:09:32 -0700875 logging.info('CBUILDBOT_DEFAULT_MODE=%s env var detected, using it.'
876 % default)
Brian Harring1d7ba942012-04-24 06:37:18 -0700877 default = default.lower()
878 if default == 'local':
879 options.local = True
880 elif default == 'remote':
881 options.remote = True
882 elif default == 'buildbot':
883 options.buildbot = True
884 else:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700885 cros_build_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
886 % default)
Ryan Cui85867972012-02-23 18:21:49 -0800887
Matt Tennant763497d2014-01-17 16:45:54 -0800888 # Ensure that all args are legitimate config targets.
Chris Sosa55cdc942014-04-16 13:08:37 -0700889 invalid_targets = []
Matt Tennant763497d2014-01-17 16:45:54 -0800890 for arg in args:
Matt Tennant2c192032014-01-16 13:49:28 -0800891 build_config = _GetConfig(arg)
Don Garrett4bb21682014-03-03 16:16:23 -0800892
Matt Tennant2c192032014-01-16 13:49:28 -0800893 if not build_config:
Chris Sosa55cdc942014-04-16 13:08:37 -0700894 invalid_targets.append(arg)
Ralph Nathan59900422015-03-24 10:41:17 -0700895 logging.error('No such configuraton target: "%s".', arg)
Don Garrett4bb21682014-03-03 16:16:23 -0800896 continue
897
Don Garrett5af1d262014-05-16 15:49:37 -0700898 is_payloads_build = build_config.build_type == constants.PAYLOADS_TYPE
899
900 if options.channels and not is_payloads_build:
Don Garrett4bb21682014-03-03 16:16:23 -0800901 cros_build_lib.Die('--channel must only be used with a payload config,'
902 ' not target (%s).' % arg)
Matt Tennant763497d2014-01-17 16:45:54 -0800903
Don Garrett5af1d262014-05-16 15:49:37 -0700904 if not options.channels and is_payloads_build:
905 cros_build_lib.Die('payload configs (%s) require --channel to do anything'
906 ' useful.' % arg)
907
Matt Tennant2c192032014-01-16 13:49:28 -0800908 # The --version option is not compatible with an external target unless the
909 # --buildbot option is specified. More correctly, only "paladin versions"
910 # will work with external targets, and those are only used with --buildbot.
911 # If --buildbot is specified, then user should know what they are doing and
912 # only specify a version that will work. See crbug.com/311648.
Don Garrett4bb21682014-03-03 16:16:23 -0800913 if (options.force_version and
914 not (options.buildbot or build_config.internal)):
915 cros_build_lib.Die('Cannot specify --version without --buildbot for an'
916 ' external target (%s).' % arg)
Matt Tennant2c192032014-01-16 13:49:28 -0800917
Chris Sosa55cdc942014-04-16 13:08:37 -0700918 if invalid_targets:
919 cros_build_lib.Die('One or more invalid configuration targets specified. '
920 'You can check the available configs by running '
921 '`cbuildbot --list --all`')
Matt Tennant763497d2014-01-17 16:45:54 -0800922
Ryan Cui85867972012-02-23 18:21:49 -0800923
924def _ParseCommandLine(parser, argv):
925 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800926 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -0700927
Matt Tennant763497d2014-01-17 16:45:54 -0800928 # Strip out null arguments.
929 # TODO(rcui): Remove when buildbot is fixed
930 args = [arg for arg in args if arg]
931
932 # A couple options, like --list, trigger a quick exit.
Brian Harring37e559b2012-05-22 20:47:32 -0700933 if options.output_api_version:
Mike Frysinger383367e2014-09-16 15:06:17 -0400934 print(constants.REEXEC_API_VERSION)
Brian Harring37e559b2012-05-22 20:47:32 -0700935 sys.exit(0)
936
Ryan Cui54da0702012-04-19 18:38:08 -0700937 if options.list:
Matt Tennant763497d2014-01-17 16:45:54 -0800938 if args:
939 cros_build_lib.Die('No arguments expected with the --list options.')
Ryan Cui54da0702012-04-19 18:38:08 -0700940 _PrintValidConfigs(options.print_all)
941 sys.exit(0)
942
Ryan Cui8be16062012-04-24 12:05:26 -0700943 if not args:
Matt Tennant763497d2014-01-17 16:45:54 -0800944 parser.error('Invalid usage: no configuration targets provided.'
945 'Use -h to see usage. Use -l to list supported configs.')
Ryan Cui8be16062012-04-24 12:05:26 -0700946
Ryan Cui85867972012-02-23 18:21:49 -0800947 _FinishParsing(options, args)
948 return options, args
949
950
Gabe Blackde694a32015-02-19 15:11:11 -0800951def _SetupConnections(options, build_config):
952 """Set up CIDB and graphite connections using the appropriate Setup call.
Aviv Keshet2982af52014-08-13 16:07:57 -0700953
954 Args:
955 options: Command line options structure.
Aviv Keshet64133022014-08-25 15:50:52 -0700956 build_config: Config object for this build.
Aviv Keshet2982af52014-08-13 16:07:57 -0700957 """
Aviv Keshet62d1a0e2014-08-22 21:16:13 -0700958 # TODO(akeshet): This is a temporary workaround to make sure that the cidb
959 # is not used on waterfalls that the db schema does not support (in particular
960 # the chromeos.chrome waterfall).
Aviv Keshet64133022014-08-25 15:50:52 -0700961 # See crbug.com/406940
Aviv Keshet62d1a0e2014-08-22 21:16:13 -0700962 waterfall = os.environ.get('BUILDBOT_MASTERNAME', '')
Aviv Keshet3e1efcd2014-09-23 12:05:54 -0700963 if not waterfall in constants.CIDB_KNOWN_WATERFALLS:
Gabe Black84b9c902015-03-09 12:48:48 -0700964 graphite.StatsFactory.SetupMock()
965 graphite.ESMetadataFactory.SetupReadOnly()
Aviv Keshet62d1a0e2014-08-22 21:16:13 -0700966 cidb.CIDBConnectionFactory.SetupNoCidb()
967 return
968
Aviv Keshet64133022014-08-25 15:50:52 -0700969 # TODO(akeshet): Clean up this code once we have better defined flags to
970 # specify on-or-off waterfall and on-or-off production runs of cbuildbot.
971 # See crbug.com/331417
972
Gabe Blackde694a32015-02-19 15:11:11 -0800973 # --buildbot runs should use the production services, unless the --debug flag
974 # is also present in which case they should use the debug cidb and not emit
975 # stats.
Aviv Keshet64133022014-08-25 15:50:52 -0700976 if options.buildbot:
977 if options.debug:
Prathmesh Prabhue9868e22015-03-04 14:14:09 -0800978 graphite.StatsFactory.SetupDebug()
Gabe Blackde694a32015-02-19 15:11:11 -0800979 graphite.ESMetadataFactory.SetupReadOnly()
Aviv Keshet64133022014-08-25 15:50:52 -0700980 cidb.CIDBConnectionFactory.SetupDebugCidb()
981 return
982 else:
Gabe Blackde694a32015-02-19 15:11:11 -0800983 graphite.StatsFactory.SetupProd()
984 graphite.ESMetadataFactory.SetupProd()
Aviv Keshet64133022014-08-25 15:50:52 -0700985 cidb.CIDBConnectionFactory.SetupProdCidb()
986 return
987
Gabe Blackde694a32015-02-19 15:11:11 -0800988 # --remote-trybot runs should use the debug database and not emit stats.
989 # With the exception of pre-cq builds, which should use the production
990 # database and emit stats.
Aviv Keshet64133022014-08-25 15:50:52 -0700991 if options.remote_trybot:
992 if build_config['pre_cq']:
Gabe Blackde694a32015-02-19 15:11:11 -0800993 graphite.StatsFactory.SetupProd()
994 graphite.ESMetadataFactory.SetupProd()
Aviv Keshet64133022014-08-25 15:50:52 -0700995 cidb.CIDBConnectionFactory.SetupProdCidb()
996 return
997 else:
Prathmesh Prabhu829e86c2015-03-05 18:20:08 -0800998 graphite.StatsFactory.SetupDebug()
Gabe Blackde694a32015-02-19 15:11:11 -0800999 graphite.ESMetadataFactory.SetupReadOnly()
Aviv Keshet64133022014-08-25 15:50:52 -07001000 cidb.CIDBConnectionFactory.SetupDebugCidb()
1001 return
1002
1003 # If neither --buildbot nor --remote-trybot flag was used, don't use the
Gabe Blackde694a32015-02-19 15:11:11 -08001004 # database or emit stats.
Aviv Keshet64133022014-08-25 15:50:52 -07001005 cidb.CIDBConnectionFactory.SetupNoCidb()
Gabe Blackde694a32015-02-19 15:11:11 -08001006 graphite.StatsFactory.SetupMock()
1007 graphite.ESMetadataFactory.SetupReadOnly()
Aviv Keshet2982af52014-08-13 16:07:57 -07001008
1009
Matt Tennant759e2352013-09-27 15:14:44 -07001010# TODO(build): This function is too damn long.
Ryan Cui85867972012-02-23 18:21:49 -08001011def main(argv):
David James59a0a2b2013-03-22 14:04:44 -07001012 # Turn on strict sudo checks.
1013 cros_build_lib.STRICT_SUDO = True
1014
Ryan Cui85867972012-02-23 18:21:49 -08001015 # Set umask to 022 so files created by buildbot are readable.
Mike Frysinger60ec1012013-10-21 00:11:10 -04001016 os.umask(0o22)
Ryan Cui85867972012-02-23 18:21:49 -08001017
Ryan Cui85867972012-02-23 18:21:49 -08001018 parser = _CreateParser()
1019 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -08001020
Brian Harringae0a5322012-09-15 01:46:51 -07001021 _PostParseCheck(parser, options, args)
Brian Harring3fec5a82012-03-01 05:57:03 -08001022
Mike Frysinger8fd67dc2012-12-03 23:51:18 -05001023 cros_build_lib.AssertOutsideChroot()
Zdenek Behan98ec2fb2012-08-31 17:12:18 +02001024
Brian Harring3fec5a82012-03-01 05:57:03 -08001025 if options.remote:
Ralph Nathan23a12212015-03-25 10:27:54 -07001026 logging.getLogger().setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001027
Brian Harring3fec5a82012-03-01 05:57:03 -08001028 # Verify configs are valid.
Dan Shi0bdb7132013-07-30 16:22:12 -07001029 # If hwtest flag is enabled, post a warning that HWTest step may fail if the
1030 # specified board is not a released platform or it is a generic overlay.
Brian Harring3fec5a82012-03-01 05:57:03 -08001031 for bot in args:
Aviv Kesheta96a2a92013-02-05 17:21:51 -08001032 build_config = _GetConfig(bot)
1033 if options.hwtest:
Ralph Nathan446aee92015-03-23 14:44:56 -07001034 logging.warning(
Dan Shi0bdb7132013-07-30 16:22:12 -07001035 'If %s is not a released platform or it is a generic overlay, '
1036 'the HWTest step will most likely not run; please ask the lab '
1037 'team for help if this is unexpected.' % build_config['boards'])
Brian Harring3fec5a82012-03-01 05:57:03 -08001038
1039 # Verify gerrit patches are valid.
Mike Frysinger383367e2014-09-16 15:06:17 -04001040 print('Verifying patches...')
Mike Frysingerb80d0192015-02-04 22:08:59 -05001041 patch_pool = trybot_patch_pool.TrybotPatchPool.FromOptions(
1042 gerrit_patches=options.gerrit_patches,
1043 local_patches=options.local_patches,
1044 sourceroot=options.sourceroot,
1045 remote_patches=options.remote_patches)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001046
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001047 # --debug need to be explicitly passed through for remote invocations.
1048 if options.buildbot and '--debug' not in options.pass_through_args:
1049 _ConfirmRemoteBuildbotRun()
1050
Mike Frysinger383367e2014-09-16 15:06:17 -04001051 print('Submitting tryjob...')
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001052 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cuia25d8eb2012-07-11 14:54:27 -07001053 tryjob.Submit(testjob=options.test_tryjob, dryrun=False)
Mike Frysinger383367e2014-09-16 15:06:17 -04001054 print('Tryjob submitted!')
1055 print(('Go to %s to view the status of your job.'
1056 % tryjob.GetTrybotWaterfallLink()))
Brian Harring3fec5a82012-03-01 05:57:03 -08001057 sys.exit(0)
Matt Tennant759e2352013-09-27 15:14:44 -07001058
Ryan Cui54da0702012-04-19 18:38:08 -07001059 elif (not options.buildbot and not options.remote_trybot
1060 and not options.resume and not options.local):
Mike Frysinger5672a2a2014-05-31 22:29:57 -04001061 cros_build_lib.Die('Please use --remote or --local to run trybots')
Brian Harring3fec5a82012-03-01 05:57:03 -08001062
Matt Tennant759e2352013-09-27 15:14:44 -07001063 # Only one config arg is allowed in this mode, which was confirmed earlier.
Ryan Cui8be16062012-04-24 12:05:26 -07001064 bot_id = args[-1]
1065 build_config = _GetConfig(bot_id)
Brian Harring3fec5a82012-03-01 05:57:03 -08001066
Don Garrettbbd7b552014-05-16 13:15:21 -07001067 # TODO: Re-enable this block when reference_repo support handles this
1068 # properly. (see chromium:330775)
1069 # if options.reference_repo is None:
1070 # repo_path = os.path.join(options.sourceroot, '.repo')
1071 # # If we're being run from a repo checkout, reuse the repo's git pool to
1072 # # cut down on sync time.
1073 # if os.path.exists(repo_path):
1074 # options.reference_repo = options.sourceroot
1075
1076 if options.reference_repo:
David Jamesdac7a912013-11-18 11:14:44 -08001077 if not os.path.exists(options.reference_repo):
1078 parser.error('Reference path %s does not exist'
1079 % (options.reference_repo,))
1080 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1081 parser.error('Reference path %s does not look to be the base of a '
1082 'repo checkout; no .repo exists in the root.'
1083 % (options.reference_repo,))
1084
Brian Harringf11bf682012-05-14 15:53:43 -07001085 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001086 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001087 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1088 'be used together. Cgroup support is required for '
1089 'buildbot/remote-trybot mode.')
Mike Frysingera78a56e2012-11-20 06:02:30 -05001090 if not cgroups.Cgroup.IsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001091 parser.error('Option --buildbot/--remote-trybot was given, but this '
1092 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001093
David Jamesaad5cc72012-10-26 15:03:13 -07001094 missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
Brian Harring351ce442012-03-09 16:38:14 -08001095 if missing:
David Jameseecba232014-06-11 11:35:11 -07001096 parser.error('Option --buildbot/--remote-trybot requires the following '
Ryan Cuid4a24212012-04-04 18:08:12 -07001097 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001098 % (', '.join(missing)))
1099
David Jamesdac7a912013-11-18 11:14:44 -08001100 if options.reference_repo:
1101 options.reference_repo = os.path.abspath(options.reference_repo)
1102
Brian Harring3fec5a82012-03-01 05:57:03 -08001103 if not options.buildroot:
1104 if options.buildbot:
Gaurav Shah59abcb52014-12-09 15:27:11 -08001105 parser.error('Please specify a buildroot with the --buildroot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001106
Ryan Cui5ba7e152012-05-10 14:36:52 -07001107 options.buildroot = _DetermineDefaultBuildRoot(options.sourceroot,
1108 build_config['internal'])
Brian Harring470f6112012-03-02 11:47:10 -08001109 # We use a marker file in the buildroot to indicate the user has
1110 # consented to using this directory.
1111 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1112 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001113
1114 # Sanity check of buildroot- specifically that it's not pointing into the
1115 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001116 if (not repository.IsARepoRoot(options.buildroot) and
David James13a69c92013-05-09 10:37:42 -07001117 git.FindRepoDir(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001118 parser.error('Configured buildroot %s points into a repository checkout, '
1119 'rather than the root of it. This is not supported.'
1120 % options.buildroot)
1121
Chris Sosab5ea3b42012-10-25 15:25:20 -07001122 if not options.log_dir:
1123 options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1124
Brian Harringd166aaf2012-05-14 18:31:53 -07001125 log_file = None
1126 if options.tee:
Chris Sosab5ea3b42012-10-25 15:25:20 -07001127 log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
1128 osutils.SafeMakedirs(options.log_dir)
Brian Harringd166aaf2012-05-14 18:31:53 -07001129 _BackupPreviousLog(log_file)
1130
Brian Harring1b8c4c82012-05-29 23:03:04 -07001131 with cros_build_lib.ContextManagerStack() as stack:
Aaron Gable881fccb2013-09-27 18:35:24 -07001132 # TODO(ferringb): update this once
1133 # https://chromium-review.googlesource.com/25359
David Jamescebc7272013-07-17 16:45:05 -07001134 # is landed- it's sensitive to the manifest-versions cache path.
1135 options.preserve_paths = set(['manifest-versions', '.cache',
Simran Basi47eaa5e2015-01-08 14:38:27 -08001136 'manifest-versions-internal',
1137 'chromite-bootstrap'])
David Jamescebc7272013-07-17 16:45:05 -07001138 if log_file is not None:
1139 # We don't want the critical section to try to clean up the tee process,
1140 # so we run Tee (forked off) outside of it. This prevents a deadlock
1141 # because the Tee process only exits when its pipe is closed, and the
1142 # critical section accidentally holds on to that file handle.
1143 stack.Add(tee.Tee, log_file)
1144 options.preserve_paths.add(_DEFAULT_LOG_DIR)
1145
Brian Harringc2d09d92012-05-13 22:03:15 -07001146 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1147 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001148
Brian Harringc2d09d92012-05-13 22:03:15 -07001149 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001150 # If we're in resume mode, use our parents tempdir rather than
1151 # nesting another layer.
David James4bc13702013-03-26 08:08:04 -07001152 stack.Add(osutils.TempDir, prefix='cbuildbot-tmp', set_global=True)
David Jameseecba232014-06-11 11:35:11 -07001153 logging.debug('Cbuildbot tempdir is %r.', os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001154
Brian Harringc2d09d92012-05-13 22:03:15 -07001155 if options.cgroups:
1156 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001157
Brian Harringc2d09d92012-05-13 22:03:15 -07001158 # Mark everything between EnforcedCleanupSection and here as having to
1159 # be rolled back via the contextmanager cleanup handlers. This
1160 # ensures that sudo bits cannot outlive cbuildbot, that anything
1161 # cgroups would kill gets killed, etc.
David Jamesfb3aac92013-10-16 13:26:52 -07001162 stack.Add(critical_section.ForkWatchdog)
Brian Harringd166aaf2012-05-14 18:31:53 -07001163
Brian Harringc2d09d92012-05-13 22:03:15 -07001164 if not options.buildbot:
Don Garrett6ebff152015-05-12 18:22:07 -07001165 build_config = cbuildbot_config.OverrideConfigForTrybot(
Don Garrett4bb21682014-03-03 16:16:23 -08001166 build_config, options)
Brian Harringc2d09d92012-05-13 22:03:15 -07001167
Aviv Kesheta0159be2013-12-12 13:56:28 -08001168 if options.mock_tree_status is not None:
Prathmesh Prabhud51d7502014-12-21 01:42:55 -08001169 stack.Add(mock.patch.object, tree_status, '_GetStatus',
Aviv Kesheta0159be2013-12-12 13:56:28 -08001170 return_value=options.mock_tree_status)
1171
Aviv Keshetcf9c2722014-02-25 15:15:10 -08001172 if options.mock_slave_status is not None:
1173 with open(options.mock_slave_status, 'r') as f:
Aviv Keshet4e750022014-03-07 16:50:34 -08001174 mock_statuses = pickle.load(f)
1175 for key, value in mock_statuses.iteritems():
1176 mock_statuses[key] = manifest_version.BuilderStatus(**value)
Yu-Ju Hongd0fda382014-05-09 15:28:24 -07001177 stack.Add(mock.patch.object,
1178 completion_stages.MasterSlaveSyncCompletionStage,
1179 '_FetchSlaveStatuses',
1180 return_value=mock_statuses)
Aviv Keshetcf9c2722014-02-25 15:15:10 -08001181
Gabe Blackde694a32015-02-19 15:11:11 -08001182 _SetupConnections(options, build_config)
Don Garrettb4318362014-10-03 15:49:36 -07001183 retry_stats.SetupStats()
Aviv Keshet2982af52014-08-13 16:07:57 -07001184
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001185 # For master-slave builds: Update slave's timeout using master's published
1186 # deadline.
1187 if options.buildbot and options.master_build_id is not None:
1188 slave_timeout = None
1189 if cidb.CIDBConnectionFactory.IsCIDBSetup():
1190 cidb_handle = cidb.CIDBConnectionFactory.GetCIDBConnectionForBuilder()
1191 if cidb_handle:
1192 slave_timeout = cidb_handle.GetTimeToDeadline(options.master_build_id)
1193
1194 if slave_timeout is not None:
1195 # Cut me some slack. We artificially add a a small time here to the
1196 # slave_timeout because '0' is handled specially, and because we don't
1197 # want to timeout while trying to set things up.
1198 slave_timeout = slave_timeout + 20
1199 if options.timeout == 0 or slave_timeout < options.timeout:
1200 logging.info('Updating slave build timeout to %d seconds enforced '
Ralph Nathan03047282015-03-23 11:09:32 -07001201 'by the master', slave_timeout)
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001202 options.timeout = slave_timeout
1203 else:
1204 logging.warning('Could not get master deadline for master-slave build. '
1205 'Can not set slave timeout.')
1206
1207 if options.timeout > 0:
1208 stack.Add(timeout_util.FatalTimeout, options.timeout)
1209
Brian Harringc2d09d92012-05-13 22:03:15 -07001210 _RunBuildStagesWrapper(options, build_config)