blob: 6bb322a8c6a3fa375df8ed90fe362efbd1c1c2ba [file] [log] [blame]
Brian Harring3fec5a82012-03-01 05:57:03 -08001#!/usr/bin/python
2
Mike Frysingerd6925b52012-07-16 16:11:00 -04003# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Brian Harring3fec5a82012-03-01 05:57:03 -08004# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Main builder code for Chromium OS.
8
9Used by Chromium OS buildbot configuration for all Chromium OS builds including
10full and pre-flight-queue builds.
11"""
12
David James1fddb8f2013-04-25 15:23:07 -070013import collections
Brian Harring3fec5a82012-03-01 05:57:03 -080014import distutils.version
Mike Frysinger6903c762012-12-04 01:57:16 -050015import errno
Brian Harring3fec5a82012-03-01 05:57:03 -080016import glob
Chris Sosa4f6ffaf2012-05-01 17:05:44 -070017import logging
Brian Harring3fec5a82012-03-01 05:57:03 -080018import optparse
19import os
20import pprint
21import sys
Ryan Cui54da0702012-04-19 18:38:08 -070022import time
David James3541a132013-03-18 13:21:58 -070023import traceback
Brian Harring3fec5a82012-03-01 05:57:03 -080024
25from chromite.buildbot import builderstage as bs
Brian Harring3fec5a82012-03-01 05:57:03 -080026from chromite.buildbot import cbuildbot_config
27from chromite.buildbot import cbuildbot_stages as stages
28from chromite.buildbot import cbuildbot_results as results_lib
Brian Harring3fec5a82012-03-01 05:57:03 -080029from chromite.buildbot import constants
Brian Harring3fec5a82012-03-01 05:57:03 -080030from chromite.buildbot import remote_try
31from chromite.buildbot import repository
32from chromite.buildbot import tee
Ryan Cui16d9e1f2012-05-11 10:50:18 -070033from chromite.buildbot import trybot_patch_pool
Brian Harring3fec5a82012-03-01 05:57:03 -080034
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
David Jamesa0a664e2013-02-13 09:52:01 -080039from chromite.lib import gclient
Brian Harring511055e2012-10-10 02:58:59 -070040from chromite.lib import gerrit
David James97d95872012-11-16 15:09:56 -080041from chromite.lib import git
Brian Harringaf019fb2012-05-10 15:06:13 -070042from chromite.lib import osutils
Brian Harring511055e2012-10-10 02:58:59 -070043from chromite.lib import patch as cros_patch
David James6450a0a2012-12-04 07:59:53 -080044from chromite.lib import parallel
Brian Harring3fec5a82012-03-01 05:57:03 -080045from chromite.lib import sudo
46
Ryan Cuiadd49122012-03-21 22:19:58 -070047
Brian Harring3fec5a82012-03-01 05:57:03 -080048_DEFAULT_LOG_DIR = 'cbuildbot_logs'
49_BUILDBOT_LOG_FILE = 'cbuildbot.log'
50_DEFAULT_EXT_BUILDROOT = 'trybot'
51_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Matt Tennant8a8118a2013-09-11 14:52:15 -070052_DISTRIBUTED_TYPES = [constants.PFQ_TYPE, constants.CANARY_TYPE,
53 constants.CHROME_PFQ_TYPE, constants.PALADIN_TYPE]
Brian Harring351ce442012-03-09 16:38:14 -080054_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Ryan Cui1c13a252012-10-16 15:00:16 -070055_API_VERSION_ATTR = 'api_version'
Brian Harring3fec5a82012-03-01 05:57:03 -080056
57
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070058def _PrintValidConfigs(display_all=False):
Brian Harring3fec5a82012-03-01 05:57:03 -080059 """Print a list of valid buildbot configs.
60
61 Arguments:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070062 display_all: Print all configs. Otherwise, prints only configs with
63 trybot_list=True.
Brian Harring3fec5a82012-03-01 05:57:03 -080064 """
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070065 def _GetSortKey(config_name):
66 config_dict = cbuildbot_config.config[config_name]
67 return (not config_dict['trybot_list'], config_dict['description'],
68 config_name)
69
Brian Harring3fec5a82012-03-01 05:57:03 -080070 COLUMN_WIDTH = 45
71 print 'config'.ljust(COLUMN_WIDTH), 'description'
72 print '------'.ljust(COLUMN_WIDTH), '-----------'
73 config_names = cbuildbot_config.config.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:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070076 if display_all or cbuildbot_config.config[name]['trybot_list']:
77 desc = cbuildbot_config.config[name].get('description')
78 desc = desc if desc else ''
Brian Harring3fec5a82012-03-01 05:57:03 -080079 print name.ljust(COLUMN_WIDTH), desc
80
81
82def _GetConfig(config_name):
83 """Gets the configuration for the build"""
84 if not cbuildbot_config.config.has_key(config_name):
85 print 'Non-existent configuration %s specified.' % config_name
86 print 'Please specify one of:'
87 _PrintValidConfigs()
88 sys.exit(1)
89
90 result = cbuildbot_config.config[config_name]
91
92 return result
93
94
Ryan Cuie1e4e662012-05-21 16:39:46 -070095def AcquirePoolFromOptions(options):
Ryan Cui16d9e1f2012-05-11 10:50:18 -070096 """Generate patch objects from passed in options.
Brian Harring3fec5a82012-03-01 05:57:03 -080097
98 Args:
Ryan Cui16d9e1f2012-05-11 10:50:18 -070099 options: The options object generated by optparse.
Brian Harring3fec5a82012-03-01 05:57:03 -0800100
Ryan Cuif7f24692012-05-18 16:35:33 -0700101 Returns:
102 trybot_patch_pool.TrybotPatchPool object.
103
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700104 Raises:
Brian Harring511055e2012-10-10 02:58:59 -0700105 gerrit.GerritException, cros_patch.PatchException
Brian Harring3fec5a82012-03-01 05:57:03 -0800106 """
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700107 gerrit_patches = []
108 local_patches = []
109 remote_patches = []
Brian Harring3fec5a82012-03-01 05:57:03 -0800110
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700111 if options.gerrit_patches:
Brian Harring511055e2012-10-10 02:58:59 -0700112 gerrit_patches = gerrit.GetGerritPatchInfo(
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700113 options.gerrit_patches)
114 for patch in gerrit_patches:
115 if patch.IsAlreadyMerged():
Brian Harring1b8c4c82012-05-29 23:03:04 -0700116 cros_build_lib.Warning('Patch %s has already been merged.' % str(patch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800117
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700118 if options.local_patches:
David James97d95872012-11-16 15:09:56 -0800119 manifest = git.ManifestCheckout.Cached(options.sourceroot)
Brian Harring609dc4e2012-05-07 02:17:44 -0700120 local_patches = cros_patch.PrepareLocalPatches(manifest,
121 options.local_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800122
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700123 if options.remote_patches:
124 remote_patches = cros_patch.PrepareRemotePatches(
125 options.remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800126
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700127 return trybot_patch_pool.TrybotPatchPool(gerrit_patches, local_patches,
128 remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800129
130
Brian Harring3fec5a82012-03-01 05:57:03 -0800131class Builder(object):
132 """Parent class for all builder types.
133
Matt Tennant759e2352013-09-27 15:14:44 -0700134 This class functions as an abstract parent class for various build types.
135 Its intended use is builder_instance.Run().
Brian Harring3fec5a82012-03-01 05:57:03 -0800136
137 Vars:
Mike Frysinger9b223362013-03-04 21:54:26 -0500138 build_config: The configuration dictionary from cbuildbot_config.
139 options: The options provided from optparse in main().
140 release_tag: The associated "chrome os version" of this build.
Brian Harring3fec5a82012-03-01 05:57:03 -0800141 """
142
Ryan Cuie1e4e662012-05-21 16:39:46 -0700143 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800144 """Initializes instance variables. Must be called by all subclasses."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800145 self.build_config = build_config
146 self.options = options
147
Brian Harring3fec5a82012-03-01 05:57:03 -0800148 if self.build_config['chromeos_official']:
149 os.environ['CHROMEOS_OFFICIAL'] = '1'
150
David James58e0c092012-03-04 20:31:12 -0800151 self.archive_stages = {}
Brian Harring3fec5a82012-03-01 05:57:03 -0800152 self.release_tag = None
Brian Harring76d1bf62012-06-01 13:52:48 -0700153 self.patch_pool = trybot_patch_pool.TrybotPatchPool()
Brian Harring3fec5a82012-03-01 05:57:03 -0800154
Ryan Cuie1e4e662012-05-21 16:39:46 -0700155 bs.BuilderStage.SetManifestBranch(self.options.branch)
Ryan Cuif7f24692012-05-18 16:35:33 -0700156
Brian Harring3fec5a82012-03-01 05:57:03 -0800157 def Initialize(self):
158 """Runs through the initialization steps of an actual build."""
Ryan Cuif7f24692012-05-18 16:35:33 -0700159 if self.options.resume:
160 results_lib.LoadCheckpoint(self.options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800161
Brian Harring3fec5a82012-03-01 05:57:03 -0800162 self._RunStage(stages.CleanUpStage)
163
164 def _GetStageInstance(self, stage, *args, **kwargs):
Matt Tennant759e2352013-09-27 15:14:44 -0700165 """Helper function to get a stage instance given the args.
Brian Harring3fec5a82012-03-01 05:57:03 -0800166
David James944a48e2012-03-07 12:19:03 -0800167 Useful as almost all stages just take in options and build_config.
Brian Harring3fec5a82012-03-01 05:57:03 -0800168 """
Matt Tennant759e2352013-09-27 15:14:44 -0700169 # Normally the current build config is used, but that config can be
170 # overridden with a config kwarg. For example, when getting a stage
171 # for a "child" config.
David James944a48e2012-03-07 12:19:03 -0800172 config = kwargs.pop('config', self.build_config)
173 return stage(self.options, config, *args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800174
175 def _SetReleaseTag(self):
176 """Sets the release tag from the manifest_manager.
177
178 Must be run after sync stage as syncing enables us to have a release tag.
179 """
180 # Extract version we have decided to build into self.release_tag.
181 manifest_manager = stages.ManifestVersionedSyncStage.manifest_manager
182 if manifest_manager:
183 self.release_tag = manifest_manager.current_version
184
185 def _RunStage(self, stage, *args, **kwargs):
Matt Tennant759e2352013-09-27 15:14:44 -0700186 """Wrapper to run a stage.
187
188 Args:
189 stage: A BuilderStage class.
190 args: args to pass to stage constructor.
191 kwargs: kwargs to pass to stage constructor.
192 Returns:
193
194 Whatever the stage's Run method returns.
195 """
Brian Harring3fec5a82012-03-01 05:57:03 -0800196 stage_instance = self._GetStageInstance(stage, *args, **kwargs)
197 return stage_instance.Run()
198
199 def GetSyncInstance(self):
200 """Returns an instance of a SyncStage that should be run.
201
202 Subclasses must override this method.
203 """
204 raise NotImplementedError()
205
Aviv Keshet5c39b6a2013-10-07 15:44:54 -0400206 def GetCompletionInstance(self):
207 """Returns the LKGMCandidateSyncCompletionStage for this build.
208
209 Subclasses may override this method.
210
211 Returns: None
212 """
213 return None
214
Brian Harring3fec5a82012-03-01 05:57:03 -0800215 def RunStages(self):
216 """Subclasses must override this method. Runs the appropriate code."""
217 raise NotImplementedError()
218
Brian Harring3fec5a82012-03-01 05:57:03 -0800219 def _ShouldReExecuteInBuildRoot(self):
220 """Returns True if this build should be re-executed in the buildroot."""
Ryan Cui88b901c2013-06-21 11:35:30 -0700221 # The commandline --noreexec flag can override the config.
222 if not (self.options.postsync_reexec and
223 self.build_config['postsync_reexec']):
224 return False
225
Brian Harring3fec5a82012-03-01 05:57:03 -0800226 abs_buildroot = os.path.abspath(self.options.buildroot)
227 return not os.path.abspath(__file__).startswith(abs_buildroot)
228
229 def _ReExecuteInBuildroot(self, sync_instance):
230 """Reexecutes self in buildroot and returns True if build succeeds.
231
232 This allows the buildbot code to test itself when changes are patched for
233 buildbot-related code. This is a no-op if the buildroot == buildroot
234 of the running chromite checkout.
235
236 Args:
237 sync_instance: Instance of the sync stage that was run to sync.
238
239 Returns:
240 True if the Build succeeded.
241 """
Brian Harring3fec5a82012-03-01 05:57:03 -0800242 if not self.options.resume:
Ryan Cuif7f24692012-05-18 16:35:33 -0700243 results_lib.WriteCheckpoint(self.options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800244
Ryan Cui1c13a252012-10-16 15:00:16 -0700245 args = stages.BootstrapStage.FilterArgsForTargetCbuildbot(
246 self.options.buildroot, constants.PATH_TO_CBUILDBOT, self.options)
Brian Harring37e559b2012-05-22 20:47:32 -0700247
David James2333c182013-02-13 16:16:15 -0800248 # Specify a buildroot explicitly (just in case, for local trybot).
Brian Harring3fec5a82012-03-01 05:57:03 -0800249 # Suppress any timeout options given from the commandline in the
250 # invoked cbuildbot; our timeout will enforce it instead.
Ryan Cui1c13a252012-10-16 15:00:16 -0700251 args += ['--resume', '--timeout', '0', '--notee', '--nocgroups',
252 '--buildroot', os.path.abspath(self.options.buildroot)]
Brian Harringae0a5322012-09-15 01:46:51 -0700253
Brian Harring3fec5a82012-03-01 05:57:03 -0800254 if stages.ManifestVersionedSyncStage.manifest_manager:
255 ver = stages.ManifestVersionedSyncStage.manifest_manager.current_version
Ryan Cui1c13a252012-10-16 15:00:16 -0700256 args += ['--version', ver]
Brian Harring3fec5a82012-03-01 05:57:03 -0800257
David Jamesf421c6d2013-04-11 15:37:57 -0700258 pool = getattr(sync_instance, 'pool', None)
259 if pool:
260 filename = os.path.join(self.options.buildroot, 'validation_pool.dump')
261 pool.Save(filename)
262 args += ['--validation_pool', filename]
Brian Harring3fec5a82012-03-01 05:57:03 -0800263
David Jamesac8c2a72013-02-13 18:44:33 -0800264 # Reset the cache dir so that the child will calculate it automatically.
265 if not self.options.cache_dir_specified:
266 commandline.BaseParser.ConfigureCacheDir(None)
267
Brian Harring3fec5a82012-03-01 05:57:03 -0800268 # Re-run the command in the buildroot.
269 # Finally, be generous and give the invoked cbuildbot 30s to shutdown
270 # when something occurs. It should exit quicker, but the sigterm may
271 # hit while the system is particularly busy.
Brian Harring1b8c4c82012-05-29 23:03:04 -0700272 return_obj = cros_build_lib.RunCommand(
Ryan Cui1c13a252012-10-16 15:00:16 -0700273 args, cwd=self.options.buildroot, error_code_ok=True, kill_timeout=30)
Brian Harring3fec5a82012-03-01 05:57:03 -0800274 return return_obj.returncode == 0
275
Ryan Cuif7f24692012-05-18 16:35:33 -0700276 def _InitializeTrybotPatchPool(self):
277 """Generate patch pool from patches specified on the command line.
278
279 Do this only if we need to patch changes later on.
280 """
281 changes_stage = stages.PatchChangesStage.StageNamePrefix()
282 check_func = results_lib.Results.PreviouslyCompletedRecord
283 if not check_func(changes_stage) or self.options.bootstrap:
Ryan Cuie1e4e662012-05-21 16:39:46 -0700284 self.patch_pool = AcquirePoolFromOptions(self.options)
Ryan Cuif7f24692012-05-18 16:35:33 -0700285
286 def _GetBootstrapStage(self):
287 """Constructs and returns the BootStrapStage object.
288
289 We return None when there are no chromite patches to test, and
290 --test-bootstrap wasn't passed in.
291 """
292 stage = None
293 chromite_pool = self.patch_pool.Filter(project=constants.CHROMITE_PROJECT)
Ryan Cui5616a512012-08-17 13:39:36 -0700294 manifest_pool = self.patch_pool.FilterManifest()
David James97d95872012-11-16 15:09:56 -0800295 chromite_branch = git.GetChromiteTrackingBranch()
Ryan Cui5616a512012-08-17 13:39:36 -0700296 if (chromite_pool or manifest_pool or self.options.test_bootstrap
Ryan Cuie1e4e662012-05-21 16:39:46 -0700297 or chromite_branch != self.options.branch):
Ryan Cuif7f24692012-05-18 16:35:33 -0700298 stage = stages.BootstrapStage(self.options, self.build_config,
Ryan Cui5616a512012-08-17 13:39:36 -0700299 chromite_pool, manifest_pool)
Ryan Cuif7f24692012-05-18 16:35:33 -0700300 return stage
301
Brian Harring3fec5a82012-03-01 05:57:03 -0800302 def Run(self):
Ryan Cuif7f24692012-05-18 16:35:33 -0700303 """Main runner for this builder class. Runs build and prints summary.
304
305 Returns:
306 Whether the build succeeded.
307 """
308 self._InitializeTrybotPatchPool()
309
310 if self.options.bootstrap:
311 bootstrap_stage = self._GetBootstrapStage()
312 if bootstrap_stage:
313 # BootstrapStage blocks on re-execution of cbuildbot.
314 bootstrap_stage.Run()
315 return bootstrap_stage.returncode == 0
316
Brian Harring3fec5a82012-03-01 05:57:03 -0800317 print_report = True
David James3d4d3502012-04-09 15:12:06 -0700318 exception_thrown = False
Brian Harring3fec5a82012-03-01 05:57:03 -0800319 success = True
David James9ebb2a42013-08-13 20:29:57 -0700320 sync_instance = None
Brian Harring3fec5a82012-03-01 05:57:03 -0800321 try:
322 self.Initialize()
323 sync_instance = self.GetSyncInstance()
324 sync_instance.Run()
325 self._SetReleaseTag()
326
Ryan Cui88b901c2013-06-21 11:35:30 -0700327 if self.options.postsync_patch and self.build_config['postsync_patch']:
328 # Filter out patches to manifest, since PatchChangesStage can't handle
329 # them. Manifest patches are patched in the BootstrapStage.
330 non_manifest_patches = self.patch_pool.FilterManifest(negate=True)
331 if non_manifest_patches:
332 self._RunStage(stages.PatchChangesStage, non_manifest_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800333
334 if self._ShouldReExecuteInBuildRoot():
335 print_report = False
336 success = self._ReExecuteInBuildroot(sync_instance)
337 else:
338 self.RunStages()
Matt Tennant759e2352013-09-27 15:14:44 -0700339
David James3541a132013-03-18 13:21:58 -0700340 except Exception as ex:
341 # If the build is marked as successful, but threw exceptions, that's a
342 # problem.
David James7fbf2d42012-07-14 18:23:49 -0700343 exception_thrown = True
David James3541a132013-03-18 13:21:58 -0700344 if results_lib.Results.BuildSucceededSoFar():
345 traceback.print_exc(file=sys.stdout)
David James7fbf2d42012-07-14 18:23:49 -0700346 raise
Matt Tennant759e2352013-09-27 15:14:44 -0700347
David James3541a132013-03-18 13:21:58 -0700348 if not (print_report and isinstance(ex, results_lib.StepFailure)):
349 raise
Matt Tennant759e2352013-09-27 15:14:44 -0700350
Brian Harring3fec5a82012-03-01 05:57:03 -0800351 finally:
352 if print_report:
Ryan Cuif7f24692012-05-18 16:35:33 -0700353 results_lib.WriteCheckpoint(self.options.buildroot)
Aviv Keshet5c39b6a2013-10-07 15:44:54 -0400354 completion_instance = self.GetCompletionInstance()
Mike Frysinger9b223362013-03-04 21:54:26 -0500355 self._RunStage(stages.ReportStage, self.archive_stages,
Aviv Keshet5c39b6a2013-10-07 15:44:54 -0400356 self.release_tag, sync_instance, completion_instance)
Brian Harring3fec5a82012-03-01 05:57:03 -0800357 success = results_lib.Results.BuildSucceededSoFar()
David James3d4d3502012-04-09 15:12:06 -0700358 if exception_thrown and success:
359 success = False
David Jamesbb20ac82012-07-18 10:59:16 -0700360 cros_build_lib.PrintBuildbotStepWarnings()
361 print """\
David James3d4d3502012-04-09 15:12:06 -0700362Exception thrown, but all stages marked successful. This is an internal error,
363because the stage that threw the exception should be marked as failing."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800364
365 return success
366
367
David James1fddb8f2013-04-25 15:23:07 -0700368BoardConfig = collections.namedtuple('BoardConfig', ['board', 'name'])
369
370
Brian Harring3fec5a82012-03-01 05:57:03 -0800371class SimpleBuilder(Builder):
372 """Builder that performs basic vetting operations."""
373
374 def GetSyncInstance(self):
375 """Sync to lkgm or TOT as necessary.
376
Matt Tennant759e2352013-09-27 15:14:44 -0700377 Returns: the instance of the sync stage to run.
Brian Harring3fec5a82012-03-01 05:57:03 -0800378 """
Ryan Cui88b901c2013-06-21 11:35:30 -0700379 if self.options.force_version:
380 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
381 elif self.build_config['use_lkgm']:
Brian Harring3fec5a82012-03-01 05:57:03 -0800382 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
Chris Sosa52a81b62012-11-14 06:12:54 -0800383 elif self.build_config['use_chrome_lkgm']:
384 sync_stage = self._GetStageInstance(stages.ChromeLKGMSyncStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800385 else:
386 sync_stage = self._GetStageInstance(stages.SyncStage)
387
388 return sync_stage
389
David James4f2d8302013-03-19 06:35:58 -0700390 @staticmethod
391 def _RunParallelStages(stage_objs):
Matt Tennant759e2352013-09-27 15:14:44 -0700392 """Run the specified stages in parallel.
393
394 Args:
395 stage_objs: BuilderStage objects.
396 """
David James4f2d8302013-03-19 06:35:58 -0700397 steps = [stage.Run for stage in stage_objs]
398 try:
399 parallel.RunParallelSteps(steps)
400 except BaseException as ex:
401 # If a stage threw an exception, it might not have correctly reported
402 # results (e.g. because it was killed before it could report the
403 # results.) In this case, attribute the exception to any stages that
404 # didn't report back correctly (if any).
405 for stage in stage_objs:
David James6b704242013-10-18 14:51:37 -0700406 for name in stage.GetStageNames():
407 if not results_lib.Results.StageHasResults(name):
408 results_lib.Results.Record(name, ex, str(ex))
Matt Tennant759e2352013-09-27 15:14:44 -0700409
David James4f2d8302013-03-19 06:35:58 -0700410 raise
411
David James1fddb8f2013-04-25 15:23:07 -0700412 def _RunBackgroundStagesForBoard(self, config, board, compilecheck):
Matt Tennant759e2352013-09-27 15:14:44 -0700413 """Run background board-specific stages for the specified board.
414
415 Args:
416 config: Build config dict.
417 board: Board name.
418 compilecheck: Boolean. If True, run only the compile steps.
419 """
David James1fddb8f2013-04-25 15:23:07 -0700420 archive_stage = self.archive_stages[BoardConfig(board, config['name'])]
421 if config['pgo_generate']:
Ahmad Sharifa2db40a2013-07-22 13:51:52 -0400422 self._RunParallelStages([archive_stage])
David James1fddb8f2013-04-25 15:23:07 -0700423 return
Matt Tennant759e2352013-09-27 15:14:44 -0700424
David James565bc9a2013-04-08 14:54:45 -0700425 if compilecheck:
426 self._RunStage(stages.BuildPackagesStage, board, archive_stage,
427 config=config)
428 self._RunStage(stages.UnitTestStage, board, config=config)
429 return
Matt Tennant759e2352013-09-27 15:14:44 -0700430
Ryan Cui3ea98e02013-08-07 16:01:48 -0700431 stage_list = []
432 if self.options.chrome_sdk and self.build_config['chrome_sdk']:
433 stage_list.append([stages.ChromeSDKStage, board, archive_stage])
David James6b704242013-10-18 14:51:37 -0700434 stage_list += [
435 [stages.RetryStage, 1, stages.VMTestStage, board, archive_stage],
436 [stages.SignerTestStage, board, archive_stage],
437 [stages.UnitTestStage, board],
438 [stages.UploadPrebuiltsStage, board, archive_stage],
439 [stages.DevInstallerPrebuiltsStage, board, archive_stage]
440 ]
Brian Harring3fec5a82012-03-01 05:57:03 -0800441
David James58e0c092012-03-04 20:31:12 -0800442 # We can not run hw tests without archiving the payloads.
443 if self.options.archive:
Chris Sosaba250522013-03-27 18:57:34 -0700444 for suite_config in config['hw_tests']:
445 if suite_config.async:
446 stage_list.append([stages.ASyncHWTestStage, board, archive_stage,
447 suite_config])
448 elif suite_config.suite == constants.HWTEST_AU_SUITE:
449 stage_list.append([stages.AUTestStage, board, archive_stage,
450 suite_config])
Aviv Keshet23efd042013-10-01 13:59:08 -0700451 elif suite_config.suite == constants.HWTEST_QAV_SUITE:
452 stage_list.append([stages.QATestStage, board,
453 archive_stage, suite_config])
Chris Sosa077df812013-01-25 17:05:28 -0800454 else:
Chris Sosaba250522013-03-27 18:57:34 -0700455 stage_list.append([stages.HWTestStage, board, archive_stage,
456 suite_config])
Chris Sosa817b1f92012-07-19 15:00:23 -0700457
David James4f2d8302013-03-19 06:35:58 -0700458 stage_objs = [self._GetStageInstance(*x, config=config) for x in stage_list]
459 self._RunParallelStages(stage_objs + [archive_stage])
Brian Harring3fec5a82012-03-01 05:57:03 -0800460
Aviv Keshet7dc300f2013-10-11 12:57:49 -0400461 def _RunChrootBuilderTypeBuild(self):
462 """Runs through stages of a CHROOT_BUILDER_TYPE build."""
463 self._RunStage(stages.UprevStage, boards=[], enter_chroot=False)
464 self._RunStage(stages.InitSDKStage)
465 self._RunStage(stages.SetupBoardStage, [constants.CHROOT_BUILDER_BOARD])
466 self._RunStage(stages.SyncChromeStage)
467 self._RunStage(stages.PatchChromeStage)
468 self._RunStage(stages.SDKPackageStage)
469 self._RunStage(stages.SDKTestStage)
470 self._RunStage(stages.UploadPrebuiltsStage,
471 constants.CHROOT_BUILDER_BOARD, None)
472
473 def _RunRefreshPackagesTypeBuild(self):
474 """Runs through the stages of a REFRESH_PACKAGES_TYPE build."""
475 self._RunStage(stages.InitSDKStage)
476 self._RunStage(stages.SetupBoardStage)
477 self._RunStage(stages.RefreshPackageStatusStage)
478
479 def _RunDefaultTypeBuild(self):
480 """Runs through the stages of a non-special-type build."""
481 self._RunStage(stages.InitSDKStage)
482 self._RunStage(stages.UprevStage)
483 self._RunStage(stages.SetupBoardStage)
484
485 # We need a handle to this stage to extract info from it.
486 # TODO(mtennant): Just have _RunStage return the stage object, since
487 # nothing uses the return value of _RunStage now, and the Run method
488 # of stage objects does not appear to return anything, either.
489 sync_chrome_stage = self._GetStageInstance(stages.SyncChromeStage)
490 sync_chrome_stage.Run()
491 self._RunStage(stages.PatchChromeStage)
492
493 # Prepare stages to run in background.
494 configs = self.build_config['child_configs'] or [self.build_config]
495 tasks = []
496 for config in configs:
497 for board in config['boards']:
498 archive_stage = self._GetStageInstance(
499 stages.ArchiveStage, board, self.release_tag, config=config,
500 chrome_version=sync_chrome_stage.chrome_version)
501 board_config = BoardConfig(board, config['name'])
502 self.archive_stages[board_config] = archive_stage
503 tasks.append((config, board, archive_stage))
504
505 # Set up a process pool to run test/archive stages in the background.
506 # This process runs task(board) for each board added to the queue.
507 task_runner = self._RunBackgroundStagesForBoard
508 with parallel.BackgroundTaskRunner(task_runner) as queue:
509 for config, board, archive_stage in tasks:
510 compilecheck = config['compilecheck'] or self.options.compilecheck
511 if not compilecheck:
512 # Run BuildPackages and BuildImage in the foreground, generating
513 # or using PGO data if requested.
514 kwargs = {'archive_stage': archive_stage, 'config': config}
515 if config['pgo_generate']:
516 kwargs['pgo_generate'] = True
517 elif config['pgo_use']:
518 kwargs['pgo_use'] = True
519
520 self._RunStage(stages.BuildPackagesStage, board, **kwargs)
521 self._RunStage(stages.BuildImageStage, board, **kwargs)
522
523 if config['pgo_generate']:
524 suite = cbuildbot_config.PGORecordTest()
525 self._RunStage(stages.HWTestStage, board, archive_stage, suite,
526 config=config)
527
528 # Kick off our background stages.
529 queue.put([config, board, compilecheck])
530
Brian Harring3fec5a82012-03-01 05:57:03 -0800531 def RunStages(self):
532 """Runs through build process."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800533 # TODO(sosa): Split these out into classes.
David James816a5942013-04-11 22:59:32 -0700534 if self.build_config['build_type'] == constants.PRE_CQ_LAUNCHER_TYPE:
535 self._RunStage(stages.PreCQLauncherStage)
Ryan Cui88b901c2013-06-21 11:35:30 -0700536 elif self.build_config['build_type'] == constants.CREATE_BRANCH_TYPE:
537 self._RunStage(stages.BranchUtilStage)
David James816a5942013-04-11 22:59:32 -0700538 elif self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
Aviv Keshet7dc300f2013-10-11 12:57:49 -0400539 self._RunChrootBuilderTypeBuild()
Brian Harring3fec5a82012-03-01 05:57:03 -0800540 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
Aviv Keshet7dc300f2013-10-11 12:57:49 -0400541 self._RunRefreshPackagesTypeBuild()
Brian Harring3fec5a82012-03-01 05:57:03 -0800542 else:
Aviv Keshet7dc300f2013-10-11 12:57:49 -0400543 self._RunDefaultTypeBuild()
David James58e0c092012-03-04 20:31:12 -0800544
Brian Harring3fec5a82012-03-01 05:57:03 -0800545
546class DistributedBuilder(SimpleBuilder):
547 """Build class that has special logic to handle distributed builds.
548
549 These builds sync using git/manifest logic in manifest_versions. In general
550 they use a non-distributed builder code for the bulk of the work.
551 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700552 def __init__(self, *args, **kwargs):
Brian Harring3fec5a82012-03-01 05:57:03 -0800553 """Initializes a buildbot builder.
554
555 Extra variables:
556 completion_stage_class: Stage used to complete a build. Set in the Sync
557 stage.
558 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700559 super(DistributedBuilder, self).__init__(*args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800560 self.completion_stage_class = None
David Jamesf421c6d2013-04-11 15:37:57 -0700561 self.sync_stage = None
Aviv Keshet5c39b6a2013-10-07 15:44:54 -0400562 self._completion_stage = None
Brian Harring3fec5a82012-03-01 05:57:03 -0800563
564 def GetSyncInstance(self):
565 """Syncs the tree using one of the distributed sync logic paths.
566
Matt Tennant759e2352013-09-27 15:14:44 -0700567 Returns: the instance of the sync stage to run.
Brian Harring3fec5a82012-03-01 05:57:03 -0800568 """
569 # Determine sync class to use. CQ overrides PFQ bits so should check it
570 # first.
David Jamesf421c6d2013-04-11 15:37:57 -0700571 if self.build_config['pre_cq'] or self.options.pre_cq:
572 sync_stage = self._GetStageInstance(stages.PreCQSyncStage,
573 self.patch_pool.gerrit_patches)
574 self.completion_stage_class = stages.PreCQCompletionStage
575 self.patch_pool.gerrit_patches = []
576 elif cbuildbot_config.IsCQType(self.build_config['build_type']):
Brian Harring3fec5a82012-03-01 05:57:03 -0800577 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
578 self.completion_stage_class = stages.CommitQueueCompletionStage
579 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
580 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
581 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
582 else:
583 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
584 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
585
David Jamesf421c6d2013-04-11 15:37:57 -0700586 self.sync_stage = sync_stage
587 return self.sync_stage
Brian Harring3fec5a82012-03-01 05:57:03 -0800588
Aviv Keshet5c39b6a2013-10-07 15:44:54 -0400589 def GetCompletionInstance(self):
590 """Returns the completion_stage_class instance that was used for this build.
591
592 Returns None if the completion_stage instance was not yet created (this
593 occurs during Publish).
594 """
595 return self._completion_stage
596
Brian Harring3fec5a82012-03-01 05:57:03 -0800597 def Publish(self, was_build_successful):
598 """Completes build by publishing any required information."""
599 completion_stage = self._GetStageInstance(self.completion_stage_class,
David Jamesf421c6d2013-04-11 15:37:57 -0700600 self.sync_stage,
Brian Harring3fec5a82012-03-01 05:57:03 -0800601 was_build_successful)
Aviv Keshet5c39b6a2013-10-07 15:44:54 -0400602 self._completion_stage = completion_stage
David James11fd7e82013-10-23 20:02:16 -0700603 completion_successful = False
604 try:
605 completion_stage.Run()
606 completion_successful = True
607 finally:
608 if not completion_successful:
609 was_build_successful = False
610 if self.build_config['push_overlays']:
611 self._RunStage(stages.PublishUprevChangesStage, was_build_successful)
Brian Harring3fec5a82012-03-01 05:57:03 -0800612
613 def RunStages(self):
614 """Runs simple builder logic and publishes information to overlays."""
615 was_build_successful = False
David James843ed252013-09-11 16:18:10 -0700616 try:
617 super(DistributedBuilder, self).RunStages()
618 was_build_successful = results_lib.Results.BuildSucceededSoFar()
619 except SystemExit as ex:
620 # If a stage calls sys.exit(0), it's exiting with success, so that means
621 # we should mark ourselves as successful.
622 if ex.code == 0:
623 was_build_successful = True
624 raise
625 finally:
626 self.Publish(was_build_successful)
Brian Harring3fec5a82012-03-01 05:57:03 -0800627
Brian Harring3fec5a82012-03-01 05:57:03 -0800628
629def _ConfirmBuildRoot(buildroot):
630 """Confirm with user the inferred buildroot, and mark it as confirmed."""
Brian Harring521e7242012-11-01 16:57:42 -0700631 cros_build_lib.Warning('Using default directory %s as buildroot', buildroot)
632 if not cros_build_lib.BooleanPrompt(default=False):
633 print('Please specify a different buildroot via the --buildroot option.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800634 sys.exit(0)
635
636 if not os.path.exists(buildroot):
637 os.mkdir(buildroot)
638
639 repository.CreateTrybotMarker(buildroot)
640
641
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700642def _ConfirmRemoteBuildbotRun():
643 """Confirm user wants to run with --buildbot --remote."""
Brian Harring521e7242012-11-01 16:57:42 -0700644 cros_build_lib.Warning(
645 'You are about to launch a PRODUCTION job! This is *NOT* a '
646 'trybot run! Are you sure?')
647 if not cros_build_lib.BooleanPrompt(default=False):
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700648 print('Please specify --pass-through="--debug".')
649 sys.exit(0)
650
651
Ryan Cui5ba7e152012-05-10 14:36:52 -0700652def _DetermineDefaultBuildRoot(sourceroot, internal_build):
Brian Harring3fec5a82012-03-01 05:57:03 -0800653 """Default buildroot to be under the directory that contains current checkout.
654
655 Arguments:
656 internal_build: Whether the build is an internal build
Ryan Cui5ba7e152012-05-10 14:36:52 -0700657 sourceroot: Use specified sourceroot.
Brian Harring3fec5a82012-03-01 05:57:03 -0800658 """
Ryan Cui5ba7e152012-05-10 14:36:52 -0700659 if not repository.IsARepoRoot(sourceroot):
Brian Harring1b8c4c82012-05-29 23:03:04 -0700660 cros_build_lib.Die(
661 'Could not find root of local checkout at %s. Please specify '
662 'using the --sourceroot option.' % sourceroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800663
664 # Place trybot buildroot under the directory containing current checkout.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700665 top_level = os.path.dirname(os.path.realpath(sourceroot))
Brian Harring3fec5a82012-03-01 05:57:03 -0800666 if internal_build:
667 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
668 else:
669 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
670
671 return buildroot
672
673
Mike Frysinger6903c762012-12-04 01:57:16 -0500674def _DisableYamaHardLinkChecks():
675 """Disable Yama kernel hardlink security checks.
676
677 The security module disables hardlinking to files you do not have
678 write access to which causes some of our build scripts problems.
679 Disable it so we don't have to worry about it.
680 """
681 PROC_PATH = '/proc/sys/kernel/yama/protected_nonaccess_hardlinks'
682 SYSCTL_PATH = PROC_PATH[len('/proc/sys/'):].replace('/', '.')
683
684 # Yama not available in this system -- nothing to do.
685 if not os.path.exists(PROC_PATH):
686 return
687
688 # Already disabled -- nothing to do.
689 if osutils.ReadFile(PROC_PATH).strip() == '0':
690 return
691
692 # Create a hardlink in a tempdir and see if we get back EPERM.
David James4bc13702013-03-26 08:08:04 -0700693 with osutils.TempDir() as tempdir:
Mike Frysinger6903c762012-12-04 01:57:16 -0500694 try:
695 os.link('/bin/sh', os.path.join(tempdir, 'sh'))
696 except OSError as e:
697 if e.errno == errno.EPERM:
698 cros_build_lib.Warning('Disabling Yama hardlink security')
699 cros_build_lib.SudoRunCommand(['sysctl', '%s=0' % SYSCTL_PATH])
700
701
Brian Harring3fec5a82012-03-01 05:57:03 -0800702def _BackupPreviousLog(log_file, backup_limit=25):
703 """Rename previous log.
704
705 Args:
706 log_file: The absolute path to the previous log.
707 """
708 if os.path.exists(log_file):
709 old_logs = sorted(glob.glob(log_file + '.*'),
710 key=distutils.version.LooseVersion)
711
712 if len(old_logs) >= backup_limit:
713 os.remove(old_logs[0])
714
715 last = 0
716 if old_logs:
717 last = int(old_logs.pop().rpartition('.')[2])
718
719 os.rename(log_file, log_file + '.' + str(last + 1))
720
Ryan Cui5616a512012-08-17 13:39:36 -0700721
David James944a48e2012-03-07 12:19:03 -0800722def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800723 """Helper function that wraps RunBuildStages()."""
724 def IsDistributedBuilder():
725 """Determines whether the build_config should be a DistributedBuilder."""
David Jamesf421c6d2013-04-11 15:37:57 -0700726 if build_config['pre_cq'] or options.pre_cq:
727 return True
728 elif not options.buildbot:
Brian Harring3fec5a82012-03-01 05:57:03 -0800729 return False
730 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
Brian Harring3fec5a82012-03-01 05:57:03 -0800731 # We don't do distributed logic to TOT Chrome PFQ's, nor local
732 # chrome roots (e.g. chrome try bots)
733 if chrome_rev not in [constants.CHROME_REV_TOT,
734 constants.CHROME_REV_LOCAL,
735 constants.CHROME_REV_SPEC]:
736 return True
737
738 return False
739
Brian Harring1b8c4c82012-05-29 23:03:04 -0700740 cros_build_lib.Info("cbuildbot executed with args %s"
741 % ' '.join(map(repr, sys.argv)))
Brian Harring3fec5a82012-03-01 05:57:03 -0800742
David Jamesa0a664e2013-02-13 09:52:01 -0800743 chrome_rev = build_config['chrome_rev']
744 if options.chrome_rev:
745 chrome_rev = options.chrome_rev
746 if chrome_rev == constants.CHROME_REV_TOT:
747 # Build the TOT Chrome revision.
748 svn_url = gclient.GetBaseURLs()[0]
749 options.chrome_version = gclient.GetTipOfTrunkSvnRevision(svn_url)
750 options.chrome_rev = constants.CHROME_REV_SPEC
751
David James4a404a52013-02-19 13:07:59 -0800752 # If it's likely we'll need to build Chrome, fetch the source.
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500753 if build_config['sync_chrome'] is None:
754 options.managed_chrome = (chrome_rev != constants.CHROME_REV_LOCAL and
755 (not build_config['usepkg_build_packages'] or chrome_rev or
David James3cce4642013-05-10 17:50:23 -0700756 build_config['profile'] or options.rietveld_patches))
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500757 else:
758 options.managed_chrome = build_config['sync_chrome']
David James2333c182013-02-13 16:16:15 -0800759
760 if options.managed_chrome:
761 # Tell Chrome to fetch the source locally.
762 internal = constants.USE_CHROME_INTERNAL in (build_config['useflags'] or [])
763 chrome_src = 'chrome-src-internal' if internal else 'chrome-src'
764 options.chrome_root = os.path.join(options.cache_dir, 'distfiles', 'target',
765 chrome_src)
David James9e27e662013-02-14 13:42:43 -0800766 elif options.rietveld_patches:
David James4a404a52013-02-19 13:07:59 -0800767 cros_build_lib.Die('This builder does not support Rietveld patches.')
David James2333c182013-02-13 16:16:15 -0800768
Ryan Cuif7f24692012-05-18 16:35:33 -0700769 target = DistributedBuilder if IsDistributedBuilder() else SimpleBuilder
Ryan Cuie1e4e662012-05-21 16:39:46 -0700770 buildbot = target(options, build_config)
Brian Harringd166aaf2012-05-14 18:31:53 -0700771 if not buildbot.Run():
772 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800773
774
775# Parser related functions
Ryan Cui5ba7e152012-05-10 14:36:52 -0700776def _CheckLocalPatches(sourceroot, local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800777 """Do an early quick check of the passed-in patches.
778
779 If the branch of a project is not specified we append the current branch the
780 project is on.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700781
782 Args:
783 sourceroot: The checkout where patches are coming from.
Brian Harring3fec5a82012-03-01 05:57:03 -0800784 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700785 verified_patches = []
David James97d95872012-11-16 15:09:56 -0800786 manifest = git.ManifestCheckout.Cached(sourceroot)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700787 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800788 components = patch.split(':')
789 if len(components) > 2:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700790 cros_build_lib.Die(
791 'Specify local patches in project[:branch] format. Got %s' % patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800792
793 # validate project
794 project = components[0]
Brian Harring3fec5a82012-03-01 05:57:03 -0800795
Brian Harring609dc4e2012-05-07 02:17:44 -0700796 try:
797 project_dir = manifest.GetProjectPath(project, True)
798 except KeyError:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700799 cros_build_lib.Die('Project %s does not exist.' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800800
801 # If no branch was specified, we use the project's current branch.
802 if len(components) == 1:
David James97d95872012-11-16 15:09:56 -0800803 branch = git.GetCurrentBranch(project_dir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800804 if not branch:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700805 cros_build_lib.Die('Project %s is not on a branch!' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800806 else:
807 branch = components[1]
David James97d95872012-11-16 15:09:56 -0800808 if not git.DoesLocalBranchExist(project_dir, branch):
Brian Harring1b8c4c82012-05-29 23:03:04 -0700809 cros_build_lib.Die('Project %s does not have branch %s'
810 % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800811
Brian Harring609dc4e2012-05-07 02:17:44 -0700812 verified_patches.append('%s:%s' % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800813
Ryan Cuicedd8a52012-03-22 02:28:35 -0700814 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800815
816
Brian Harring3fec5a82012-03-01 05:57:03 -0800817def _CheckChromeVersionOption(_option, _opt_str, value, parser):
818 """Upgrade other options based on chrome_version being passed."""
819 value = value.strip()
820
821 if parser.values.chrome_rev is None and value:
822 parser.values.chrome_rev = constants.CHROME_REV_SPEC
823
824 parser.values.chrome_version = value
825
826
827def _CheckChromeRootOption(_option, _opt_str, value, parser):
828 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800829 if parser.values.chrome_rev is None:
830 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
831
Ryan Cui5ba7e152012-05-10 14:36:52 -0700832 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800833
834
835def _CheckChromeRevOption(_option, _opt_str, value, parser):
836 """Validate the chrome_rev option."""
837 value = value.strip()
838 if value not in constants.VALID_CHROME_REVISIONS:
839 raise optparse.OptionValueError('Invalid chrome rev specified')
840
841 parser.values.chrome_rev = value
842
843
David Jamesac8c2a72013-02-13 18:44:33 -0800844def FindCacheDir(_parser, _options):
Brian Harringae0a5322012-09-15 01:46:51 -0700845 return None
846
847
Ryan Cui5ba7e152012-05-10 14:36:52 -0700848class CustomGroup(optparse.OptionGroup):
849 def add_remote_option(self, *args, **kwargs):
850 """For arguments that are passed-through to remote trybot."""
851 return optparse.OptionGroup.add_option(self, *args,
852 remote_pass_through=True,
853 **kwargs)
854
855
Ryan Cui1c13a252012-10-16 15:00:16 -0700856class CustomOption(commandline.FilteringOption):
857 """Subclass FilteringOption class to implement pass-through and api."""
Ryan Cui5ba7e152012-05-10 14:36:52 -0700858
Ryan Cui1c13a252012-10-16 15:00:16 -0700859 ACTIONS = commandline.FilteringOption.ACTIONS + ('extend',)
860 STORE_ACTIONS = commandline.FilteringOption.STORE_ACTIONS + ('extend',)
861 TYPED_ACTIONS = commandline.FilteringOption.TYPED_ACTIONS + ('extend',)
862 ALWAYS_TYPED_ACTIONS = (commandline.FilteringOption.ALWAYS_TYPED_ACTIONS +
863 ('extend',))
Ryan Cui79319ab2012-05-21 12:59:18 -0700864
Ryan Cui5ba7e152012-05-10 14:36:52 -0700865 def __init__(self, *args, **kwargs):
866 # The remote_pass_through argument specifies whether we should directly
867 # pass the argument (with its value) onto the remote trybot.
868 self.pass_through = kwargs.pop('remote_pass_through', False)
Ryan Cui1c13a252012-10-16 15:00:16 -0700869 self.api_version = int(kwargs.pop('api', '0'))
870 commandline.FilteringOption.__init__(self, *args, **kwargs)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700871
872 def take_action(self, action, dest, opt, value, values, parser):
Ryan Cui79319ab2012-05-21 12:59:18 -0700873 if action == 'extend':
Mike Frysingerd6925b52012-07-16 16:11:00 -0400874 # If there is extra spaces between each argument, we get '' which later
875 # code barfs on, so skip those. e.g. We see this with the forms:
876 # cbuildbot -p 'proj:branch ' ...
877 # cbuildbot -p ' proj:branch' ...
878 # cbuildbot -p 'proj:branch proj2:branch' ...
879 lvalue = value.split()
Ryan Cui79319ab2012-05-21 12:59:18 -0700880 values.ensure_value(dest, []).extend(lvalue)
Ryan Cui79319ab2012-05-21 12:59:18 -0700881
Ryan Cui1c13a252012-10-16 15:00:16 -0700882 commandline.FilteringOption.take_action(
883 self, action, dest, opt, value, values, parser)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700884
885
Ryan Cui1c13a252012-10-16 15:00:16 -0700886class CustomParser(commandline.FilteringParser):
Brian Harringb6cf9142012-09-01 20:43:17 -0700887
888 DEFAULT_OPTION_CLASS = CustomOption
889
890 def add_remote_option(self, *args, **kwargs):
891 """For arguments that are passed-through to remote trybot."""
Ryan Cui1c13a252012-10-16 15:00:16 -0700892 return self.add_option(*args, remote_pass_through=True, **kwargs)
Brian Harringb6cf9142012-09-01 20:43:17 -0700893
894
Brian Harring3fec5a82012-03-01 05:57:03 -0800895def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700896 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800897 # Parse options
898 usage = "usage: %prog [options] buildbot_config"
Brian Harringae0a5322012-09-15 01:46:51 -0700899 parser = CustomParser(usage=usage, caching=FindCacheDir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800900
901 # Main options
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400902 parser.add_option('-l', '--list', action='store_true', dest='list',
903 default=False,
904 help='List the suggested trybot configs to use (see --all)')
Brian Harring3fec5a82012-03-01 05:57:03 -0800905 parser.add_option('-a', '--all', action='store_true', dest='print_all',
906 default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400907 help='List all of the buildbot configs available w/--list')
908
909 parser.add_option('--local', default=False, action='store_true',
Ryan Cui88b901c2013-06-21 11:35:30 -0700910 help='Specifies that this tryjob should be run locally. '
911 'Implies --debug.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400912 parser.add_option('--remote', default=False, action='store_true',
Ryan Cui88b901c2013-06-21 11:35:30 -0700913 help='Specifies that this tryjob should be run remotely.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400914
Ryan Cuie1e4e662012-05-21 16:39:46 -0700915 parser.add_remote_option('-b', '--branch',
916 help='The manifest branch to test. The branch to '
917 'check the buildroot out to.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700918 parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700919 help='Root directory where source is checked out to, and '
920 'where the build occurs. For external build configs, '
921 "defaults to 'trybot' directory at top level of your "
922 'repo-managed checkout.')
923 parser.add_remote_option('--chrome_rev', default=None, type='string',
924 action='callback', dest='chrome_rev',
925 callback=_CheckChromeRevOption,
926 help=('Revision of Chrome to use, of type [%s]'
927 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700928 parser.add_remote_option('--profile', default=None, type='string',
929 action='store', dest='profile',
930 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800931
Ryan Cuif4f84be2012-07-09 18:50:41 -0700932 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400933 # Patch selection options.
934 #
935
936 group = CustomGroup(
937 parser,
938 'Patch Options')
939
940 group.add_remote_option('-g', '--gerrit-patches', action='extend',
941 default=[], type='string',
942 metavar="'Id1 *int_Id2...IdN'",
943 help="Space-separated list of short-form Gerrit "
944 "Change-Id's or change numbers to patch. "
945 "Please prepend '*' to internal Change-Id's")
946 group.add_remote_option('-G', '--rietveld-patches', action='extend',
947 default=[], type='string',
948 metavar="'id1[:subdir1]...idN[:subdirN]'",
949 help='Space-separated list of short-form Rietveld '
950 'issue numbers to patch. If no subdir is '
951 'specified, the src directory is used.')
952 group.add_option('-p', '--local-patches', action='extend', default=[],
953 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
954 help='Space-separated list of project branches with '
955 'patches to apply. Projects are specified by name. '
956 'If no branch is specified the current branch of the '
957 'project will be used.')
958
959 parser.add_option_group(group)
960
961 #
962 # Remote trybot options.
963 #
964
965 group = CustomGroup(
966 parser,
967 'Remote Trybot Options (--remote)')
968
969 group.add_remote_option('--hwtest', dest='hwtest', action='store_true',
970 default=False,
971 help='Run the HWTest stage (tests on real hardware)')
972 group.add_option('--remote-description', default=None,
973 help='Attach an optional description to a --remote run '
974 'to make it easier to identify the results when it '
975 'finishes')
976 group.add_option('--slaves', action='extend', default=[],
977 help='Specify specific remote tryslaves to run on (e.g. '
978 'build149-m2); if the bot is busy, it will be queued')
979 group.add_option('--test-tryjob', action='store_true',
980 default=False,
981 help='Submit a tryjob to the test repository. Will not '
982 'show up on the production trybot waterfall.')
983
984 parser.add_option_group(group)
985
986 #
Ryan Cui88b901c2013-06-21 11:35:30 -0700987 # Branch creation options.
988 #
989
990 group = CustomGroup(
991 parser,
992 'Branch Creation Options (used with branch-util)')
993
994 group.add_remote_option('--branch-name',
995 help='The branch to create or delete.')
996 group.add_remote_option('--delete-branch', default=False, action='store_true',
997 help='Delete the branch specified in --branch-name.')
998 group.add_remote_option('--rename-to', type='string',
999 help='Rename a branch to the specified name.')
1000 group.add_remote_option('--force-create', default=False, action='store_true',
1001 help='Overwrites an existing branch.')
1002
1003 parser.add_option_group(group)
1004
1005 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001006 # Advanced options.
Ryan Cuif4f84be2012-07-09 18:50:41 -07001007 #
1008
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001009 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -08001010 parser,
1011 'Advanced Options',
1012 'Caution: use these options at your own risk.')
1013
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001014 group.add_remote_option('--bootstrap-args', action='append', default=[],
1015 help='Args passed directly to the bootstrap re-exec '
1016 'to skip verification by the bootstrap code')
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001017 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
1018 default=False, help='This is running on a buildbot')
1019 group.add_remote_option('--buildnumber', help='build number', type='int',
1020 default=0)
Ryan Cui5ba7e152012-05-10 14:36:52 -07001021 group.add_option('--chrome_root', default=None, type='path',
1022 action='callback', callback=_CheckChromeRootOption,
1023 dest='chrome_root', help='Local checkout of Chrome to use.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001024 group.add_remote_option('--chrome_version', default=None, type='string',
1025 action='callback', dest='chrome_version',
1026 callback=_CheckChromeVersionOption,
1027 help='Used with SPEC logic to force a particular SVN '
1028 'revision of chrome rather than the latest.')
1029 group.add_remote_option('--clobber', action='store_true', dest='clobber',
1030 default=False,
1031 help='Clears an old checkout before syncing')
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001032 group.add_remote_option('--latest-toolchain', action='store_true',
1033 default=False,
1034 help='Use the latest toolchain.')
Ryan Cui5ba7e152012-05-10 14:36:52 -07001035 parser.add_option('--log_dir', dest='log_dir', type='path',
Brian Harring3fec5a82012-03-01 05:57:03 -08001036 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001037 group.add_remote_option('--maxarchives', dest='max_archive_builds',
1038 default=3, type='int',
1039 help="Change the local saved build count limit.")
Ryan Cuibbd3d4b2012-08-17 12:20:37 -07001040 parser.add_remote_option('--manifest-repo-url',
1041 help=('Overrides the default manifest repo url.'))
David James565bc9a2013-04-08 14:54:45 -07001042 group.add_remote_option('--compilecheck', action='store_true', default=False,
1043 help='Only verify compilation and unit tests.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001044 group.add_remote_option('--noarchive', action='store_false', dest='archive',
1045 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -07001046 group.add_remote_option('--nobootstrap', action='store_false',
1047 dest='bootstrap', default=True,
1048 help="Don't checkout and run from a standalone "
1049 "chromite repo.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001050 group.add_remote_option('--nobuild', action='store_false', dest='build',
1051 default=True,
1052 help="Don't actually build (for cbuildbot dev)")
1053 group.add_remote_option('--noclean', action='store_false', dest='clean',
1054 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -07001055 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
1056 default=True,
1057 help='Disable cbuildbots usage of cgroups.')
Ryan Cui3ea98e02013-08-07 16:01:48 -07001058 group.add_remote_option('--nochromesdk', action='store_false',
1059 dest='chrome_sdk', default=True,
1060 help="Don't run the ChromeSDK stage which builds "
1061 "Chrome outside of the chroot.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001062 group.add_remote_option('--noprebuilts', action='store_false',
1063 dest='prebuilts', default=True,
1064 help="Don't upload prebuilts.")
Ryan Cui88b901c2013-06-21 11:35:30 -07001065 group.add_remote_option('--nopatch', action='store_false',
1066 dest='postsync_patch', default=True,
1067 help=("Don't run PatchChanges stage. This does not "
1068 "disable patching in of chromite patches "
1069 "during BootstrapStage."))
1070 group.add_remote_option('--noreexec', action='store_false',
1071 dest='postsync_reexec', default=True,
1072 help="Don't reexec into the buildroot after syncing.")
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001073 group.add_remote_option('--nosdk', action='store_true',
1074 default=False,
1075 help='Re-create the SDK from scratch.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001076 group.add_remote_option('--nosync', action='store_false', dest='sync',
1077 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001078 group.add_remote_option('--notests', action='store_false', dest='tests',
1079 default=True,
1080 help='Override values from buildconfig and run no '
1081 'tests.')
1082 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
1083 default=True,
1084 help='Override values from buildconfig and never '
1085 'uprev.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001086 group.add_option('--reference-repo', action='store', default=None,
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001087 dest='reference_repo',
1088 help='Reuse git data stored in an existing repo '
1089 'checkout. This can drastically reduce the network '
1090 'time spent setting up the trybot checkout. By '
1091 "default, if this option isn't given but cbuildbot "
1092 'is invoked from a repo checkout, cbuildbot will '
1093 'use the repo root.')
Ryan Cuicedd8a52012-03-22 02:28:35 -07001094 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001095 help='Skip stages already successfully completed.')
1096 group.add_remote_option('--timeout', action='store', type='int', default=0,
1097 help='Specify the maximum amount of time this job '
1098 'can run for, at which point the build will be '
1099 'aborted. If set to zero, then there is no '
1100 'timeout.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001101 group.add_remote_option('--version', dest='force_version', default=None,
1102 help='Used with manifest logic. Forces use of this '
Aviv Keshetc2c123d2013-10-14 18:06:12 -04001103 'version rather than create or get latest. '
1104 'Examples: 4815.0.0-rc1, 4815.1.2')
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001105
1106 parser.add_option_group(group)
1107
1108 #
1109 # Internal options.
1110 #
1111
1112 group = CustomGroup(
1113 parser,
1114 'Internal ChromeOS Build Team Options',
1115 'Caution: these are for meant for the ChromeOS build team only')
1116
1117 group.add_remote_option('--archive-base', type='gs_path',
1118 help='Base GS URL (gs://<bucket_name>/<path>) to '
1119 'upload archive artifacts to')
Brian Harringab8fb5c2012-07-18 11:28:22 -07001120 group.add_remote_option('--cq-gerrit-query', dest='cq_gerrit_override',
1121 default=None,
1122 help=
1123 "If given, this gerrit query will be used to find what patches to test, "
Brian Harringc5cabfe2012-12-19 01:04:44 -08001124 "rather than the normal 'CommitQueue=1 AND Verified=1 AND CodeReview=2' "
Brian Harringab8fb5c2012-07-18 11:28:22 -07001125 "query it defaults to. Use with care- note additionally this setting "
1126 "only has an effect if the buildbot target is a cq target, and we're "
1127 "in buildbot mode.")
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001128 group.add_option('--pass-through', dest='pass_through_args', action='append',
1129 type='string', default=[])
David Jamesf421c6d2013-04-11 15:37:57 -07001130 group.add_remote_option('--pre-cq', action='store_true', default=False,
1131 help='Mark CLs as tested by the PreCQ on success.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001132 group.add_option('--reexec-api-version', dest='output_api_version',
Ryan Cuif4f84be2012-07-09 18:50:41 -07001133 action='store_true', default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001134 help='Used for handling forwards/backwards compatibility '
1135 'with --resume and --bootstrap')
1136 group.add_option('--remote-trybot', dest='remote_trybot',
1137 action='store_true', default=False,
1138 help='Indicates this is running on a remote trybot machine')
1139 group.add_remote_option('--remote-patches', action='extend', default=[],
1140 help='Patches uploaded by the trybot client when run '
1141 'using the -p option')
Brian Harringf611e6e2012-07-17 18:47:44 -07001142 # Note the default here needs to be hardcoded to 3; that is the last version
1143 # that lacked this functionality.
Mike Frysinger81af6ef2013-04-03 02:24:09 -04001144 group.add_option('--remote-version', default=3, type=int, action='store',
1145 help='Used for compatibility checks w/tryjobs running in '
1146 'older chromite instances')
1147 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT)
1148 group.add_remote_option('--test-bootstrap', action='store_true',
1149 default=False,
1150 help='Causes cbuildbot to bootstrap itself twice, in '
1151 'the sequence A->B->C: A(unpatched) patches and '
1152 'bootstraps B; B patches and bootstraps C')
1153 group.add_remote_option('--validation_pool', default=None,
1154 help='Path to a pickled validation pool. Intended '
1155 'for use only with the commit queue.')
1156
1157 parser.add_option_group(group)
Ryan Cuif4f84be2012-07-09 18:50:41 -07001158
1159 #
Brian Harring3fec5a82012-03-01 05:57:03 -08001160 # Debug options
Ryan Cuif4f84be2012-07-09 18:50:41 -07001161 #
Brian Harringfec89fe2012-09-23 07:30:54 -07001162 # Temporary hack; in place till --dry-run replaces --debug.
1163 # pylint: disable=W0212
Brian Harring009db502012-10-10 02:21:37 -07001164 group = parser.debug_group
Brian Harringfec89fe2012-09-23 07:30:54 -07001165 debug = [x for x in group.option_list if x._long_opts == ['--debug']][0]
1166 debug.help += " Currently functions as --dry-run in addition."
1167 debug.pass_through = True
Brian Harring3fec5a82012-03-01 05:57:03 -08001168 group.add_option('--dump_config', action='store_true', dest='dump_config',
1169 default=False,
1170 help='Dump out build config options, and exit.')
1171 group.add_option('--notee', action='store_false', dest='tee', default=True,
1172 help="Disable logging and internal tee process. Primarily "
1173 "used for debugging cbuildbot itself.")
Brian Harring3fec5a82012-03-01 05:57:03 -08001174 return parser
1175
1176
Ryan Cui85867972012-02-23 18:21:49 -08001177def _FinishParsing(options, args):
1178 """Perform some parsing tasks that need to take place after optparse.
1179
1180 This function needs to be easily testable! Keep it free of
1181 environment-dependent code. Put more detailed usage validation in
1182 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -08001183
1184 Args:
Matt Tennant759e2352013-09-27 15:14:44 -07001185 options: The options object returned by optparse
1186 args: The args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -08001187 """
Ryan Cui41023d92012-11-13 19:59:50 -08001188 # Populate options.pass_through_args.
1189 accepted, _ = commandline.FilteringParser.FilterArgs(
1190 options.parsed_args, lambda x: x.opt_inst.pass_through)
1191 options.pass_through_args.extend(accepted)
Brian Harring07039b52012-05-13 17:56:47 -07001192
Brian Harring3fec5a82012-03-01 05:57:03 -08001193 if options.chrome_root:
1194 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001195 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
1196 constants.CHROME_REV_LOCAL)
David Jamesa0a664e2013-02-13 09:52:01 -08001197 elif options.chrome_rev == constants.CHROME_REV_LOCAL:
1198 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
1199 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -08001200
1201 if options.chrome_version:
1202 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001203 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
1204 constants.CHROME_REV_SPEC)
David Jamesa0a664e2013-02-13 09:52:01 -08001205 elif options.chrome_rev == constants.CHROME_REV_SPEC:
1206 cros_build_lib.Die(
1207 'Chrome rev must not be %s if chrome_version is not set.'
1208 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -08001209
David James9e27e662013-02-14 13:42:43 -08001210 patches = bool(options.gerrit_patches or options.local_patches or
1211 options.rietveld_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001212 if options.remote:
1213 if options.local:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001214 cros_build_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -07001215
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001216 if not options.buildbot and not patches:
Brian Harring7cc4b932012-11-01 16:58:55 -07001217 if not cros_build_lib.BooleanPrompt(
1218 prompt="No patches were provided; are you sure you want to just "
1219 "run a remote build of ToT?", default=False):
1220 cros_build_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001221
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001222 # --debug needs to be explicitly passed through for remote invocations.
1223 release_mode_with_patches = (options.buildbot and patches and
1224 '--debug' not in options.pass_through_args)
1225 else:
1226 if len(args) > 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001227 cros_build_lib.Die('Multiple configs not supported if not running with '
Brian Harringf1aad832012-07-18 10:46:39 -07001228 '--remote. Got %r', args)
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001229
Ryan Cui79319ab2012-05-21 12:59:18 -07001230 if options.slaves:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001231 cros_build_lib.Die('Cannot use --slaves if not running with --remote.')
Ryan Cui79319ab2012-05-21 12:59:18 -07001232
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001233 release_mode_with_patches = (options.buildbot and patches and
1234 not options.debug)
1235
David James5734ea32012-08-15 20:23:49 -07001236 # When running in release mode, make sure we are running with checked-in code.
1237 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
1238 # a release image with checked-in code for CrOS packages.
1239 if release_mode_with_patches:
1240 cros_build_lib.Die(
1241 'Cannot provide patches when running with --buildbot!')
1242
Ryan Cuiba41ad32012-03-08 17:15:29 -08001243 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001244 cros_build_lib.Die(
1245 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -08001246
Ryan Cui85867972012-02-23 18:21:49 -08001247 # Record whether --debug was set explicitly vs. it was inferred.
1248 options.debug_forced = False
1249 if options.debug:
1250 options.debug_forced = True
Ryan Cui88b901c2013-06-21 11:35:30 -07001251 if not options.debug:
Ryan Cui16ca5812012-03-08 20:34:27 -08001252 # We don't set debug by default for
1253 # 1. --buildbot invocations.
1254 # 2. --remote invocations, because it needs to push changes to the tryjob
1255 # repo.
1256 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -08001257
Ryan Cui1c13a252012-10-16 15:00:16 -07001258 # Record the configs targeted.
1259 options.build_targets = args[:]
1260
Ryan Cui88b901c2013-06-21 11:35:30 -07001261 if constants.BRANCH_UTIL_CONFIG in options.build_targets:
Ryan Cui7bd8db62013-08-08 16:29:51 -07001262 if options.remote:
1263 cros_build_lib.Die(
1264 'Running branch-util as a remote tryjob is not yet supported.')
Ryan Cui88b901c2013-06-21 11:35:30 -07001265 if len(options.build_targets) > 1:
1266 cros_build_lib.Die(
1267 'Cannot run branch-util with any other configs.')
1268 if not options.branch_name:
1269 cros_build_lib.Die(
1270 'Must specify --branch-name with the branch-util config.')
1271 if not any([options.force_version, options.delete_branch,
1272 options.rename_to]):
1273 cros_build_lib.Die(
1274 'Must specify --version with the branch-util config, unless '
1275 'running with --delete-branch or --rename-to.')
1276 elif any([options.delete_branch, options.rename_to, options.branch_name]):
1277 cros_build_lib.Die(
1278 'Cannot specify --delete-branch, --rename-to or --branch-name when not '
1279 'running the %s config', constants.BRANCH_UTIL_CONFIG)
1280
Brian Harring3fec5a82012-03-01 05:57:03 -08001281
Brian Harring1d7ba942012-04-24 06:37:18 -07001282# pylint: disable=W0613
Brian Harringae0a5322012-09-15 01:46:51 -07001283def _PostParseCheck(parser, options, args):
Ryan Cui85867972012-02-23 18:21:49 -08001284 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -08001285
Ryan Cui85867972012-02-23 18:21:49 -08001286 Args:
1287 options/args: The options/args object returned by optparse
1288 """
Ryan Cuie1e4e662012-05-21 16:39:46 -07001289 if not options.branch:
David James97d95872012-11-16 15:09:56 -08001290 options.branch = git.GetChromiteTrackingBranch()
Ryan Cuie1e4e662012-05-21 16:39:46 -07001291
Brian Harringae0a5322012-09-15 01:46:51 -07001292 if not repository.IsARepoRoot(options.sourceroot):
1293 if options.local_patches:
1294 raise Exception('Could not find repo checkout at %s!'
1295 % options.sourceroot)
1296
David Jamesac8c2a72013-02-13 18:44:33 -08001297 # Because the default cache dir depends on other options, FindCacheDir
1298 # always returns None, and we setup the default here.
Brian Harringae0a5322012-09-15 01:46:51 -07001299 if options.cache_dir is None:
1300 # Note, options.sourceroot is set regardless of the path
1301 # actually existing.
David Jamesac8c2a72013-02-13 18:44:33 -08001302 if options.buildroot is not None:
Brian Harringae0a5322012-09-15 01:46:51 -07001303 options.cache_dir = os.path.join(options.buildroot, '.cache')
David Jamesac8c2a72013-02-13 18:44:33 -08001304 elif os.path.exists(options.sourceroot):
1305 options.cache_dir = os.path.join(options.sourceroot, '.cache')
Brian Harringae0a5322012-09-15 01:46:51 -07001306 else:
1307 options.cache_dir = parser.FindCacheDir(parser, options)
1308 options.cache_dir = os.path.abspath(options.cache_dir)
Brian Harring8c1d7b12012-10-04 17:36:32 -07001309 parser.ConfigureCacheDir(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -07001310
1311 osutils.SafeMakedirs(options.cache_dir)
Ryan Cui5ba7e152012-05-10 14:36:52 -07001312
Brian Harring609dc4e2012-05-07 02:17:44 -07001313 if options.local_patches:
Brian Harring1d7ba942012-04-24 06:37:18 -07001314 options.local_patches = _CheckLocalPatches(
Brian Harring609dc4e2012-05-07 02:17:44 -07001315 options.sourceroot, options.local_patches)
Brian Harring1d7ba942012-04-24 06:37:18 -07001316
1317 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
1318 if (default and not any([options.local, options.buildbot,
1319 options.remote, options.remote_trybot])):
Brian Harring1b8c4c82012-05-29 23:03:04 -07001320 cros_build_lib.Info("CBUILDBOT_DEFAULT_MODE=%s env var detected, using it."
1321 % default)
Brian Harring1d7ba942012-04-24 06:37:18 -07001322 default = default.lower()
1323 if default == 'local':
1324 options.local = True
1325 elif default == 'remote':
1326 options.remote = True
1327 elif default == 'buildbot':
1328 options.buildbot = True
1329 else:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001330 cros_build_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
1331 % default)
Ryan Cui85867972012-02-23 18:21:49 -08001332
1333
1334def _ParseCommandLine(parser, argv):
1335 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -08001336 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -07001337
1338 if options.output_api_version:
Ryan Cui724f1d32012-10-15 18:10:22 -07001339 print constants.REEXEC_API_VERSION
Brian Harring37e559b2012-05-22 20:47:32 -07001340 sys.exit(0)
1341
Ryan Cui54da0702012-04-19 18:38:08 -07001342 if options.list:
1343 _PrintValidConfigs(options.print_all)
1344 sys.exit(0)
1345
Ryan Cui8be16062012-04-24 12:05:26 -07001346 # Strip out null arguments.
1347 # TODO(rcui): Remove when buildbot is fixed
1348 args = [arg for arg in args if arg]
1349 if not args:
1350 parser.error('Invalid usage. Use -h to see usage. Use -l to list '
1351 'supported configs.')
1352
Ryan Cui85867972012-02-23 18:21:49 -08001353 _FinishParsing(options, args)
1354 return options, args
1355
1356
Matt Tennant759e2352013-09-27 15:14:44 -07001357# TODO(build): This function is too damn long.
Ryan Cui85867972012-02-23 18:21:49 -08001358def main(argv):
David James59a0a2b2013-03-22 14:04:44 -07001359 # Turn on strict sudo checks.
1360 cros_build_lib.STRICT_SUDO = True
1361
Ryan Cui85867972012-02-23 18:21:49 -08001362 # Set umask to 022 so files created by buildbot are readable.
Mike Frysinger60ec1012013-10-21 00:11:10 -04001363 os.umask(0o22)
Ryan Cui85867972012-02-23 18:21:49 -08001364
Ryan Cui85867972012-02-23 18:21:49 -08001365 parser = _CreateParser()
1366 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -08001367
Brian Harringae0a5322012-09-15 01:46:51 -07001368 _PostParseCheck(parser, options, args)
Brian Harring3fec5a82012-03-01 05:57:03 -08001369
Mike Frysinger8fd67dc2012-12-03 23:51:18 -05001370 cros_build_lib.AssertOutsideChroot()
Zdenek Behan98ec2fb2012-08-31 17:12:18 +02001371
Brian Harring3fec5a82012-03-01 05:57:03 -08001372 if options.remote:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001373 cros_build_lib.logger.setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001374
Brian Harring3fec5a82012-03-01 05:57:03 -08001375 # Verify configs are valid.
Dan Shi0bdb7132013-07-30 16:22:12 -07001376 # If hwtest flag is enabled, post a warning that HWTest step may fail if the
1377 # specified board is not a released platform or it is a generic overlay.
Brian Harring3fec5a82012-03-01 05:57:03 -08001378 for bot in args:
Aviv Kesheta96a2a92013-02-05 17:21:51 -08001379 build_config = _GetConfig(bot)
1380 if options.hwtest:
Dan Shi0bdb7132013-07-30 16:22:12 -07001381 cros_build_lib.Warning(
1382 'If %s is not a released platform or it is a generic overlay, '
1383 'the HWTest step will most likely not run; please ask the lab '
1384 'team for help if this is unexpected.' % build_config['boards'])
Brian Harring3fec5a82012-03-01 05:57:03 -08001385
1386 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -08001387 print 'Verifying patches...'
Ryan Cuie1e4e662012-05-21 16:39:46 -07001388 patch_pool = AcquirePoolFromOptions(options)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001389
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001390 # --debug need to be explicitly passed through for remote invocations.
1391 if options.buildbot and '--debug' not in options.pass_through_args:
1392 _ConfirmRemoteBuildbotRun()
1393
Ryan Cui16ca5812012-03-08 20:34:27 -08001394 print 'Submitting tryjob...'
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001395 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cuia25d8eb2012-07-11 14:54:27 -07001396 tryjob.Submit(testjob=options.test_tryjob, dryrun=False)
Ryan Cui16ca5812012-03-08 20:34:27 -08001397 print 'Tryjob submitted!'
1398 print ('Go to %s to view the status of your job.'
Ryan Cui4906e1c2012-04-03 20:09:34 -07001399 % tryjob.GetTrybotWaterfallLink())
Brian Harring3fec5a82012-03-01 05:57:03 -08001400 sys.exit(0)
Matt Tennant759e2352013-09-27 15:14:44 -07001401
Ryan Cui54da0702012-04-19 18:38:08 -07001402 elif (not options.buildbot and not options.remote_trybot
1403 and not options.resume and not options.local):
Ryan Cui88b901c2013-06-21 11:35:30 -07001404 options.local = True
Brian Harring1b8c4c82012-05-29 23:03:04 -07001405 cros_build_lib.Warning(
1406 'Running in LOCAL TRYBOT mode! Use --remote to submit REMOTE '
1407 'tryjobs. Use --local to suppress this message.')
1408 cros_build_lib.Warning(
Ryan Cui51591352012-07-09 15:15:53 -07001409 'In the future, --local will be required to run the local '
Brian Harring1b8c4c82012-05-29 23:03:04 -07001410 'trybot.')
Ryan Cui54da0702012-04-19 18:38:08 -07001411 time.sleep(5)
Brian Harring3fec5a82012-03-01 05:57:03 -08001412
Matt Tennant759e2352013-09-27 15:14:44 -07001413 # Only one config arg is allowed in this mode, which was confirmed earlier.
Ryan Cui8be16062012-04-24 12:05:26 -07001414 bot_id = args[-1]
1415 build_config = _GetConfig(bot_id)
Brian Harring3fec5a82012-03-01 05:57:03 -08001416
1417 if options.reference_repo is None:
Ryan Cui5ba7e152012-05-10 14:36:52 -07001418 repo_path = os.path.join(options.sourceroot, '.repo')
Brian Harring3fec5a82012-03-01 05:57:03 -08001419 # If we're being run from a repo checkout, reuse the repo's git pool to
1420 # cut down on sync time.
1421 if os.path.exists(repo_path):
Ryan Cui5ba7e152012-05-10 14:36:52 -07001422 options.reference_repo = options.sourceroot
Brian Harring3fec5a82012-03-01 05:57:03 -08001423 elif options.reference_repo:
1424 if not os.path.exists(options.reference_repo):
1425 parser.error('Reference path %s does not exist'
1426 % (options.reference_repo,))
1427 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1428 parser.error('Reference path %s does not look to be the base of a '
1429 'repo checkout; no .repo exists in the root.'
1430 % (options.reference_repo,))
Ryan Cuid4a24212012-04-04 18:08:12 -07001431
Brian Harringf11bf682012-05-14 15:53:43 -07001432 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001433 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001434 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1435 'be used together. Cgroup support is required for '
1436 'buildbot/remote-trybot mode.')
Mike Frysingera78a56e2012-11-20 06:02:30 -05001437 if not cgroups.Cgroup.IsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001438 parser.error('Option --buildbot/--remote-trybot was given, but this '
1439 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001440
David Jamesaad5cc72012-10-26 15:03:13 -07001441 missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
Brian Harring351ce442012-03-09 16:38:14 -08001442 if missing:
Ryan Cuid4a24212012-04-04 18:08:12 -07001443 parser.error("Option --buildbot/--remote-trybot requires the following "
1444 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001445 % (', '.join(missing)))
1446
Brian Harring3fec5a82012-03-01 05:57:03 -08001447 if options.reference_repo:
1448 options.reference_repo = os.path.abspath(options.reference_repo)
1449
1450 if options.dump_config:
1451 # This works, but option ordering is bad...
1452 print 'Configuration %s:' % bot_id
1453 pretty_printer = pprint.PrettyPrinter(indent=2)
1454 pretty_printer.pprint(build_config)
1455 sys.exit(0)
1456
1457 if not options.buildroot:
1458 if options.buildbot:
Mike Frysinger6903c762012-12-04 01:57:16 -05001459 parser.error('Please specify a buildroot with the --buildbot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001460
Ryan Cui5ba7e152012-05-10 14:36:52 -07001461 options.buildroot = _DetermineDefaultBuildRoot(options.sourceroot,
1462 build_config['internal'])
Brian Harring470f6112012-03-02 11:47:10 -08001463 # We use a marker file in the buildroot to indicate the user has
1464 # consented to using this directory.
1465 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1466 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001467
1468 # Sanity check of buildroot- specifically that it's not pointing into the
1469 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001470 if (not repository.IsARepoRoot(options.buildroot) and
David James13a69c92013-05-09 10:37:42 -07001471 git.FindRepoDir(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001472 parser.error('Configured buildroot %s points into a repository checkout, '
1473 'rather than the root of it. This is not supported.'
1474 % options.buildroot)
1475
Chris Sosab5ea3b42012-10-25 15:25:20 -07001476 if not options.log_dir:
1477 options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1478
Brian Harringd166aaf2012-05-14 18:31:53 -07001479 log_file = None
1480 if options.tee:
Chris Sosab5ea3b42012-10-25 15:25:20 -07001481 log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
1482 osutils.SafeMakedirs(options.log_dir)
Brian Harringd166aaf2012-05-14 18:31:53 -07001483 _BackupPreviousLog(log_file)
1484
Brian Harring1b8c4c82012-05-29 23:03:04 -07001485 with cros_build_lib.ContextManagerStack() as stack:
Aaron Gable881fccb2013-09-27 18:35:24 -07001486 # TODO(ferringb): update this once
1487 # https://chromium-review.googlesource.com/25359
David Jamescebc7272013-07-17 16:45:05 -07001488 # is landed- it's sensitive to the manifest-versions cache path.
1489 options.preserve_paths = set(['manifest-versions', '.cache',
1490 'manifest-versions-internal'])
1491 if log_file is not None:
1492 # We don't want the critical section to try to clean up the tee process,
1493 # so we run Tee (forked off) outside of it. This prevents a deadlock
1494 # because the Tee process only exits when its pipe is closed, and the
1495 # critical section accidentally holds on to that file handle.
1496 stack.Add(tee.Tee, log_file)
1497 options.preserve_paths.add(_DEFAULT_LOG_DIR)
1498
Brian Harringc2d09d92012-05-13 22:03:15 -07001499 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1500 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001501
Brian Harringc2d09d92012-05-13 22:03:15 -07001502 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001503 # If we're in resume mode, use our parents tempdir rather than
1504 # nesting another layer.
David James4bc13702013-03-26 08:08:04 -07001505 stack.Add(osutils.TempDir, prefix='cbuildbot-tmp', set_global=True)
Brian Harringc2d09d92012-05-13 22:03:15 -07001506 logging.debug("Cbuildbot tempdir is %r.", os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001507
Brian Harringc2d09d92012-05-13 22:03:15 -07001508 if options.cgroups:
1509 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001510
Brian Harringc2d09d92012-05-13 22:03:15 -07001511 # Mark everything between EnforcedCleanupSection and here as having to
1512 # be rolled back via the contextmanager cleanup handlers. This
1513 # ensures that sudo bits cannot outlive cbuildbot, that anything
1514 # cgroups would kill gets killed, etc.
David Jamesfb3aac92013-10-16 13:26:52 -07001515 stack.Add(critical_section.ForkWatchdog)
Brian Harringd166aaf2012-05-14 18:31:53 -07001516
Brian Harringc2d09d92012-05-13 22:03:15 -07001517 if options.timeout > 0:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001518 stack.Add(cros_build_lib.Timeout, options.timeout)
Brian Harringa184efa2012-03-04 11:51:25 -08001519
Brian Harringc2d09d92012-05-13 22:03:15 -07001520 if not options.buildbot:
1521 build_config = cbuildbot_config.OverrideConfigForTrybot(
1522 build_config,
David Jamese8dcfc42013-03-21 19:49:49 -07001523 options)
Brian Harringc2d09d92012-05-13 22:03:15 -07001524
Mike Frysinger6903c762012-12-04 01:57:16 -05001525 if options.buildbot or options.remote_trybot:
1526 _DisableYamaHardLinkChecks()
1527
Brian Harringc2d09d92012-05-13 22:03:15 -07001528 _RunBuildStagesWrapper(options, build_config)