blob: 9bf3a8ac5f8179c300deabf10184a636e7bd060c [file] [log] [blame]
Brian Harring3fec5a82012-03-01 05:57:03 -08001#!/usr/bin/python
2
3# Copyright (c) 2011-2012 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
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
13import distutils.version
14import glob
Chris Sosa4f6ffaf2012-05-01 17:05:44 -070015import logging
David James58e0c092012-03-04 20:31:12 -080016import multiprocessing
Brian Harring3fec5a82012-03-01 05:57:03 -080017import optparse
18import os
19import pprint
20import sys
Ryan Cui54da0702012-04-19 18:38:08 -070021import time
Brian Harring3fec5a82012-03-01 05:57:03 -080022
23from chromite.buildbot import builderstage as bs
24from chromite.buildbot import cbuildbot_background as background
25from chromite.buildbot import cbuildbot_config
26from chromite.buildbot import cbuildbot_stages as stages
27from chromite.buildbot import cbuildbot_results as results_lib
Brian Harring3fec5a82012-03-01 05:57:03 -080028from chromite.buildbot import constants
29from chromite.buildbot import gerrit_helper
30from chromite.buildbot import patch as cros_patch
31from chromite.buildbot import remote_try
32from chromite.buildbot import repository
33from chromite.buildbot import tee
Ryan Cui16d9e1f2012-05-11 10:50:18 -070034from chromite.buildbot import trybot_patch_pool
Brian Harring3fec5a82012-03-01 05:57:03 -080035
Brian Harringc92a7012012-02-29 10:11:34 -080036from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080037from chromite.lib import cleanup
Brian Harring3fec5a82012-03-01 05:57:03 -080038from chromite.lib import cros_build_lib as cros_lib
Brian Harringaf019fb2012-05-10 15:06:13 -070039from chromite.lib import osutils
Brian Harring3fec5a82012-03-01 05:57:03 -080040from chromite.lib import sudo
41
Ryan Cuiadd49122012-03-21 22:19:58 -070042
Brian Harring3fec5a82012-03-01 05:57:03 -080043cros_lib.STRICT_SUDO = True
44
45_DEFAULT_LOG_DIR = 'cbuildbot_logs'
46_BUILDBOT_LOG_FILE = 'cbuildbot.log'
47_DEFAULT_EXT_BUILDROOT = 'trybot'
48_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Brian Harring3fec5a82012-03-01 05:57:03 -080049_DISTRIBUTED_TYPES = [constants.COMMIT_QUEUE_TYPE, constants.PFQ_TYPE,
50 constants.CANARY_TYPE, constants.CHROME_PFQ_TYPE,
51 constants.PALADIN_TYPE]
Brian Harring351ce442012-03-09 16:38:14 -080052_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Brian Harring3fec5a82012-03-01 05:57:03 -080053
Brian Harring37e559b2012-05-22 20:47:32 -070054# Used by --resume and --bootstrap to decipher which options they
55# can pass to the target cbuildbot (since it may not have that
56# option).
57# Format is Major:Minor. Minor is used for tracking new options added
58# that aren't critical to the older version if it's not ran.
59# Major is used for tracking heavy API breakage- for example, no longer
60# supporting the --resume option.
61_REEXEC_API_MAJOR = 0
62_REEXEC_API_MINOR = 1
63_REEXEC_API_VERSION = '%i.%i' % (_REEXEC_API_MAJOR, _REEXEC_API_MINOR)
64
Brian Harring3fec5a82012-03-01 05:57:03 -080065
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070066def _PrintValidConfigs(display_all=False):
Brian Harring3fec5a82012-03-01 05:57:03 -080067 """Print a list of valid buildbot configs.
68
69 Arguments:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070070 display_all: Print all configs. Otherwise, prints only configs with
71 trybot_list=True.
Brian Harring3fec5a82012-03-01 05:57:03 -080072 """
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070073 def _GetSortKey(config_name):
74 config_dict = cbuildbot_config.config[config_name]
75 return (not config_dict['trybot_list'], config_dict['description'],
76 config_name)
77
Brian Harring3fec5a82012-03-01 05:57:03 -080078 COLUMN_WIDTH = 45
79 print 'config'.ljust(COLUMN_WIDTH), 'description'
80 print '------'.ljust(COLUMN_WIDTH), '-----------'
81 config_names = cbuildbot_config.config.keys()
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070082 config_names.sort(key=_GetSortKey)
Brian Harring3fec5a82012-03-01 05:57:03 -080083 for name in config_names:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070084 if display_all or cbuildbot_config.config[name]['trybot_list']:
85 desc = cbuildbot_config.config[name].get('description')
86 desc = desc if desc else ''
Brian Harring3fec5a82012-03-01 05:57:03 -080087 print name.ljust(COLUMN_WIDTH), desc
88
89
90def _GetConfig(config_name):
91 """Gets the configuration for the build"""
92 if not cbuildbot_config.config.has_key(config_name):
93 print 'Non-existent configuration %s specified.' % config_name
94 print 'Please specify one of:'
95 _PrintValidConfigs()
96 sys.exit(1)
97
98 result = cbuildbot_config.config[config_name]
99
100 return result
101
102
103def _GetChromiteTrackingBranch():
David James66009462012-03-25 10:08:38 -0700104 """Returns the remote branch associated with chromite."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800105 cwd = os.path.dirname(os.path.realpath(__file__))
David James66009462012-03-25 10:08:38 -0700106 branch = cros_lib.GetCurrentBranch(cwd)
107 if branch:
108 tracking_branch = cros_lib.GetTrackingBranch(branch, cwd)[1]
109 if tracking_branch.startswith('refs/heads/'):
110 return tracking_branch.replace('refs/heads/', '')
111 # If we are not on a branch, or if the tracking branch is a revision,
David James8b3c1bf2012-03-28 09:10:16 -0700112 # use the push branch. For repo repositories, this will be the manifest
113 # branch configured for this project. For other repositories, we'll just
114 # guess 'master', since there's no easy way to find out what branch
115 # we're on.
116 return cros_lib.GetPushBranch(cwd)[1]
Brian Harring3fec5a82012-03-01 05:57:03 -0800117
118
119def _CheckBuildRootBranch(buildroot, tracking_branch):
120 """Make sure buildroot branch is the same as Chromite branch."""
121 manifest_branch = cros_lib.GetManifestDefaultBranch(buildroot)
122 if manifest_branch != tracking_branch:
123 cros_lib.Die('Chromite is not on same branch as buildroot checkout\n' +
124 'Chromite is on branch %s.\n' % tracking_branch +
125 'Buildroot checked out to %s\n' % manifest_branch)
126
127
Ryan Cuie1e4e662012-05-21 16:39:46 -0700128def AcquirePoolFromOptions(options):
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700129 """Generate patch objects from passed in options.
Brian Harring3fec5a82012-03-01 05:57:03 -0800130
131 Args:
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700132 options: The options object generated by optparse.
Brian Harring3fec5a82012-03-01 05:57:03 -0800133
Ryan Cuif7f24692012-05-18 16:35:33 -0700134 Returns:
135 trybot_patch_pool.TrybotPatchPool object.
136
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700137 Raises:
138 gerrit_helper.GerritException, cros_patch.PatchException
Brian Harring3fec5a82012-03-01 05:57:03 -0800139 """
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700140 gerrit_patches = []
141 local_patches = []
142 remote_patches = []
Brian Harring3fec5a82012-03-01 05:57:03 -0800143
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700144 if options.gerrit_patches:
145 gerrit_patches = gerrit_helper.GetGerritPatchInfo(
146 options.gerrit_patches)
147 for patch in gerrit_patches:
148 if patch.IsAlreadyMerged():
149 cros_lib.Warning('Patch %s has already been merged.' % str(patch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800150
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700151 if options.local_patches:
152 local_patches = cros_patch.PrepareLocalPatches(
Ryan Cui5ba7e152012-05-10 14:36:52 -0700153 options.sourceroot,
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700154 options.local_patches,
Ryan Cuie1e4e662012-05-21 16:39:46 -0700155 options.branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800156
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700157 if options.remote_patches:
158 remote_patches = cros_patch.PrepareRemotePatches(
159 options.remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800160
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700161 return trybot_patch_pool.TrybotPatchPool(gerrit_patches, local_patches,
162 remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800163
164
165def _IsIncrementalBuild(buildroot, clobber):
166 """Returns True if we are reusing an existing buildroot."""
167 repo_dir = os.path.join(buildroot, '.repo')
168 return not clobber and os.path.isdir(repo_dir)
169
170
171class Builder(object):
172 """Parent class for all builder types.
173
174 This class functions as a parent class for various build types. It's intended
175 use is builder_instance.Run().
176
177 Vars:
Brian Harring3fec5a82012-03-01 05:57:03 -0800178 build_config: The configuration dictionary from cbuildbot_config.
179 options: The options provided from optparse in main().
Brian Harring3fec5a82012-03-01 05:57:03 -0800180 archive_url: Where our artifacts for this builder will be archived.
181 tracking_branch: The tracking branch for this build.
182 release_tag: The associated "chrome os version" of this build.
Brian Harring3fec5a82012-03-01 05:57:03 -0800183 """
184
Ryan Cuie1e4e662012-05-21 16:39:46 -0700185 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800186 """Initializes instance variables. Must be called by all subclasses."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800187 self.build_config = build_config
188 self.options = options
189
190 # TODO, Remove here and in config after bug chromium-os:14649 is fixed.
191 if self.build_config['chromeos_official']:
192 os.environ['CHROMEOS_OFFICIAL'] = '1'
193
David James58e0c092012-03-04 20:31:12 -0800194 self.archive_stages = {}
Brian Harring3fec5a82012-03-01 05:57:03 -0800195 self.archive_urls = {}
196 self.release_tag = None
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700197 self.patch_pool = trybot_patch_pool.GetEmptyPool()
Brian Harring3fec5a82012-03-01 05:57:03 -0800198
Ryan Cuie1e4e662012-05-21 16:39:46 -0700199 bs.BuilderStage.SetManifestBranch(self.options.branch)
Ryan Cuif7f24692012-05-18 16:35:33 -0700200
Brian Harring3fec5a82012-03-01 05:57:03 -0800201 def Initialize(self):
202 """Runs through the initialization steps of an actual build."""
Ryan Cuif7f24692012-05-18 16:35:33 -0700203 if self.options.resume:
204 results_lib.LoadCheckpoint(self.options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800205
206 # Check branch matching early.
207 if _IsIncrementalBuild(self.options.buildroot, self.options.clobber):
Ryan Cuie1e4e662012-05-21 16:39:46 -0700208 _CheckBuildRootBranch(self.options.buildroot, self.options.branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800209
210 self._RunStage(stages.CleanUpStage)
211
212 def _GetStageInstance(self, stage, *args, **kwargs):
213 """Helper function to get an instance given the args.
214
David James944a48e2012-03-07 12:19:03 -0800215 Useful as almost all stages just take in options and build_config.
Brian Harring3fec5a82012-03-01 05:57:03 -0800216 """
David James944a48e2012-03-07 12:19:03 -0800217 config = kwargs.pop('config', self.build_config)
218 return stage(self.options, config, *args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800219
220 def _SetReleaseTag(self):
221 """Sets the release tag from the manifest_manager.
222
223 Must be run after sync stage as syncing enables us to have a release tag.
224 """
225 # Extract version we have decided to build into self.release_tag.
226 manifest_manager = stages.ManifestVersionedSyncStage.manifest_manager
227 if manifest_manager:
228 self.release_tag = manifest_manager.current_version
229
230 def _RunStage(self, stage, *args, **kwargs):
231 """Wrapper to run a stage."""
232 stage_instance = self._GetStageInstance(stage, *args, **kwargs)
233 return stage_instance.Run()
234
235 def GetSyncInstance(self):
236 """Returns an instance of a SyncStage that should be run.
237
238 Subclasses must override this method.
239 """
240 raise NotImplementedError()
241
242 def RunStages(self):
243 """Subclasses must override this method. Runs the appropriate code."""
244 raise NotImplementedError()
245
Brian Harring3fec5a82012-03-01 05:57:03 -0800246 def _ShouldReExecuteInBuildRoot(self):
247 """Returns True if this build should be re-executed in the buildroot."""
248 abs_buildroot = os.path.abspath(self.options.buildroot)
249 return not os.path.abspath(__file__).startswith(abs_buildroot)
250
251 def _ReExecuteInBuildroot(self, sync_instance):
252 """Reexecutes self in buildroot and returns True if build succeeds.
253
254 This allows the buildbot code to test itself when changes are patched for
255 buildbot-related code. This is a no-op if the buildroot == buildroot
256 of the running chromite checkout.
257
258 Args:
259 sync_instance: Instance of the sync stage that was run to sync.
260
261 Returns:
262 True if the Build succeeded.
263 """
Brian Harring3fec5a82012-03-01 05:57:03 -0800264 if not self.options.resume:
Ryan Cuif7f24692012-05-18 16:35:33 -0700265 results_lib.WriteCheckpoint(self.options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800266
Brian Harring37e559b2012-05-22 20:47:32 -0700267 # Get the re-exec API version of the target chromite; if it's incompatible
268 # with us, bail now.
269 api = cros_lib.RunCommandCaptureOutput(
270 [constants.PATH_TO_CBUILDBOT] + ['--reexec-api-version'],
271 cwd=self.options.buildroot, error_code_ok=True)
272 # If the command failed, then we're targeting a cbuildbot that lacks the
273 # option; assume 0:0 (ie, initial state).
274 major, minor = 0, 0
275 if api.returncode == 0:
276 major, minor = map(int, api.output.strip().split('.', 1))
277
278 if major != _REEXEC_API_MAJOR:
279 cros_lib.Die(
280 'The targeted version of chromite in buildroot %s requires '
281 'api version %i, but we are api version %i. We cannot proceed.'
282 % (self.options.buildroot, major, _REEXEC_API_MAJOR))
283
Brian Harring3fec5a82012-03-01 05:57:03 -0800284 # Re-write paths to use absolute paths.
285 # Suppress any timeout options given from the commandline in the
286 # invoked cbuildbot; our timeout will enforce it instead.
Brian Harringf11bf682012-05-14 15:53:43 -0700287 args_to_append = ['--resume', '--timeout', '0', '--notee', '--nocgroups',
288 '--buildroot', os.path.abspath(self.options.buildroot)]
Brian Harring3fec5a82012-03-01 05:57:03 -0800289
290 if self.options.chrome_root:
291 args_to_append += ['--chrome_root',
292 os.path.abspath(self.options.chrome_root)]
293
294 if stages.ManifestVersionedSyncStage.manifest_manager:
295 ver = stages.ManifestVersionedSyncStage.manifest_manager.current_version
296 args_to_append += ['--version', ver]
297
298 if isinstance(sync_instance, stages.CommitQueueSyncStage):
299 vp_file = sync_instance.SaveValidationPool()
300 args_to_append += ['--validation_pool', vp_file]
301
302 # Re-run the command in the buildroot.
303 # Finally, be generous and give the invoked cbuildbot 30s to shutdown
304 # when something occurs. It should exit quicker, but the sigterm may
305 # hit while the system is particularly busy.
306 return_obj = cros_lib.RunCommand(
Ryan Cuif7f24692012-05-18 16:35:33 -0700307 [constants.PATH_TO_CBUILDBOT] + sys.argv[1:] + args_to_append,
Brian Harring3fec5a82012-03-01 05:57:03 -0800308 cwd=self.options.buildroot, error_code_ok=True, kill_timeout=30)
309 return return_obj.returncode == 0
310
Ryan Cuif7f24692012-05-18 16:35:33 -0700311 def _InitializeTrybotPatchPool(self):
312 """Generate patch pool from patches specified on the command line.
313
314 Do this only if we need to patch changes later on.
315 """
316 changes_stage = stages.PatchChangesStage.StageNamePrefix()
317 check_func = results_lib.Results.PreviouslyCompletedRecord
318 if not check_func(changes_stage) or self.options.bootstrap:
Ryan Cuie1e4e662012-05-21 16:39:46 -0700319 self.patch_pool = AcquirePoolFromOptions(self.options)
Ryan Cuif7f24692012-05-18 16:35:33 -0700320
321 def _GetBootstrapStage(self):
322 """Constructs and returns the BootStrapStage object.
323
324 We return None when there are no chromite patches to test, and
325 --test-bootstrap wasn't passed in.
326 """
327 stage = None
328 chromite_pool = self.patch_pool.Filter(project=constants.CHROMITE_PROJECT)
Ryan Cuie1e4e662012-05-21 16:39:46 -0700329 chromite_branch = _GetChromiteTrackingBranch()
330 if (chromite_pool or self.options.test_bootstrap
331 or chromite_branch != self.options.branch):
Ryan Cuif7f24692012-05-18 16:35:33 -0700332 stage = stages.BootstrapStage(self.options, self.build_config,
333 chromite_pool)
334 return stage
335
Brian Harring3fec5a82012-03-01 05:57:03 -0800336 def Run(self):
Ryan Cuif7f24692012-05-18 16:35:33 -0700337 """Main runner for this builder class. Runs build and prints summary.
338
339 Returns:
340 Whether the build succeeded.
341 """
342 self._InitializeTrybotPatchPool()
343
344 if self.options.bootstrap:
345 bootstrap_stage = self._GetBootstrapStage()
346 if bootstrap_stage:
347 # BootstrapStage blocks on re-execution of cbuildbot.
348 bootstrap_stage.Run()
349 return bootstrap_stage.returncode == 0
350
Brian Harring3fec5a82012-03-01 05:57:03 -0800351 print_report = True
David James3d4d3502012-04-09 15:12:06 -0700352 exception_thrown = False
Brian Harring3fec5a82012-03-01 05:57:03 -0800353 success = True
354 try:
355 self.Initialize()
356 sync_instance = self.GetSyncInstance()
357 sync_instance.Run()
358 self._SetReleaseTag()
359
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700360 if self.patch_pool:
361 self._RunStage(stages.PatchChangesStage, self.patch_pool)
Brian Harring3fec5a82012-03-01 05:57:03 -0800362
363 if self._ShouldReExecuteInBuildRoot():
364 print_report = False
365 success = self._ReExecuteInBuildroot(sync_instance)
366 else:
367 self.RunStages()
David James3d4d3502012-04-09 15:12:06 -0700368 except Exception:
369 exception_thrown = True
370 raise
Brian Harring3fec5a82012-03-01 05:57:03 -0800371 finally:
372 if print_report:
Ryan Cuif7f24692012-05-18 16:35:33 -0700373 results_lib.WriteCheckpoint(self.options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800374 print '\n\n\n@@@BUILD_STEP Report@@@\n'
375 results_lib.Results.Report(sys.stdout, self.archive_urls,
376 self.release_tag)
377 success = results_lib.Results.BuildSucceededSoFar()
David James3d4d3502012-04-09 15:12:06 -0700378 if exception_thrown and success:
379 success = False
380 print >> sys.stderr, """
381@@@STEP_FAILURE@@@
382Exception thrown, but all stages marked successful. This is an internal error,
383because the stage that threw the exception should be marked as failing."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800384
385 return success
386
387
388class SimpleBuilder(Builder):
389 """Builder that performs basic vetting operations."""
390
391 def GetSyncInstance(self):
392 """Sync to lkgm or TOT as necessary.
393
394 Returns: the instance of the sync stage that was run.
395 """
396 if self.options.lkgm or self.build_config['use_lkgm']:
397 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
398 else:
399 sync_stage = self._GetStageInstance(stages.SyncStage)
400
401 return sync_stage
402
David James58e0c092012-03-04 20:31:12 -0800403 def _RunBackgroundStagesForBoard(self, board):
404 """Run background board-specific stages for the specified board."""
David James58e0c092012-03-04 20:31:12 -0800405 archive_stage = self.archive_stages[board]
David James944a48e2012-03-07 12:19:03 -0800406 configs = self.build_config['board_specific_configs']
407 config = configs.get(board, self.build_config)
408 stage_list = [[stages.VMTestStage, board, archive_stage],
409 [stages.ChromeTestStage, board, archive_stage],
410 [stages.UnitTestStage, board],
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700411 [stages.UploadPrebuiltsStage, board, archive_stage]]
Brian Harring3fec5a82012-03-01 05:57:03 -0800412
David James58e0c092012-03-04 20:31:12 -0800413 # We can not run hw tests without archiving the payloads.
414 if self.options.archive:
David James944a48e2012-03-07 12:19:03 -0800415 for suite in config['hw_tests']:
416 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800417
David James944a48e2012-03-07 12:19:03 -0800418 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
419 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800420
421 def RunStages(self):
422 """Runs through build process."""
423 self._RunStage(stages.BuildBoardStage)
424
425 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800426 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
427 self._RunStage(stages.SDKTestStage)
428 self._RunStage(stages.UploadPrebuiltsStage,
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700429 constants.CHROOT_BUILDER_BOARD, None)
Brian Harring3fec5a82012-03-01 05:57:03 -0800430 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
431 self._RunStage(stages.RefreshPackageStatusStage)
432 else:
433 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800434
David James944a48e2012-03-07 12:19:03 -0800435 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800436 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800437 config = configs.get(board, self.build_config)
438 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
439 config=config)
David James58e0c092012-03-04 20:31:12 -0800440 self.archive_stages[board] = archive_stage
441
David James944a48e2012-03-07 12:19:03 -0800442 # Set up a process pool to run test/archive stages in the background.
443 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800444 queue = multiprocessing.Queue()
445 task = self._RunBackgroundStagesForBoard
446 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800447 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800448 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800449 archive_stage = self.archive_stages[board]
450 config = configs.get(board, self.build_config)
451 self._RunStage(stages.BuildTargetStage, board, archive_stage,
Chris Sosa1a87b3e2012-04-12 13:20:42 -0700452 self.release_tag, config=config)
David James58e0c092012-03-04 20:31:12 -0800453 self.archive_urls[board] = archive_stage.GetDownloadUrl()
454
David James944a48e2012-03-07 12:19:03 -0800455 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800456 queue.put([board])
457
Brian Harring3fec5a82012-03-01 05:57:03 -0800458
459class DistributedBuilder(SimpleBuilder):
460 """Build class that has special logic to handle distributed builds.
461
462 These builds sync using git/manifest logic in manifest_versions. In general
463 they use a non-distributed builder code for the bulk of the work.
464 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700465 def __init__(self, *args, **kwargs):
Brian Harring3fec5a82012-03-01 05:57:03 -0800466 """Initializes a buildbot builder.
467
468 Extra variables:
469 completion_stage_class: Stage used to complete a build. Set in the Sync
470 stage.
471 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700472 super(DistributedBuilder, self).__init__(*args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800473 self.completion_stage_class = None
474
475 def GetSyncInstance(self):
476 """Syncs the tree using one of the distributed sync logic paths.
477
478 Returns: the instance of the sync stage that was run.
479 """
480 # Determine sync class to use. CQ overrides PFQ bits so should check it
481 # first.
482 if cbuildbot_config.IsCQType(self.build_config['build_type']):
483 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
484 self.completion_stage_class = stages.CommitQueueCompletionStage
485 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
486 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
487 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
488 else:
489 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
490 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
491
492 return sync_stage
493
494 def Publish(self, was_build_successful):
495 """Completes build by publishing any required information."""
496 completion_stage = self._GetStageInstance(self.completion_stage_class,
497 was_build_successful)
498 completion_stage.Run()
499 name = completion_stage.name
500 if not results_lib.Results.WasStageSuccessful(name):
501 should_publish_changes = False
502 else:
503 should_publish_changes = (self.build_config['master'] and
504 was_build_successful)
505
506 if should_publish_changes:
507 self._RunStage(stages.PublishUprevChangesStage)
508
509 def RunStages(self):
510 """Runs simple builder logic and publishes information to overlays."""
511 was_build_successful = False
512 try:
David Jamesf55709e2012-03-13 09:10:15 -0700513 super(DistributedBuilder, self).RunStages()
514 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800515 except SystemExit as ex:
516 # If a stage calls sys.exit(0), it's exiting with success, so that means
517 # we should mark ourselves as successful.
518 if ex.code == 0:
519 was_build_successful = True
520 raise
521 finally:
522 self.Publish(was_build_successful)
523
Brian Harring3fec5a82012-03-01 05:57:03 -0800524
525def _ConfirmBuildRoot(buildroot):
526 """Confirm with user the inferred buildroot, and mark it as confirmed."""
527 warning = 'Using default directory %s as buildroot' % buildroot
528 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
529 full=True)
530 if response == cros_lib.NO:
531 print('Please specify a buildroot with the --buildroot option.')
532 sys.exit(0)
533
534 if not os.path.exists(buildroot):
535 os.mkdir(buildroot)
536
537 repository.CreateTrybotMarker(buildroot)
538
539
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700540def _ConfirmRemoteBuildbotRun():
541 """Confirm user wants to run with --buildbot --remote."""
542 warning = ('You are about to launch a PRODUCTION job! This is *NOT* a '
543 'trybot run! Are you sure?')
544 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
545 full=True)
546
547 if response == cros_lib.NO:
548 print('Please specify --pass-through="--debug".')
549 sys.exit(0)
550
551
Ryan Cui5ba7e152012-05-10 14:36:52 -0700552def _DetermineDefaultBuildRoot(sourceroot, internal_build):
Brian Harring3fec5a82012-03-01 05:57:03 -0800553 """Default buildroot to be under the directory that contains current checkout.
554
555 Arguments:
556 internal_build: Whether the build is an internal build
Ryan Cui5ba7e152012-05-10 14:36:52 -0700557 sourceroot: Use specified sourceroot.
Brian Harring3fec5a82012-03-01 05:57:03 -0800558 """
Ryan Cui5ba7e152012-05-10 14:36:52 -0700559 if not repository.IsARepoRoot(sourceroot):
560 cros_lib.Die('Could not find root of local checkout at %s. Please specify '
561 'using the --sourceroot option.' % sourceroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800562
563 # Place trybot buildroot under the directory containing current checkout.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700564 top_level = os.path.dirname(os.path.realpath(sourceroot))
Brian Harring3fec5a82012-03-01 05:57:03 -0800565 if internal_build:
566 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
567 else:
568 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
569
570 return buildroot
571
572
573def _BackupPreviousLog(log_file, backup_limit=25):
574 """Rename previous log.
575
576 Args:
577 log_file: The absolute path to the previous log.
578 """
579 if os.path.exists(log_file):
580 old_logs = sorted(glob.glob(log_file + '.*'),
581 key=distutils.version.LooseVersion)
582
583 if len(old_logs) >= backup_limit:
584 os.remove(old_logs[0])
585
586 last = 0
587 if old_logs:
588 last = int(old_logs.pop().rpartition('.')[2])
589
590 os.rename(log_file, log_file + '.' + str(last + 1))
591
David James944a48e2012-03-07 12:19:03 -0800592def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800593 """Helper function that wraps RunBuildStages()."""
594 def IsDistributedBuilder():
595 """Determines whether the build_config should be a DistributedBuilder."""
596 if not options.buildbot:
597 return False
598 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
599 chrome_rev = build_config['chrome_rev']
600 if options.chrome_rev: chrome_rev = options.chrome_rev
601 # We don't do distributed logic to TOT Chrome PFQ's, nor local
602 # chrome roots (e.g. chrome try bots)
603 if chrome_rev not in [constants.CHROME_REV_TOT,
604 constants.CHROME_REV_LOCAL,
605 constants.CHROME_REV_SPEC]:
606 return True
607
608 return False
609
Brian Harringd166aaf2012-05-14 18:31:53 -0700610 cros_lib.Info("cbuildbot executed with args %s"
611 % ' '.join(map(repr, sys.argv)))
Brian Harring3fec5a82012-03-01 05:57:03 -0800612
Ryan Cuif7f24692012-05-18 16:35:33 -0700613 target = DistributedBuilder if IsDistributedBuilder() else SimpleBuilder
Ryan Cuie1e4e662012-05-21 16:39:46 -0700614 buildbot = target(options, build_config)
Brian Harringd166aaf2012-05-14 18:31:53 -0700615 if not buildbot.Run():
616 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800617
618
619# Parser related functions
Ryan Cui5ba7e152012-05-10 14:36:52 -0700620def _CheckLocalPatches(sourceroot, local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800621 """Do an early quick check of the passed-in patches.
622
623 If the branch of a project is not specified we append the current branch the
624 project is on.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700625
626 Args:
627 sourceroot: The checkout where patches are coming from.
Brian Harring3fec5a82012-03-01 05:57:03 -0800628 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700629 verified_patches = []
630 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800631 components = patch.split(':')
632 if len(components) > 2:
633 msg = 'Specify local patches in project[:branch] format.'
634 raise optparse.OptionValueError(msg)
635
636 # validate project
637 project = components[0]
Ryan Cui5ba7e152012-05-10 14:36:52 -0700638 if not cros_lib.DoesProjectExist(sourceroot, project):
Brian Harring3fec5a82012-03-01 05:57:03 -0800639 raise optparse.OptionValueError('Project %s does not exist.' % project)
640
Ryan Cui5ba7e152012-05-10 14:36:52 -0700641 project_dir = cros_lib.GetProjectDir(sourceroot, project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800642
643 # If no branch was specified, we use the project's current branch.
644 if len(components) == 1:
645 branch = cros_lib.GetCurrentBranch(project_dir)
646 if not branch:
647 raise optparse.OptionValueError('project %s is not on a branch!'
648 % project)
649 # Append branch information to patch
650 patch = '%s:%s' % (project, branch)
651 else:
652 branch = components[1]
653 if not cros_lib.DoesLocalBranchExist(project_dir, branch):
654 raise optparse.OptionValueError('Project %s does not have branch %s'
655 % (project, branch))
656
Ryan Cuicedd8a52012-03-22 02:28:35 -0700657 verified_patches.append(patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800658
Ryan Cuicedd8a52012-03-22 02:28:35 -0700659 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800660
661
Brian Harring3fec5a82012-03-01 05:57:03 -0800662def _CheckChromeVersionOption(_option, _opt_str, value, parser):
663 """Upgrade other options based on chrome_version being passed."""
664 value = value.strip()
665
666 if parser.values.chrome_rev is None and value:
667 parser.values.chrome_rev = constants.CHROME_REV_SPEC
668
669 parser.values.chrome_version = value
670
671
672def _CheckChromeRootOption(_option, _opt_str, value, parser):
673 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800674 if parser.values.chrome_rev is None:
675 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
676
Ryan Cui5ba7e152012-05-10 14:36:52 -0700677 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800678
679
680def _CheckChromeRevOption(_option, _opt_str, value, parser):
681 """Validate the chrome_rev option."""
682 value = value.strip()
683 if value not in constants.VALID_CHROME_REVISIONS:
684 raise optparse.OptionValueError('Invalid chrome rev specified')
685
686 parser.values.chrome_rev = value
687
688
Ryan Cui5ba7e152012-05-10 14:36:52 -0700689class CustomParser(optparse.OptionParser):
690 def add_remote_option(self, *args, **kwargs):
691 """For arguments that are passed-through to remote trybot."""
692 return optparse.OptionParser.add_option(self, *args,
693 remote_pass_through=True,
694 **kwargs)
695
696
697class CustomGroup(optparse.OptionGroup):
698 def add_remote_option(self, *args, **kwargs):
699 """For arguments that are passed-through to remote trybot."""
700 return optparse.OptionGroup.add_option(self, *args,
701 remote_pass_through=True,
702 **kwargs)
703
704
Ryan Cuif7f24692012-05-18 16:35:33 -0700705# pylint: disable=W0613
Ryan Cui5ba7e152012-05-10 14:36:52 -0700706def check_path(option, opt, value):
707 """Expand paths and make them absolute."""
708 expanded = osutils.ExpandPath(value)
709 if expanded == '/':
710 raise optparse.OptionValueError('Invalid path %s specified for %s'
711 % (expanded, opt))
712
713 return expanded
714
715
716class CustomOption(optparse.Option):
717 """Subclass Option class to implement pass-through and path evaluation."""
718 TYPES = optparse.Option.TYPES + ('path',)
719 TYPE_CHECKER = optparse.Option.TYPE_CHECKER.copy()
720 TYPE_CHECKER['path'] = check_path
721
Ryan Cui79319ab2012-05-21 12:59:18 -0700722 ACTIONS = optparse.Option.ACTIONS + ('extend',)
723 STORE_ACTIONS = optparse.Option.STORE_ACTIONS + ('extend',)
724 TYPED_ACTIONS = optparse.Option.TYPED_ACTIONS + ('extend',)
725 ALWAYS_TYPED_ACTIONS = optparse.Option.ALWAYS_TYPED_ACTIONS + ('extend',)
726
Ryan Cui5ba7e152012-05-10 14:36:52 -0700727 def __init__(self, *args, **kwargs):
728 # The remote_pass_through argument specifies whether we should directly
729 # pass the argument (with its value) onto the remote trybot.
730 self.pass_through = kwargs.pop('remote_pass_through', False)
731 optparse.Option.__init__(self, *args, **kwargs)
732
733 def take_action(self, action, dest, opt, value, values, parser):
Ryan Cui79319ab2012-05-21 12:59:18 -0700734 if action == 'extend':
735 lvalue = value.split(' ')
736 values.ensure_value(dest, []).extend(lvalue)
737 else:
738 optparse.Option.take_action(self, action, dest, opt, value, values,
739 parser)
740
Ryan Cui5ba7e152012-05-10 14:36:52 -0700741 if self.pass_through:
742 parser.values.pass_through_args.append(opt)
743 if self.nargs and self.nargs > 1:
744 # value is a tuple if nargs > 1
745 string_list = [str(val) for val in list(value)]
746 parser.values.pass_through_args.extend(string_list)
747 elif value:
748 parser.values.pass_through_args.append(str(value))
749
750
Brian Harring3fec5a82012-03-01 05:57:03 -0800751def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700752 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800753 # Parse options
754 usage = "usage: %prog [options] buildbot_config"
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700755 parser = CustomParser(usage=usage, option_class=CustomOption)
Brian Harring3fec5a82012-03-01 05:57:03 -0800756
757 # Main options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700758 # The remote_pass_through parameter to add_option is implemented by the
759 # CustomOption class. See CustomOption for more information.
Brian Harring3fec5a82012-03-01 05:57:03 -0800760 parser.add_option('-a', '--all', action='store_true', dest='print_all',
761 default=False,
762 help=('List all of the buildbot configs available. Use '
763 'with the --list option'))
Ryan Cuie1e4e662012-05-21 16:39:46 -0700764 parser.add_remote_option('-b', '--branch',
765 help='The manifest branch to test. The branch to '
766 'check the buildroot out to.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700767 parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700768 help='Root directory where source is checked out to, and '
769 'where the build occurs. For external build configs, '
770 "defaults to 'trybot' directory at top level of your "
771 'repo-managed checkout.')
772 parser.add_remote_option('--chrome_rev', default=None, type='string',
773 action='callback', dest='chrome_rev',
774 callback=_CheckChromeRevOption,
775 help=('Revision of Chrome to use, of type [%s]'
776 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cui79319ab2012-05-21 12:59:18 -0700777 parser.add_remote_option('-g', '--gerrit-patches', action='extend',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700778 default=[], type='string',
779 metavar="'Id1 *int_Id2...IdN'",
780 help=("Space-separated list of short-form Gerrit "
781 "Change-Id's or change numbers to patch. "
782 "Please prepend '*' to internal Change-Id's"))
Brian Harring3fec5a82012-03-01 05:57:03 -0800783 parser.add_option('-l', '--list', action='store_true', dest='list',
784 default=False,
785 help=('List the suggested trybot configs to use. Use '
786 '--all to list all of the available configs.'))
Ryan Cui54da0702012-04-19 18:38:08 -0700787 parser.add_option('--local', default=False, action='store_true',
788 help=('Specifies that this tryjob should be run locally.'))
Ryan Cui79319ab2012-05-21 12:59:18 -0700789 parser.add_option('-p', '--local-patches', action='extend', default=[],
Brian Harring3fec5a82012-03-01 05:57:03 -0800790 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
791 help=('Space-separated list of project branches with '
792 'patches to apply. Projects are specified by name. '
793 'If no branch is specified the current branch of the '
794 'project will be used.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700795 parser.add_remote_option('--profile', default=None, type='string',
796 action='store', dest='profile',
797 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800798 parser.add_option('--remote', default=False, action='store_true',
Brian Harring3fec5a82012-03-01 05:57:03 -0800799 help=('Specifies that this tryjob should be run remotely.'))
800
801 # Advanced options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700802 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800803 parser,
804 'Advanced Options',
805 'Caution: use these options at your own risk.')
806
Ryan Cui42aeae32012-05-21 17:09:09 -0700807 # bootstrap-args are not verified by the bootstrap code. It gets passed
808 # direcly to the bootstrap re-execution.
809 group.add_remote_option('--bootstrap-args', action='append',
810 default=[], help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700811 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
812 default=False, help='This is running on a buildbot')
813 group.add_remote_option('--buildnumber', help='build number', type='int',
814 default=0)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700815 group.add_option('--chrome_root', default=None, type='path',
816 action='callback', callback=_CheckChromeRootOption,
817 dest='chrome_root', help='Local checkout of Chrome to use.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700818 group.add_remote_option('--chrome_version', default=None, type='string',
819 action='callback', dest='chrome_version',
820 callback=_CheckChromeVersionOption,
821 help='Used with SPEC logic to force a particular SVN '
822 'revision of chrome rather than the latest.')
823 group.add_remote_option('--clobber', action='store_true', dest='clobber',
824 default=False,
825 help='Clears an old checkout before syncing')
826 group.add_remote_option('--lkgm', action='store_true', dest='lkgm',
827 default=False,
828 help='Sync to last known good manifest blessed by '
829 'PFQ')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700830 parser.add_option('--log_dir', dest='log_dir', type='path',
Brian Harring3fec5a82012-03-01 05:57:03 -0800831 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700832 group.add_remote_option('--maxarchives', dest='max_archive_builds',
833 default=3, type='int',
834 help="Change the local saved build count limit.")
835 group.add_remote_option('--noarchive', action='store_false', dest='archive',
836 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700837 group.add_remote_option('--nobootstrap', action='store_false',
838 dest='bootstrap', default=True,
839 help="Don't checkout and run from a standalone "
840 "chromite repo.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700841 group.add_remote_option('--nobuild', action='store_false', dest='build',
842 default=True,
843 help="Don't actually build (for cbuildbot dev)")
844 group.add_remote_option('--noclean', action='store_false', dest='clean',
845 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700846 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
847 default=True,
848 help='Disable cbuildbots usage of cgroups.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700849 group.add_remote_option('--noprebuilts', action='store_false',
850 dest='prebuilts', default=True,
851 help="Don't upload prebuilts.")
852 group.add_remote_option('--nosync', action='store_false', dest='sync',
853 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700854 group.add_remote_option('--notests', action='store_false', dest='tests',
855 default=True,
856 help='Override values from buildconfig and run no '
857 'tests.')
858 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
859 default=True,
860 help='Override values from buildconfig and never '
861 'uprev.')
862 group.add_option('--pass-through', dest='pass_through_args', action='append',
863 type='string', default=[], help=optparse.SUPPRESS_HELP)
Brian Harring3fec5a82012-03-01 05:57:03 -0800864 group.add_option('--reference-repo', action='store', default=None,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700865 dest='reference_repo',
866 help='Reuse git data stored in an existing repo '
867 'checkout. This can drastically reduce the network '
868 'time spent setting up the trybot checkout. By '
869 "default, if this option isn't given but cbuildbot "
870 'is invoked from a repo checkout, cbuildbot will '
871 'use the repo root.')
Brian Harring37e559b2012-05-22 20:47:32 -0700872 # Used for handling forwards/backwards compatibility for --resume and
873 # --bootstrap.
874 group.add_option('--reexec-api-version', dest='output_api_version',
875 action='store_true', default=False,
876 help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700877 # Indicates this is running on a remote trybot machine.
Ryan Cuiba41ad32012-03-08 17:15:29 -0800878 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700879 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700880 # Patches uploaded by trybot client when run using the -p option.
Ryan Cui79319ab2012-05-21 12:59:18 -0700881 group.add_remote_option('--remote-patches', action='extend', default=[],
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700882 help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700883 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700884 help='Skip stages already successfully completed.')
885 group.add_remote_option('--timeout', action='store', type='int', default=0,
886 help='Specify the maximum amount of time this job '
887 'can run for, at which point the build will be '
888 'aborted. If set to zero, then there is no '
889 'timeout.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700890 # Specify specific remote tryslaves to run on.
891 group.add_option('--slaves', action='extend', default=[],
892 help=optparse.SUPPRESS_HELP)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700893 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT,
894 help=optparse.SUPPRESS_HELP)
Ryan Cuif7f24692012-05-18 16:35:33 -0700895 # Causes cbuildbot to bootstrap itself twice, in the sequence A->B->C.
896 # A(unpatched) patches and bootstraps B. B patches and bootstraps C.
897 group.add_remote_option('--test-bootstrap', action='store_true',
898 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cui39bdbbf2012-02-29 16:15:39 -0800899 group.add_option('--test-tryjob', action='store_true',
900 default=False,
901 help='Submit a tryjob to the test repository. Will not '
902 'show up on the production trybot waterfall.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700903 group.add_remote_option('--validation_pool', default=None,
904 help='Path to a pickled validation pool. Intended '
905 'for use only with the commit queue.')
906 group.add_remote_option('--version', dest='force_version', default=None,
907 help='Used with manifest logic. Forces use of this '
908 'version rather than create or get latest.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800909
910 parser.add_option_group(group)
911
912 # Debug options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700913 group = CustomGroup(parser, "Debug Options")
Brian Harring3fec5a82012-03-01 05:57:03 -0800914
Ryan Cui85867972012-02-23 18:21:49 -0800915 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800916 help='Override some options to run as a developer.')
917 group.add_option('--dump_config', action='store_true', dest='dump_config',
918 default=False,
919 help='Dump out build config options, and exit.')
920 group.add_option('--notee', action='store_false', dest='tee', default=True,
921 help="Disable logging and internal tee process. Primarily "
922 "used for debugging cbuildbot itself.")
923 parser.add_option_group(group)
924 return parser
925
926
Ryan Cui85867972012-02-23 18:21:49 -0800927def _FinishParsing(options, args):
928 """Perform some parsing tasks that need to take place after optparse.
929
930 This function needs to be easily testable! Keep it free of
931 environment-dependent code. Put more detailed usage validation in
932 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800933
934 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800935 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800936 """
Brian Harring07039b52012-05-13 17:56:47 -0700937 # Setup logging levels first so any parsing triggered log messages
938 # are appropriately filtered.
939 logging.getLogger().setLevel(
940 logging.DEBUG if options.debug else logging.INFO)
941
Brian Harring3fec5a82012-03-01 05:57:03 -0800942 if options.chrome_root:
943 if options.chrome_rev != constants.CHROME_REV_LOCAL:
944 cros_lib.Die('Chrome rev must be %s if chrome_root is set.' %
945 constants.CHROME_REV_LOCAL)
946 else:
947 if options.chrome_rev == constants.CHROME_REV_LOCAL:
948 cros_lib.Die('Chrome root must be set if chrome_rev is %s.' %
949 constants.CHROME_REV_LOCAL)
950
951 if options.chrome_version:
952 if options.chrome_rev != constants.CHROME_REV_SPEC:
953 cros_lib.Die('Chrome rev must be %s if chrome_version is set.' %
954 constants.CHROME_REV_SPEC)
955 else:
956 if options.chrome_rev == constants.CHROME_REV_SPEC:
957 cros_lib.Die('Chrome rev must not be %s if chrome_version is not set.' %
958 constants.CHROME_REV_SPEC)
959
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700960 patches = bool(options.gerrit_patches or options.local_patches)
961 if options.remote:
962 if options.local:
963 cros_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -0700964
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700965 if not options.buildbot and not patches:
966 cros_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800967
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700968 # --debug needs to be explicitly passed through for remote invocations.
969 release_mode_with_patches = (options.buildbot and patches and
970 '--debug' not in options.pass_through_args)
971 else:
972 if len(args) > 1:
973 cros_lib.Die('Multiple configs not supported if not running with '
974 '--remote.')
975
Ryan Cui79319ab2012-05-21 12:59:18 -0700976 if options.slaves:
977 cros_lib.Die('Cannot use --slaves if not running with --remote.')
978
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700979 release_mode_with_patches = (options.buildbot and patches and
980 not options.debug)
981
982 # When running in release mode, make sure we are running with checked-in code.
983 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
984 # a release image with checked-in code for CrOS packages.
985 if release_mode_with_patches:
986 cros_lib.Die('Cannot provide patches when running with --buildbot!')
Brian Harring3fec5a82012-03-01 05:57:03 -0800987
Ryan Cuiba41ad32012-03-08 17:15:29 -0800988 if options.buildbot and options.remote_trybot:
989 cros_lib.Die('--buildbot and --remote-trybot cannot be used together.')
990
Ryan Cui85867972012-02-23 18:21:49 -0800991 # Record whether --debug was set explicitly vs. it was inferred.
992 options.debug_forced = False
993 if options.debug:
994 options.debug_forced = True
995 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800996 # We don't set debug by default for
997 # 1. --buildbot invocations.
998 # 2. --remote invocations, because it needs to push changes to the tryjob
999 # repo.
1000 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -08001001
Brian Harring3fec5a82012-03-01 05:57:03 -08001002
Brian Harring1d7ba942012-04-24 06:37:18 -07001003# pylint: disable=W0613
Ryan Cui85867972012-02-23 18:21:49 -08001004def _PostParseCheck(options, args):
1005 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -08001006
Ryan Cui85867972012-02-23 18:21:49 -08001007 Args:
1008 options/args: The options/args object returned by optparse
1009 """
Ryan Cuie1e4e662012-05-21 16:39:46 -07001010 if not options.branch:
1011 options.branch = _GetChromiteTrackingBranch()
1012
Ryan Cui5ba7e152012-05-10 14:36:52 -07001013 if options.local_patches and not repository.IsARepoRoot(options.sourceroot):
1014 raise Exception('Could not find repo checkout at %s!'
1015 % options.sourceroot)
1016
Brian Harring1d7ba942012-04-24 06:37:18 -07001017 try:
1018 # TODO(rcui): Split this into two stages, one that parses, another that
1019 # validates. Parsing step will be called by _FinishParsing().
1020 options.local_patches = _CheckLocalPatches(
Ryan Cui5ba7e152012-05-10 14:36:52 -07001021 options.sourceroot,
Ryan Cui79319ab2012-05-21 12:59:18 -07001022 options.local_patches)
Brian Harring1d7ba942012-04-24 06:37:18 -07001023 except optparse.OptionValueError as e:
1024 cros_lib.Die(str(e))
1025
1026 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
1027 if (default and not any([options.local, options.buildbot,
1028 options.remote, options.remote_trybot])):
1029 cros_lib.Info("CBUILDBOT_DEFAULT_MODE=%s env var detected, using it."
1030 % default)
1031 default = default.lower()
1032 if default == 'local':
1033 options.local = True
1034 elif default == 'remote':
1035 options.remote = True
1036 elif default == 'buildbot':
1037 options.buildbot = True
1038 else:
1039 cros_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
1040 % default)
Ryan Cui85867972012-02-23 18:21:49 -08001041
1042
1043def _ParseCommandLine(parser, argv):
1044 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -08001045 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -07001046
1047 if options.output_api_version:
1048 print _REEXEC_API_VERSION
1049 sys.exit(0)
1050
Ryan Cui54da0702012-04-19 18:38:08 -07001051 if options.list:
1052 _PrintValidConfigs(options.print_all)
1053 sys.exit(0)
1054
Ryan Cui8be16062012-04-24 12:05:26 -07001055 # Strip out null arguments.
1056 # TODO(rcui): Remove when buildbot is fixed
1057 args = [arg for arg in args if arg]
1058 if not args:
1059 parser.error('Invalid usage. Use -h to see usage. Use -l to list '
1060 'supported configs.')
1061
Ryan Cui85867972012-02-23 18:21:49 -08001062 _FinishParsing(options, args)
1063 return options, args
1064
1065
1066def main(argv):
1067 # Set umask to 022 so files created by buildbot are readable.
1068 os.umask(022)
1069
1070 if cros_lib.IsInsideChroot():
1071 cros_lib.Die('Please run cbuildbot from outside the chroot.')
1072
1073 parser = _CreateParser()
1074 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -08001075
Brian Harring3fec5a82012-03-01 05:57:03 -08001076 _PostParseCheck(options, args)
1077
1078 if options.remote:
Chris Sosa4f6ffaf2012-05-01 17:05:44 -07001079 cros_lib.logger.setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001080
Brian Harring3fec5a82012-03-01 05:57:03 -08001081 # Verify configs are valid.
1082 for bot in args:
1083 _GetConfig(bot)
1084
1085 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -08001086 print 'Verifying patches...'
Ryan Cuie1e4e662012-05-21 16:39:46 -07001087 patch_pool = AcquirePoolFromOptions(options)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001088
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001089 # --debug need to be explicitly passed through for remote invocations.
1090 if options.buildbot and '--debug' not in options.pass_through_args:
1091 _ConfirmRemoteBuildbotRun()
1092
Ryan Cui16ca5812012-03-08 20:34:27 -08001093 print 'Submitting tryjob...'
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001094 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cui39bdbbf2012-02-29 16:15:39 -08001095 tryjob.Submit(testjob=options.test_tryjob, dryrun=options.debug)
Ryan Cui16ca5812012-03-08 20:34:27 -08001096 print 'Tryjob submitted!'
1097 print ('Go to %s to view the status of your job.'
Ryan Cui4906e1c2012-04-03 20:09:34 -07001098 % tryjob.GetTrybotWaterfallLink())
Brian Harring3fec5a82012-03-01 05:57:03 -08001099 sys.exit(0)
Ryan Cui54da0702012-04-19 18:38:08 -07001100 elif (not options.buildbot and not options.remote_trybot
1101 and not options.resume and not options.local):
1102 cros_lib.Warning('Running in LOCAL TRYBOT mode! Use --remote to submit '
1103 'REMOTE tryjobs. Use --local to suppress this message.')
1104 cros_lib.Warning('Starting April 30th, --local will be required to run the '
1105 'local trybot.')
1106 time.sleep(5)
Brian Harring3fec5a82012-03-01 05:57:03 -08001107
Ryan Cui8be16062012-04-24 12:05:26 -07001108 # Only expecting one config
1109 bot_id = args[-1]
1110 build_config = _GetConfig(bot_id)
Brian Harring3fec5a82012-03-01 05:57:03 -08001111
1112 if options.reference_repo is None:
Ryan Cui5ba7e152012-05-10 14:36:52 -07001113 repo_path = os.path.join(options.sourceroot, '.repo')
Brian Harring3fec5a82012-03-01 05:57:03 -08001114 # If we're being run from a repo checkout, reuse the repo's git pool to
1115 # cut down on sync time.
1116 if os.path.exists(repo_path):
Ryan Cui5ba7e152012-05-10 14:36:52 -07001117 options.reference_repo = options.sourceroot
Brian Harring3fec5a82012-03-01 05:57:03 -08001118 elif options.reference_repo:
1119 if not os.path.exists(options.reference_repo):
1120 parser.error('Reference path %s does not exist'
1121 % (options.reference_repo,))
1122 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1123 parser.error('Reference path %s does not look to be the base of a '
1124 'repo checkout; no .repo exists in the root.'
1125 % (options.reference_repo,))
Ryan Cuid4a24212012-04-04 18:08:12 -07001126
Brian Harringf11bf682012-05-14 15:53:43 -07001127 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001128 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001129 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1130 'be used together. Cgroup support is required for '
1131 'buildbot/remote-trybot mode.')
Brian Harring470f6112012-03-02 11:47:10 -08001132 if not cgroups.Cgroup.CgroupsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001133 parser.error('Option --buildbot/--remote-trybot was given, but this '
1134 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001135
Brian Harring351ce442012-03-09 16:38:14 -08001136 missing = []
1137 for program in _BUILDBOT_REQUIRED_BINARIES:
1138 ret = cros_lib.RunCommand('which %s' % program, shell=True,
1139 redirect_stderr=True, redirect_stdout=True,
1140 error_code_ok=True, print_cmd=False)
1141 if ret.returncode != 0:
1142 missing.append(program)
1143
1144 if missing:
Ryan Cuid4a24212012-04-04 18:08:12 -07001145 parser.error("Option --buildbot/--remote-trybot requires the following "
1146 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001147 % (', '.join(missing)))
1148
Brian Harring3fec5a82012-03-01 05:57:03 -08001149 if options.reference_repo:
1150 options.reference_repo = os.path.abspath(options.reference_repo)
1151
1152 if options.dump_config:
1153 # This works, but option ordering is bad...
1154 print 'Configuration %s:' % bot_id
1155 pretty_printer = pprint.PrettyPrinter(indent=2)
1156 pretty_printer.pprint(build_config)
1157 sys.exit(0)
1158
1159 if not options.buildroot:
1160 if options.buildbot:
1161 parser.error('Please specify a buildroot with the --buildroot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001162
Ryan Cui5ba7e152012-05-10 14:36:52 -07001163 options.buildroot = _DetermineDefaultBuildRoot(options.sourceroot,
1164 build_config['internal'])
Brian Harring470f6112012-03-02 11:47:10 -08001165 # We use a marker file in the buildroot to indicate the user has
1166 # consented to using this directory.
1167 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1168 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001169
1170 # Sanity check of buildroot- specifically that it's not pointing into the
1171 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001172 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -08001173 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001174 parser.error('Configured buildroot %s points into a repository checkout, '
1175 'rather than the root of it. This is not supported.'
1176 % options.buildroot)
1177
Brian Harringd166aaf2012-05-14 18:31:53 -07001178 log_file = None
1179 if options.tee:
1180 default_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1181 dirname = options.log_dir or default_dir
1182 log_file = os.path.join(dirname, _BUILDBOT_LOG_FILE)
1183
1184 osutils.SafeMakedirs(dirname)
1185 _BackupPreviousLog(log_file)
1186
Brian Harringc2d09d92012-05-13 22:03:15 -07001187 with cros_lib.ContextManagerStack() as stack:
1188 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1189 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001190
Brian Harringc2d09d92012-05-13 22:03:15 -07001191 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001192 # If we're in resume mode, use our parents tempdir rather than
1193 # nesting another layer.
Brian Harringc2d09d92012-05-13 22:03:15 -07001194 stack.Add(osutils.TempDirContextManager, 'cbuildbot-tmp')
1195 logging.debug("Cbuildbot tempdir is %r.", os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001196
1197 if log_file is not None:
1198 stack.Add(tee.Tee, log_file)
1199 options.preserve_paths = set([_DEFAULT_LOG_DIR])
1200
Brian Harringc2d09d92012-05-13 22:03:15 -07001201 if options.cgroups:
1202 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001203
Brian Harringc2d09d92012-05-13 22:03:15 -07001204 # Mark everything between EnforcedCleanupSection and here as having to
1205 # be rolled back via the contextmanager cleanup handlers. This
1206 # ensures that sudo bits cannot outlive cbuildbot, that anything
1207 # cgroups would kill gets killed, etc.
1208 critical_section.ForkWatchdog()
Brian Harringd166aaf2012-05-14 18:31:53 -07001209
Brian Harringc2d09d92012-05-13 22:03:15 -07001210 if options.timeout > 0:
1211 stack.Add(cros_lib.Timeout, options.timeout)
Brian Harringa184efa2012-03-04 11:51:25 -08001212
Brian Harringc2d09d92012-05-13 22:03:15 -07001213 if not options.buildbot:
1214 build_config = cbuildbot_config.OverrideConfigForTrybot(
1215 build_config,
1216 options.remote_trybot)
1217
1218 _RunBuildStagesWrapper(options, build_config)