blob: 0285c1a9abf9b569c09678e171bfdd8968bcd312 [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
Brian Harring1b8c4c82012-05-29 23:03:04 -070014import errno
Brian Harring3fec5a82012-03-01 05:57:03 -080015import glob
Chris Sosa4f6ffaf2012-05-01 17:05:44 -070016import logging
David James58e0c092012-03-04 20:31:12 -080017import multiprocessing
Brian Harring3fec5a82012-03-01 05:57:03 -080018import optparse
19import os
20import pprint
21import sys
Ryan Cui54da0702012-04-19 18:38:08 -070022import time
Brian Harring3fec5a82012-03-01 05:57:03 -080023
24from chromite.buildbot import builderstage as bs
25from chromite.buildbot import cbuildbot_background as background
26from 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
30from chromite.buildbot import gerrit_helper
31from chromite.buildbot import patch as cros_patch
32from chromite.buildbot import remote_try
33from chromite.buildbot import repository
34from chromite.buildbot import tee
Ryan Cui16d9e1f2012-05-11 10:50:18 -070035from chromite.buildbot import trybot_patch_pool
Brian Harring3fec5a82012-03-01 05:57:03 -080036
Brian Harringc92a7012012-02-29 10:11:34 -080037from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080038from chromite.lib import cleanup
Brian Harring1b8c4c82012-05-29 23:03:04 -070039from chromite.lib import cros_build_lib
Brian Harringaf019fb2012-05-10 15:06:13 -070040from chromite.lib import osutils
Brian Harring3fec5a82012-03-01 05:57:03 -080041from chromite.lib import sudo
42
Ryan Cuiadd49122012-03-21 22:19:58 -070043
Brian Harring1b8c4c82012-05-29 23:03:04 -070044cros_build_lib.STRICT_SUDO = True
Brian Harring3fec5a82012-03-01 05:57:03 -080045
46_DEFAULT_LOG_DIR = 'cbuildbot_logs'
47_BUILDBOT_LOG_FILE = 'cbuildbot.log'
48_DEFAULT_EXT_BUILDROOT = 'trybot'
49_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Brian Harring3fec5a82012-03-01 05:57:03 -080050_DISTRIBUTED_TYPES = [constants.COMMIT_QUEUE_TYPE, constants.PFQ_TYPE,
51 constants.CANARY_TYPE, constants.CHROME_PFQ_TYPE,
52 constants.PALADIN_TYPE]
Brian Harring351ce442012-03-09 16:38:14 -080053_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Brian Harring3fec5a82012-03-01 05:57:03 -080054
Brian Harring37e559b2012-05-22 20:47:32 -070055# Used by --resume and --bootstrap to decipher which options they
56# can pass to the target cbuildbot (since it may not have that
57# option).
58# Format is Major:Minor. Minor is used for tracking new options added
59# that aren't critical to the older version if it's not ran.
60# Major is used for tracking heavy API breakage- for example, no longer
61# supporting the --resume option.
62_REEXEC_API_MAJOR = 0
63_REEXEC_API_MINOR = 1
64_REEXEC_API_VERSION = '%i.%i' % (_REEXEC_API_MAJOR, _REEXEC_API_MINOR)
65
Brian Harring3fec5a82012-03-01 05:57:03 -080066
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070067def _PrintValidConfigs(display_all=False):
Brian Harring3fec5a82012-03-01 05:57:03 -080068 """Print a list of valid buildbot configs.
69
70 Arguments:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070071 display_all: Print all configs. Otherwise, prints only configs with
72 trybot_list=True.
Brian Harring3fec5a82012-03-01 05:57:03 -080073 """
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070074 def _GetSortKey(config_name):
75 config_dict = cbuildbot_config.config[config_name]
76 return (not config_dict['trybot_list'], config_dict['description'],
77 config_name)
78
Brian Harring3fec5a82012-03-01 05:57:03 -080079 COLUMN_WIDTH = 45
80 print 'config'.ljust(COLUMN_WIDTH), 'description'
81 print '------'.ljust(COLUMN_WIDTH), '-----------'
82 config_names = cbuildbot_config.config.keys()
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070083 config_names.sort(key=_GetSortKey)
Brian Harring3fec5a82012-03-01 05:57:03 -080084 for name in config_names:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070085 if display_all or cbuildbot_config.config[name]['trybot_list']:
86 desc = cbuildbot_config.config[name].get('description')
87 desc = desc if desc else ''
Brian Harring3fec5a82012-03-01 05:57:03 -080088 print name.ljust(COLUMN_WIDTH), desc
89
90
91def _GetConfig(config_name):
92 """Gets the configuration for the build"""
93 if not cbuildbot_config.config.has_key(config_name):
94 print 'Non-existent configuration %s specified.' % config_name
95 print 'Please specify one of:'
96 _PrintValidConfigs()
97 sys.exit(1)
98
99 result = cbuildbot_config.config[config_name]
100
101 return result
102
103
104def _GetChromiteTrackingBranch():
David James66009462012-03-25 10:08:38 -0700105 """Returns the remote branch associated with chromite."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800106 cwd = os.path.dirname(os.path.realpath(__file__))
Brian Harring1b8c4c82012-05-29 23:03:04 -0700107 result = cros_build_lib.GetTrackingBranch(cwd, for_checkout=False,
108 fallback=False)
Brian Harring609dc4e2012-05-07 02:17:44 -0700109 if result is not None:
110 remote, branch = result
111 if branch.startswith("refs/heads/"):
112 # Normal scenario.
Brian Harring1b8c4c82012-05-29 23:03:04 -0700113 return cros_build_lib.StripLeadingRefsHeads(branch)
Brian Harring609dc4e2012-05-07 02:17:44 -0700114 # Reaching here means it was refs/remotes/m/blah, or just plain invalid,
115 # or that we're on a detached head in a repo not managed by chromite.
116
117 # Manually try the manifest next.
118 try:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700119 manifest = cros_build_lib.ManifestCheckout.Cached(cwd)
Brian Harring609dc4e2012-05-07 02:17:44 -0700120 # Ensure the manifest knows of this checkout.
121 if manifest.FindProjectFromPath(cwd) is not None:
122 return manifest.manifest_branch
123 except EnvironmentError, e:
124 if e.errno != errno.ENOENT:
125 raise
126 # Not a manifest checkout.
Brian Harring1b8c4c82012-05-29 23:03:04 -0700127 cros_build_lib.Warning(
Brian Harring609dc4e2012-05-07 02:17:44 -0700128 "Chromite checkout at %s isn't controlled by repo, nor is it on a "
129 "branch (or if it is, the tracking configuration is missing or broken). "
130 "Falling back to assuming the chromite checkout is derived from "
131 "'master'; this *may* result in breakage." % cwd)
132 return 'master'
Brian Harring3fec5a82012-03-01 05:57:03 -0800133
134
Ryan Cuie1e4e662012-05-21 16:39:46 -0700135def AcquirePoolFromOptions(options):
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700136 """Generate patch objects from passed in options.
Brian Harring3fec5a82012-03-01 05:57:03 -0800137
138 Args:
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700139 options: The options object generated by optparse.
Brian Harring3fec5a82012-03-01 05:57:03 -0800140
Ryan Cuif7f24692012-05-18 16:35:33 -0700141 Returns:
142 trybot_patch_pool.TrybotPatchPool object.
143
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700144 Raises:
145 gerrit_helper.GerritException, cros_patch.PatchException
Brian Harring3fec5a82012-03-01 05:57:03 -0800146 """
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700147 gerrit_patches = []
148 local_patches = []
149 remote_patches = []
Brian Harring3fec5a82012-03-01 05:57:03 -0800150
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700151 if options.gerrit_patches:
152 gerrit_patches = gerrit_helper.GetGerritPatchInfo(
153 options.gerrit_patches)
154 for patch in gerrit_patches:
155 if patch.IsAlreadyMerged():
Brian Harring1b8c4c82012-05-29 23:03:04 -0700156 cros_build_lib.Warning('Patch %s has already been merged.' % str(patch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800157
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700158 if options.local_patches:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700159 manifest = cros_build_lib.ManifestCheckout.Cached(options.sourceroot)
Brian Harring609dc4e2012-05-07 02:17:44 -0700160 local_patches = cros_patch.PrepareLocalPatches(manifest,
161 options.local_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800162
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700163 if options.remote_patches:
164 remote_patches = cros_patch.PrepareRemotePatches(
165 options.remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800166
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700167 return trybot_patch_pool.TrybotPatchPool(gerrit_patches, local_patches,
168 remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800169
170
Brian Harring3fec5a82012-03-01 05:57:03 -0800171class 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
Brian Harring3fec5a82012-03-01 05:57:03 -0800206 self._RunStage(stages.CleanUpStage)
207
208 def _GetStageInstance(self, stage, *args, **kwargs):
209 """Helper function to get an instance given the args.
210
David James944a48e2012-03-07 12:19:03 -0800211 Useful as almost all stages just take in options and build_config.
Brian Harring3fec5a82012-03-01 05:57:03 -0800212 """
David James944a48e2012-03-07 12:19:03 -0800213 config = kwargs.pop('config', self.build_config)
214 return stage(self.options, config, *args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800215
216 def _SetReleaseTag(self):
217 """Sets the release tag from the manifest_manager.
218
219 Must be run after sync stage as syncing enables us to have a release tag.
220 """
221 # Extract version we have decided to build into self.release_tag.
222 manifest_manager = stages.ManifestVersionedSyncStage.manifest_manager
223 if manifest_manager:
224 self.release_tag = manifest_manager.current_version
225
226 def _RunStage(self, stage, *args, **kwargs):
227 """Wrapper to run a stage."""
228 stage_instance = self._GetStageInstance(stage, *args, **kwargs)
229 return stage_instance.Run()
230
231 def GetSyncInstance(self):
232 """Returns an instance of a SyncStage that should be run.
233
234 Subclasses must override this method.
235 """
236 raise NotImplementedError()
237
238 def RunStages(self):
239 """Subclasses must override this method. Runs the appropriate code."""
240 raise NotImplementedError()
241
Brian Harring3fec5a82012-03-01 05:57:03 -0800242 def _ShouldReExecuteInBuildRoot(self):
243 """Returns True if this build should be re-executed in the buildroot."""
244 abs_buildroot = os.path.abspath(self.options.buildroot)
245 return not os.path.abspath(__file__).startswith(abs_buildroot)
246
247 def _ReExecuteInBuildroot(self, sync_instance):
248 """Reexecutes self in buildroot and returns True if build succeeds.
249
250 This allows the buildbot code to test itself when changes are patched for
251 buildbot-related code. This is a no-op if the buildroot == buildroot
252 of the running chromite checkout.
253
254 Args:
255 sync_instance: Instance of the sync stage that was run to sync.
256
257 Returns:
258 True if the Build succeeded.
259 """
Brian Harring3fec5a82012-03-01 05:57:03 -0800260 if not self.options.resume:
Ryan Cuif7f24692012-05-18 16:35:33 -0700261 results_lib.WriteCheckpoint(self.options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800262
Brian Harring37e559b2012-05-22 20:47:32 -0700263 # Get the re-exec API version of the target chromite; if it's incompatible
264 # with us, bail now.
Brian Harring1b8c4c82012-05-29 23:03:04 -0700265 api = cros_build_lib.RunCommandCaptureOutput(
Brian Harring37e559b2012-05-22 20:47:32 -0700266 [constants.PATH_TO_CBUILDBOT] + ['--reexec-api-version'],
267 cwd=self.options.buildroot, error_code_ok=True)
268 # If the command failed, then we're targeting a cbuildbot that lacks the
269 # option; assume 0:0 (ie, initial state).
270 major, minor = 0, 0
271 if api.returncode == 0:
272 major, minor = map(int, api.output.strip().split('.', 1))
273
274 if major != _REEXEC_API_MAJOR:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700275 cros_build_lib.Die(
Brian Harring37e559b2012-05-22 20:47:32 -0700276 'The targeted version of chromite in buildroot %s requires '
277 'api version %i, but we are api version %i. We cannot proceed.'
278 % (self.options.buildroot, major, _REEXEC_API_MAJOR))
279
Brian Harring3fec5a82012-03-01 05:57:03 -0800280 # Re-write paths to use absolute paths.
281 # Suppress any timeout options given from the commandline in the
282 # invoked cbuildbot; our timeout will enforce it instead.
Brian Harringf11bf682012-05-14 15:53:43 -0700283 args_to_append = ['--resume', '--timeout', '0', '--notee', '--nocgroups',
284 '--buildroot', os.path.abspath(self.options.buildroot)]
Brian Harring3fec5a82012-03-01 05:57:03 -0800285
286 if self.options.chrome_root:
287 args_to_append += ['--chrome_root',
288 os.path.abspath(self.options.chrome_root)]
289
290 if stages.ManifestVersionedSyncStage.manifest_manager:
291 ver = stages.ManifestVersionedSyncStage.manifest_manager.current_version
292 args_to_append += ['--version', ver]
293
294 if isinstance(sync_instance, stages.CommitQueueSyncStage):
295 vp_file = sync_instance.SaveValidationPool()
296 args_to_append += ['--validation_pool', vp_file]
297
298 # Re-run the command in the buildroot.
299 # Finally, be generous and give the invoked cbuildbot 30s to shutdown
300 # when something occurs. It should exit quicker, but the sigterm may
301 # hit while the system is particularly busy.
Brian Harring1b8c4c82012-05-29 23:03:04 -0700302 return_obj = cros_build_lib.RunCommand(
Ryan Cuif7f24692012-05-18 16:35:33 -0700303 [constants.PATH_TO_CBUILDBOT] + sys.argv[1:] + args_to_append,
Brian Harring3fec5a82012-03-01 05:57:03 -0800304 cwd=self.options.buildroot, error_code_ok=True, kill_timeout=30)
305 return return_obj.returncode == 0
306
Ryan Cuif7f24692012-05-18 16:35:33 -0700307 def _InitializeTrybotPatchPool(self):
308 """Generate patch pool from patches specified on the command line.
309
310 Do this only if we need to patch changes later on.
311 """
312 changes_stage = stages.PatchChangesStage.StageNamePrefix()
313 check_func = results_lib.Results.PreviouslyCompletedRecord
314 if not check_func(changes_stage) or self.options.bootstrap:
Ryan Cuie1e4e662012-05-21 16:39:46 -0700315 self.patch_pool = AcquirePoolFromOptions(self.options)
Ryan Cuif7f24692012-05-18 16:35:33 -0700316
317 def _GetBootstrapStage(self):
318 """Constructs and returns the BootStrapStage object.
319
320 We return None when there are no chromite patches to test, and
321 --test-bootstrap wasn't passed in.
322 """
323 stage = None
324 chromite_pool = self.patch_pool.Filter(project=constants.CHROMITE_PROJECT)
Ryan Cuie1e4e662012-05-21 16:39:46 -0700325 chromite_branch = _GetChromiteTrackingBranch()
326 if (chromite_pool or self.options.test_bootstrap
327 or chromite_branch != self.options.branch):
Ryan Cuif7f24692012-05-18 16:35:33 -0700328 stage = stages.BootstrapStage(self.options, self.build_config,
329 chromite_pool)
330 return stage
331
Brian Harring3fec5a82012-03-01 05:57:03 -0800332 def Run(self):
Ryan Cuif7f24692012-05-18 16:35:33 -0700333 """Main runner for this builder class. Runs build and prints summary.
334
335 Returns:
336 Whether the build succeeded.
337 """
338 self._InitializeTrybotPatchPool()
339
340 if self.options.bootstrap:
341 bootstrap_stage = self._GetBootstrapStage()
342 if bootstrap_stage:
343 # BootstrapStage blocks on re-execution of cbuildbot.
344 bootstrap_stage.Run()
345 return bootstrap_stage.returncode == 0
346
Brian Harring3fec5a82012-03-01 05:57:03 -0800347 print_report = True
David James3d4d3502012-04-09 15:12:06 -0700348 exception_thrown = False
Brian Harring3fec5a82012-03-01 05:57:03 -0800349 success = True
350 try:
351 self.Initialize()
352 sync_instance = self.GetSyncInstance()
353 sync_instance.Run()
354 self._SetReleaseTag()
355
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700356 if self.patch_pool:
357 self._RunStage(stages.PatchChangesStage, self.patch_pool)
Brian Harring3fec5a82012-03-01 05:57:03 -0800358
359 if self._ShouldReExecuteInBuildRoot():
360 print_report = False
361 success = self._ReExecuteInBuildroot(sync_instance)
362 else:
363 self.RunStages()
David James3d4d3502012-04-09 15:12:06 -0700364 except Exception:
365 exception_thrown = True
366 raise
Brian Harring3fec5a82012-03-01 05:57:03 -0800367 finally:
368 if print_report:
Ryan Cuif7f24692012-05-18 16:35:33 -0700369 results_lib.WriteCheckpoint(self.options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800370 print '\n\n\n@@@BUILD_STEP Report@@@\n'
371 results_lib.Results.Report(sys.stdout, self.archive_urls,
372 self.release_tag)
373 success = results_lib.Results.BuildSucceededSoFar()
David James3d4d3502012-04-09 15:12:06 -0700374 if exception_thrown and success:
375 success = False
376 print >> sys.stderr, """
377@@@STEP_FAILURE@@@
378Exception thrown, but all stages marked successful. This is an internal error,
379because the stage that threw the exception should be marked as failing."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800380
381 return success
382
383
384class SimpleBuilder(Builder):
385 """Builder that performs basic vetting operations."""
386
387 def GetSyncInstance(self):
388 """Sync to lkgm or TOT as necessary.
389
390 Returns: the instance of the sync stage that was run.
391 """
392 if self.options.lkgm or self.build_config['use_lkgm']:
393 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
394 else:
395 sync_stage = self._GetStageInstance(stages.SyncStage)
396
397 return sync_stage
398
David James58e0c092012-03-04 20:31:12 -0800399 def _RunBackgroundStagesForBoard(self, board):
400 """Run background board-specific stages for the specified board."""
David James58e0c092012-03-04 20:31:12 -0800401 archive_stage = self.archive_stages[board]
David James944a48e2012-03-07 12:19:03 -0800402 configs = self.build_config['board_specific_configs']
403 config = configs.get(board, self.build_config)
404 stage_list = [[stages.VMTestStage, board, archive_stage],
405 [stages.ChromeTestStage, board, archive_stage],
406 [stages.UnitTestStage, board],
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700407 [stages.UploadPrebuiltsStage, board, archive_stage]]
Brian Harring3fec5a82012-03-01 05:57:03 -0800408
David James58e0c092012-03-04 20:31:12 -0800409 # We can not run hw tests without archiving the payloads.
410 if self.options.archive:
David James944a48e2012-03-07 12:19:03 -0800411 for suite in config['hw_tests']:
412 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800413
David James944a48e2012-03-07 12:19:03 -0800414 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
415 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800416
417 def RunStages(self):
418 """Runs through build process."""
419 self._RunStage(stages.BuildBoardStage)
420
421 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800422 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
423 self._RunStage(stages.SDKTestStage)
424 self._RunStage(stages.UploadPrebuiltsStage,
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700425 constants.CHROOT_BUILDER_BOARD, None)
Brian Harring3fec5a82012-03-01 05:57:03 -0800426 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
427 self._RunStage(stages.RefreshPackageStatusStage)
428 else:
429 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800430
David James944a48e2012-03-07 12:19:03 -0800431 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800432 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800433 config = configs.get(board, self.build_config)
434 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
435 config=config)
David James58e0c092012-03-04 20:31:12 -0800436 self.archive_stages[board] = archive_stage
437
David James944a48e2012-03-07 12:19:03 -0800438 # Set up a process pool to run test/archive stages in the background.
439 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800440 queue = multiprocessing.Queue()
441 task = self._RunBackgroundStagesForBoard
442 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800443 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800444 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800445 archive_stage = self.archive_stages[board]
446 config = configs.get(board, self.build_config)
447 self._RunStage(stages.BuildTargetStage, board, archive_stage,
Chris Sosa1a87b3e2012-04-12 13:20:42 -0700448 self.release_tag, config=config)
David James58e0c092012-03-04 20:31:12 -0800449 self.archive_urls[board] = archive_stage.GetDownloadUrl()
450
David James944a48e2012-03-07 12:19:03 -0800451 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800452 queue.put([board])
453
Brian Harring3fec5a82012-03-01 05:57:03 -0800454
455class DistributedBuilder(SimpleBuilder):
456 """Build class that has special logic to handle distributed builds.
457
458 These builds sync using git/manifest logic in manifest_versions. In general
459 they use a non-distributed builder code for the bulk of the work.
460 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700461 def __init__(self, *args, **kwargs):
Brian Harring3fec5a82012-03-01 05:57:03 -0800462 """Initializes a buildbot builder.
463
464 Extra variables:
465 completion_stage_class: Stage used to complete a build. Set in the Sync
466 stage.
467 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700468 super(DistributedBuilder, self).__init__(*args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800469 self.completion_stage_class = None
470
471 def GetSyncInstance(self):
472 """Syncs the tree using one of the distributed sync logic paths.
473
474 Returns: the instance of the sync stage that was run.
475 """
476 # Determine sync class to use. CQ overrides PFQ bits so should check it
477 # first.
478 if cbuildbot_config.IsCQType(self.build_config['build_type']):
479 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
480 self.completion_stage_class = stages.CommitQueueCompletionStage
481 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
482 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
483 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
484 else:
485 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
486 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
487
488 return sync_stage
489
490 def Publish(self, was_build_successful):
491 """Completes build by publishing any required information."""
492 completion_stage = self._GetStageInstance(self.completion_stage_class,
493 was_build_successful)
494 completion_stage.Run()
495 name = completion_stage.name
496 if not results_lib.Results.WasStageSuccessful(name):
497 should_publish_changes = False
498 else:
499 should_publish_changes = (self.build_config['master'] and
500 was_build_successful)
501
502 if should_publish_changes:
503 self._RunStage(stages.PublishUprevChangesStage)
504
505 def RunStages(self):
506 """Runs simple builder logic and publishes information to overlays."""
507 was_build_successful = False
508 try:
David Jamesf55709e2012-03-13 09:10:15 -0700509 super(DistributedBuilder, self).RunStages()
510 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800511 except SystemExit as ex:
512 # If a stage calls sys.exit(0), it's exiting with success, so that means
513 # we should mark ourselves as successful.
514 if ex.code == 0:
515 was_build_successful = True
516 raise
517 finally:
518 self.Publish(was_build_successful)
519
Brian Harring3fec5a82012-03-01 05:57:03 -0800520
521def _ConfirmBuildRoot(buildroot):
522 """Confirm with user the inferred buildroot, and mark it as confirmed."""
523 warning = 'Using default directory %s as buildroot' % buildroot
Brian Harring1b8c4c82012-05-29 23:03:04 -0700524 response = cros_build_lib.YesNoPrompt(
525 default=cros_build_lib.NO, warning=warning, full=True)
526 if response == cros_build_lib.NO:
Brian Harring3fec5a82012-03-01 05:57:03 -0800527 print('Please specify a buildroot with the --buildroot option.')
528 sys.exit(0)
529
530 if not os.path.exists(buildroot):
531 os.mkdir(buildroot)
532
533 repository.CreateTrybotMarker(buildroot)
534
535
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700536def _ConfirmRemoteBuildbotRun():
537 """Confirm user wants to run with --buildbot --remote."""
538 warning = ('You are about to launch a PRODUCTION job! This is *NOT* a '
539 'trybot run! Are you sure?')
Brian Harring1b8c4c82012-05-29 23:03:04 -0700540 response = cros_build_lib.YesNoPrompt(
541 default=cros_build_lib.NO, warning=warning, full=True)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700542
Brian Harring1b8c4c82012-05-29 23:03:04 -0700543 if response == cros_build_lib.NO:
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700544 print('Please specify --pass-through="--debug".')
545 sys.exit(0)
546
547
Ryan Cui5ba7e152012-05-10 14:36:52 -0700548def _DetermineDefaultBuildRoot(sourceroot, internal_build):
Brian Harring3fec5a82012-03-01 05:57:03 -0800549 """Default buildroot to be under the directory that contains current checkout.
550
551 Arguments:
552 internal_build: Whether the build is an internal build
Ryan Cui5ba7e152012-05-10 14:36:52 -0700553 sourceroot: Use specified sourceroot.
Brian Harring3fec5a82012-03-01 05:57:03 -0800554 """
Ryan Cui5ba7e152012-05-10 14:36:52 -0700555 if not repository.IsARepoRoot(sourceroot):
Brian Harring1b8c4c82012-05-29 23:03:04 -0700556 cros_build_lib.Die(
557 'Could not find root of local checkout at %s. Please specify '
558 'using the --sourceroot option.' % sourceroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800559
560 # Place trybot buildroot under the directory containing current checkout.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700561 top_level = os.path.dirname(os.path.realpath(sourceroot))
Brian Harring3fec5a82012-03-01 05:57:03 -0800562 if internal_build:
563 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
564 else:
565 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
566
567 return buildroot
568
569
570def _BackupPreviousLog(log_file, backup_limit=25):
571 """Rename previous log.
572
573 Args:
574 log_file: The absolute path to the previous log.
575 """
576 if os.path.exists(log_file):
577 old_logs = sorted(glob.glob(log_file + '.*'),
578 key=distutils.version.LooseVersion)
579
580 if len(old_logs) >= backup_limit:
581 os.remove(old_logs[0])
582
583 last = 0
584 if old_logs:
585 last = int(old_logs.pop().rpartition('.')[2])
586
587 os.rename(log_file, log_file + '.' + str(last + 1))
588
David James944a48e2012-03-07 12:19:03 -0800589def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800590 """Helper function that wraps RunBuildStages()."""
591 def IsDistributedBuilder():
592 """Determines whether the build_config should be a DistributedBuilder."""
593 if not options.buildbot:
594 return False
595 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
596 chrome_rev = build_config['chrome_rev']
597 if options.chrome_rev: chrome_rev = options.chrome_rev
598 # We don't do distributed logic to TOT Chrome PFQ's, nor local
599 # chrome roots (e.g. chrome try bots)
600 if chrome_rev not in [constants.CHROME_REV_TOT,
601 constants.CHROME_REV_LOCAL,
602 constants.CHROME_REV_SPEC]:
603 return True
604
605 return False
606
Brian Harring1b8c4c82012-05-29 23:03:04 -0700607 cros_build_lib.Info("cbuildbot executed with args %s"
608 % ' '.join(map(repr, sys.argv)))
Brian Harring3fec5a82012-03-01 05:57:03 -0800609
Ryan Cuif7f24692012-05-18 16:35:33 -0700610 target = DistributedBuilder if IsDistributedBuilder() else SimpleBuilder
Ryan Cuie1e4e662012-05-21 16:39:46 -0700611 buildbot = target(options, build_config)
Brian Harringd166aaf2012-05-14 18:31:53 -0700612 if not buildbot.Run():
613 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800614
615
616# Parser related functions
Ryan Cui5ba7e152012-05-10 14:36:52 -0700617def _CheckLocalPatches(sourceroot, local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800618 """Do an early quick check of the passed-in patches.
619
620 If the branch of a project is not specified we append the current branch the
621 project is on.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700622
623 Args:
624 sourceroot: The checkout where patches are coming from.
Brian Harring3fec5a82012-03-01 05:57:03 -0800625 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700626 verified_patches = []
Brian Harring1b8c4c82012-05-29 23:03:04 -0700627 manifest = cros_build_lib.ManifestCheckout.Cached(sourceroot)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700628 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800629 components = patch.split(':')
630 if len(components) > 2:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700631 cros_build_lib.Die(
632 'Specify local patches in project[:branch] format. Got %s' % patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800633
634 # validate project
635 project = components[0]
Brian Harring3fec5a82012-03-01 05:57:03 -0800636
Brian Harring609dc4e2012-05-07 02:17:44 -0700637 try:
638 project_dir = manifest.GetProjectPath(project, True)
639 except KeyError:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700640 cros_build_lib.Die('Project %s does not exist.' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800641
642 # If no branch was specified, we use the project's current branch.
643 if len(components) == 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700644 branch = cros_build_lib.GetCurrentBranch(project_dir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800645 if not branch:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700646 cros_build_lib.Die('Project %s is not on a branch!' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800647 else:
648 branch = components[1]
Brian Harring1b8c4c82012-05-29 23:03:04 -0700649 if not cros_build_lib.DoesLocalBranchExist(project_dir, branch):
650 cros_build_lib.Die('Project %s does not have branch %s'
651 % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800652
Brian Harring609dc4e2012-05-07 02:17:44 -0700653 verified_patches.append('%s:%s' % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800654
Ryan Cuicedd8a52012-03-22 02:28:35 -0700655 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800656
657
Brian Harring3fec5a82012-03-01 05:57:03 -0800658def _CheckChromeVersionOption(_option, _opt_str, value, parser):
659 """Upgrade other options based on chrome_version being passed."""
660 value = value.strip()
661
662 if parser.values.chrome_rev is None and value:
663 parser.values.chrome_rev = constants.CHROME_REV_SPEC
664
665 parser.values.chrome_version = value
666
667
668def _CheckChromeRootOption(_option, _opt_str, value, parser):
669 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800670 if parser.values.chrome_rev is None:
671 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
672
Ryan Cui5ba7e152012-05-10 14:36:52 -0700673 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800674
675
676def _CheckChromeRevOption(_option, _opt_str, value, parser):
677 """Validate the chrome_rev option."""
678 value = value.strip()
679 if value not in constants.VALID_CHROME_REVISIONS:
680 raise optparse.OptionValueError('Invalid chrome rev specified')
681
682 parser.values.chrome_rev = value
683
684
Ryan Cui5ba7e152012-05-10 14:36:52 -0700685class CustomParser(optparse.OptionParser):
686 def add_remote_option(self, *args, **kwargs):
687 """For arguments that are passed-through to remote trybot."""
688 return optparse.OptionParser.add_option(self, *args,
689 remote_pass_through=True,
690 **kwargs)
691
692
693class CustomGroup(optparse.OptionGroup):
694 def add_remote_option(self, *args, **kwargs):
695 """For arguments that are passed-through to remote trybot."""
696 return optparse.OptionGroup.add_option(self, *args,
697 remote_pass_through=True,
698 **kwargs)
699
700
Ryan Cuif7f24692012-05-18 16:35:33 -0700701# pylint: disable=W0613
Ryan Cui5ba7e152012-05-10 14:36:52 -0700702def check_path(option, opt, value):
703 """Expand paths and make them absolute."""
704 expanded = osutils.ExpandPath(value)
705 if expanded == '/':
706 raise optparse.OptionValueError('Invalid path %s specified for %s'
707 % (expanded, opt))
708
709 return expanded
710
711
712class CustomOption(optparse.Option):
713 """Subclass Option class to implement pass-through and path evaluation."""
714 TYPES = optparse.Option.TYPES + ('path',)
715 TYPE_CHECKER = optparse.Option.TYPE_CHECKER.copy()
716 TYPE_CHECKER['path'] = check_path
717
Ryan Cui79319ab2012-05-21 12:59:18 -0700718 ACTIONS = optparse.Option.ACTIONS + ('extend',)
719 STORE_ACTIONS = optparse.Option.STORE_ACTIONS + ('extend',)
720 TYPED_ACTIONS = optparse.Option.TYPED_ACTIONS + ('extend',)
721 ALWAYS_TYPED_ACTIONS = optparse.Option.ALWAYS_TYPED_ACTIONS + ('extend',)
722
Ryan Cui5ba7e152012-05-10 14:36:52 -0700723 def __init__(self, *args, **kwargs):
724 # The remote_pass_through argument specifies whether we should directly
725 # pass the argument (with its value) onto the remote trybot.
726 self.pass_through = kwargs.pop('remote_pass_through', False)
727 optparse.Option.__init__(self, *args, **kwargs)
728
729 def take_action(self, action, dest, opt, value, values, parser):
Ryan Cui79319ab2012-05-21 12:59:18 -0700730 if action == 'extend':
731 lvalue = value.split(' ')
732 values.ensure_value(dest, []).extend(lvalue)
733 else:
734 optparse.Option.take_action(self, action, dest, opt, value, values,
735 parser)
736
Ryan Cui5ba7e152012-05-10 14:36:52 -0700737 if self.pass_through:
738 parser.values.pass_through_args.append(opt)
739 if self.nargs and self.nargs > 1:
740 # value is a tuple if nargs > 1
741 string_list = [str(val) for val in list(value)]
742 parser.values.pass_through_args.extend(string_list)
743 elif value:
744 parser.values.pass_through_args.append(str(value))
745
746
Brian Harring3fec5a82012-03-01 05:57:03 -0800747def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700748 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800749 # Parse options
750 usage = "usage: %prog [options] buildbot_config"
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700751 parser = CustomParser(usage=usage, option_class=CustomOption)
Brian Harring3fec5a82012-03-01 05:57:03 -0800752
753 # Main options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700754 # The remote_pass_through parameter to add_option is implemented by the
755 # CustomOption class. See CustomOption for more information.
Brian Harring3fec5a82012-03-01 05:57:03 -0800756 parser.add_option('-a', '--all', action='store_true', dest='print_all',
757 default=False,
758 help=('List all of the buildbot configs available. Use '
759 'with the --list option'))
Ryan Cuie1e4e662012-05-21 16:39:46 -0700760 parser.add_remote_option('-b', '--branch',
761 help='The manifest branch to test. The branch to '
762 'check the buildroot out to.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700763 parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700764 help='Root directory where source is checked out to, and '
765 'where the build occurs. For external build configs, '
766 "defaults to 'trybot' directory at top level of your "
767 'repo-managed checkout.')
768 parser.add_remote_option('--chrome_rev', default=None, type='string',
769 action='callback', dest='chrome_rev',
770 callback=_CheckChromeRevOption,
771 help=('Revision of Chrome to use, of type [%s]'
772 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cui79319ab2012-05-21 12:59:18 -0700773 parser.add_remote_option('-g', '--gerrit-patches', action='extend',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700774 default=[], type='string',
775 metavar="'Id1 *int_Id2...IdN'",
776 help=("Space-separated list of short-form Gerrit "
777 "Change-Id's or change numbers to patch. "
778 "Please prepend '*' to internal Change-Id's"))
Brian Harring3fec5a82012-03-01 05:57:03 -0800779 parser.add_option('-l', '--list', action='store_true', dest='list',
780 default=False,
781 help=('List the suggested trybot configs to use. Use '
782 '--all to list all of the available configs.'))
Ryan Cui54da0702012-04-19 18:38:08 -0700783 parser.add_option('--local', default=False, action='store_true',
784 help=('Specifies that this tryjob should be run locally.'))
Ryan Cui79319ab2012-05-21 12:59:18 -0700785 parser.add_option('-p', '--local-patches', action='extend', default=[],
Brian Harring3fec5a82012-03-01 05:57:03 -0800786 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
787 help=('Space-separated list of project branches with '
788 'patches to apply. Projects are specified by name. '
789 'If no branch is specified the current branch of the '
790 'project will be used.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700791 parser.add_remote_option('--profile', default=None, type='string',
792 action='store', dest='profile',
793 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800794 parser.add_option('--remote', default=False, action='store_true',
Brian Harring3fec5a82012-03-01 05:57:03 -0800795 help=('Specifies that this tryjob should be run remotely.'))
796
797 # Advanced options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700798 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800799 parser,
800 'Advanced Options',
801 'Caution: use these options at your own risk.')
802
Ryan Cui42aeae32012-05-21 17:09:09 -0700803 # bootstrap-args are not verified by the bootstrap code. It gets passed
804 # direcly to the bootstrap re-execution.
805 group.add_remote_option('--bootstrap-args', action='append',
806 default=[], help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700807 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
808 default=False, help='This is running on a buildbot')
809 group.add_remote_option('--buildnumber', help='build number', type='int',
810 default=0)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700811 group.add_option('--chrome_root', default=None, type='path',
812 action='callback', callback=_CheckChromeRootOption,
813 dest='chrome_root', help='Local checkout of Chrome to use.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700814 group.add_remote_option('--chrome_version', default=None, type='string',
815 action='callback', dest='chrome_version',
816 callback=_CheckChromeVersionOption,
817 help='Used with SPEC logic to force a particular SVN '
818 'revision of chrome rather than the latest.')
819 group.add_remote_option('--clobber', action='store_true', dest='clobber',
820 default=False,
821 help='Clears an old checkout before syncing')
822 group.add_remote_option('--lkgm', action='store_true', dest='lkgm',
823 default=False,
824 help='Sync to last known good manifest blessed by '
825 'PFQ')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700826 parser.add_option('--log_dir', dest='log_dir', type='path',
Brian Harring3fec5a82012-03-01 05:57:03 -0800827 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700828 group.add_remote_option('--maxarchives', dest='max_archive_builds',
829 default=3, type='int',
830 help="Change the local saved build count limit.")
831 group.add_remote_option('--noarchive', action='store_false', dest='archive',
832 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700833 group.add_remote_option('--nobootstrap', action='store_false',
834 dest='bootstrap', default=True,
835 help="Don't checkout and run from a standalone "
836 "chromite repo.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700837 group.add_remote_option('--nobuild', action='store_false', dest='build',
838 default=True,
839 help="Don't actually build (for cbuildbot dev)")
840 group.add_remote_option('--noclean', action='store_false', dest='clean',
841 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700842 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
843 default=True,
844 help='Disable cbuildbots usage of cgroups.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700845 group.add_remote_option('--noprebuilts', action='store_false',
846 dest='prebuilts', default=True,
847 help="Don't upload prebuilts.")
848 group.add_remote_option('--nosync', action='store_false', dest='sync',
849 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700850 group.add_remote_option('--notests', action='store_false', dest='tests',
851 default=True,
852 help='Override values from buildconfig and run no '
853 'tests.')
854 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
855 default=True,
856 help='Override values from buildconfig and never '
857 'uprev.')
858 group.add_option('--pass-through', dest='pass_through_args', action='append',
859 type='string', default=[], help=optparse.SUPPRESS_HELP)
Brian Harring3fec5a82012-03-01 05:57:03 -0800860 group.add_option('--reference-repo', action='store', default=None,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700861 dest='reference_repo',
862 help='Reuse git data stored in an existing repo '
863 'checkout. This can drastically reduce the network '
864 'time spent setting up the trybot checkout. By '
865 "default, if this option isn't given but cbuildbot "
866 'is invoked from a repo checkout, cbuildbot will '
867 'use the repo root.')
Brian Harring37e559b2012-05-22 20:47:32 -0700868 # Used for handling forwards/backwards compatibility for --resume and
869 # --bootstrap.
870 group.add_option('--reexec-api-version', dest='output_api_version',
871 action='store_true', default=False,
872 help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700873 # Indicates this is running on a remote trybot machine.
Ryan Cuiba41ad32012-03-08 17:15:29 -0800874 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700875 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700876 # Patches uploaded by trybot client when run using the -p option.
Ryan Cui79319ab2012-05-21 12:59:18 -0700877 group.add_remote_option('--remote-patches', action='extend', default=[],
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700878 help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700879 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700880 help='Skip stages already successfully completed.')
881 group.add_remote_option('--timeout', action='store', type='int', default=0,
882 help='Specify the maximum amount of time this job '
883 'can run for, at which point the build will be '
884 'aborted. If set to zero, then there is no '
885 'timeout.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700886 # Specify specific remote tryslaves to run on.
887 group.add_option('--slaves', action='extend', default=[],
888 help=optparse.SUPPRESS_HELP)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700889 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT,
890 help=optparse.SUPPRESS_HELP)
Ryan Cuif7f24692012-05-18 16:35:33 -0700891 # Causes cbuildbot to bootstrap itself twice, in the sequence A->B->C.
892 # A(unpatched) patches and bootstraps B. B patches and bootstraps C.
893 group.add_remote_option('--test-bootstrap', action='store_true',
894 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cui39bdbbf2012-02-29 16:15:39 -0800895 group.add_option('--test-tryjob', action='store_true',
896 default=False,
897 help='Submit a tryjob to the test repository. Will not '
898 'show up on the production trybot waterfall.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700899 group.add_remote_option('--validation_pool', default=None,
900 help='Path to a pickled validation pool. Intended '
901 'for use only with the commit queue.')
902 group.add_remote_option('--version', dest='force_version', default=None,
903 help='Used with manifest logic. Forces use of this '
904 'version rather than create or get latest.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800905
906 parser.add_option_group(group)
907
908 # Debug options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700909 group = CustomGroup(parser, "Debug Options")
Brian Harring3fec5a82012-03-01 05:57:03 -0800910
Ryan Cui85867972012-02-23 18:21:49 -0800911 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800912 help='Override some options to run as a developer.')
913 group.add_option('--dump_config', action='store_true', dest='dump_config',
914 default=False,
915 help='Dump out build config options, and exit.')
916 group.add_option('--notee', action='store_false', dest='tee', default=True,
917 help="Disable logging and internal tee process. Primarily "
918 "used for debugging cbuildbot itself.")
919 parser.add_option_group(group)
920 return parser
921
922
Ryan Cui85867972012-02-23 18:21:49 -0800923def _FinishParsing(options, args):
924 """Perform some parsing tasks that need to take place after optparse.
925
926 This function needs to be easily testable! Keep it free of
927 environment-dependent code. Put more detailed usage validation in
928 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800929
930 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800931 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800932 """
Brian Harring07039b52012-05-13 17:56:47 -0700933 # Setup logging levels first so any parsing triggered log messages
934 # are appropriately filtered.
935 logging.getLogger().setLevel(
936 logging.DEBUG if options.debug else logging.INFO)
937
Brian Harring3fec5a82012-03-01 05:57:03 -0800938 if options.chrome_root:
939 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700940 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
941 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800942 else:
943 if options.chrome_rev == constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700944 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
945 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800946
947 if options.chrome_version:
948 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700949 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
950 constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800951 else:
952 if options.chrome_rev == constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700953 cros_build_lib.Die(
954 'Chrome rev must not be %s if chrome_version is not set.'
955 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800956
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700957 patches = bool(options.gerrit_patches or options.local_patches)
958 if options.remote:
959 if options.local:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700960 cros_build_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -0700961
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700962 if not options.buildbot and not patches:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700963 cros_build_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800964
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700965 # --debug needs to be explicitly passed through for remote invocations.
966 release_mode_with_patches = (options.buildbot and patches and
967 '--debug' not in options.pass_through_args)
968 else:
969 if len(args) > 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700970 cros_build_lib.Die('Multiple configs not supported if not running with '
971 '--remote.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700972
Ryan Cui79319ab2012-05-21 12:59:18 -0700973 if options.slaves:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700974 cros_build_lib.Die('Cannot use --slaves if not running with --remote.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700975
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700976 release_mode_with_patches = (options.buildbot and patches and
977 not options.debug)
978
979 # When running in release mode, make sure we are running with checked-in code.
980 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
981 # a release image with checked-in code for CrOS packages.
982 if release_mode_with_patches:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700983 cros_build_lib.Die(
984 'Cannot provide patches when running with --buildbot!')
Brian Harring3fec5a82012-03-01 05:57:03 -0800985
Ryan Cuiba41ad32012-03-08 17:15:29 -0800986 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700987 cros_build_lib.Die(
988 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800989
Ryan Cui85867972012-02-23 18:21:49 -0800990 # Record whether --debug was set explicitly vs. it was inferred.
991 options.debug_forced = False
992 if options.debug:
993 options.debug_forced = True
994 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800995 # We don't set debug by default for
996 # 1. --buildbot invocations.
997 # 2. --remote invocations, because it needs to push changes to the tryjob
998 # repo.
999 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -08001000
Brian Harring3fec5a82012-03-01 05:57:03 -08001001
Brian Harring1d7ba942012-04-24 06:37:18 -07001002# pylint: disable=W0613
Ryan Cui85867972012-02-23 18:21:49 -08001003def _PostParseCheck(options, args):
1004 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -08001005
Ryan Cui85867972012-02-23 18:21:49 -08001006 Args:
1007 options/args: The options/args object returned by optparse
1008 """
Ryan Cuie1e4e662012-05-21 16:39:46 -07001009 if not options.branch:
1010 options.branch = _GetChromiteTrackingBranch()
1011
Ryan Cui5ba7e152012-05-10 14:36:52 -07001012 if options.local_patches and not repository.IsARepoRoot(options.sourceroot):
1013 raise Exception('Could not find repo checkout at %s!'
1014 % options.sourceroot)
1015
Brian Harring609dc4e2012-05-07 02:17:44 -07001016 if options.local_patches:
Brian Harring1d7ba942012-04-24 06:37:18 -07001017 options.local_patches = _CheckLocalPatches(
Brian Harring609dc4e2012-05-07 02:17:44 -07001018 options.sourceroot, options.local_patches)
Brian Harring1d7ba942012-04-24 06:37:18 -07001019
1020 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
1021 if (default and not any([options.local, options.buildbot,
1022 options.remote, options.remote_trybot])):
Brian Harring1b8c4c82012-05-29 23:03:04 -07001023 cros_build_lib.Info("CBUILDBOT_DEFAULT_MODE=%s env var detected, using it."
1024 % default)
Brian Harring1d7ba942012-04-24 06:37:18 -07001025 default = default.lower()
1026 if default == 'local':
1027 options.local = True
1028 elif default == 'remote':
1029 options.remote = True
1030 elif default == 'buildbot':
1031 options.buildbot = True
1032 else:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001033 cros_build_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
1034 % default)
Ryan Cui85867972012-02-23 18:21:49 -08001035
1036
1037def _ParseCommandLine(parser, argv):
1038 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -08001039 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -07001040
1041 if options.output_api_version:
1042 print _REEXEC_API_VERSION
1043 sys.exit(0)
1044
Ryan Cui54da0702012-04-19 18:38:08 -07001045 if options.list:
1046 _PrintValidConfigs(options.print_all)
1047 sys.exit(0)
1048
Ryan Cui8be16062012-04-24 12:05:26 -07001049 # Strip out null arguments.
1050 # TODO(rcui): Remove when buildbot is fixed
1051 args = [arg for arg in args if arg]
1052 if not args:
1053 parser.error('Invalid usage. Use -h to see usage. Use -l to list '
1054 'supported configs.')
1055
Ryan Cui85867972012-02-23 18:21:49 -08001056 _FinishParsing(options, args)
1057 return options, args
1058
1059
1060def main(argv):
1061 # Set umask to 022 so files created by buildbot are readable.
1062 os.umask(022)
1063
Brian Harring1b8c4c82012-05-29 23:03:04 -07001064 if cros_build_lib.IsInsideChroot():
1065 cros_build_lib.Die('Please run cbuildbot from outside the chroot.')
Ryan Cui85867972012-02-23 18:21:49 -08001066
1067 parser = _CreateParser()
1068 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -08001069
Brian Harring3fec5a82012-03-01 05:57:03 -08001070 _PostParseCheck(options, args)
1071
1072 if options.remote:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001073 cros_build_lib.logger.setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001074
Brian Harring3fec5a82012-03-01 05:57:03 -08001075 # Verify configs are valid.
1076 for bot in args:
1077 _GetConfig(bot)
1078
1079 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -08001080 print 'Verifying patches...'
Ryan Cuie1e4e662012-05-21 16:39:46 -07001081 patch_pool = AcquirePoolFromOptions(options)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001082
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001083 # --debug need to be explicitly passed through for remote invocations.
1084 if options.buildbot and '--debug' not in options.pass_through_args:
1085 _ConfirmRemoteBuildbotRun()
1086
Ryan Cui16ca5812012-03-08 20:34:27 -08001087 print 'Submitting tryjob...'
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001088 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cui39bdbbf2012-02-29 16:15:39 -08001089 tryjob.Submit(testjob=options.test_tryjob, dryrun=options.debug)
Ryan Cui16ca5812012-03-08 20:34:27 -08001090 print 'Tryjob submitted!'
1091 print ('Go to %s to view the status of your job.'
Ryan Cui4906e1c2012-04-03 20:09:34 -07001092 % tryjob.GetTrybotWaterfallLink())
Brian Harringe2078b92012-05-24 03:21:38 -07001093 if options.debug:
1094 print
1095 print "Keep in mind that you had --debug enabled, thus nothing was"
1096 print "actually submitted."
Brian Harring3fec5a82012-03-01 05:57:03 -08001097 sys.exit(0)
Ryan Cui54da0702012-04-19 18:38:08 -07001098 elif (not options.buildbot and not options.remote_trybot
1099 and not options.resume and not options.local):
Brian Harring1b8c4c82012-05-29 23:03:04 -07001100 cros_build_lib.Warning(
1101 'Running in LOCAL TRYBOT mode! Use --remote to submit REMOTE '
1102 'tryjobs. Use --local to suppress this message.')
1103 cros_build_lib.Warning(
1104 'Starting April 30th, --local will be required to run the local '
1105 'trybot.')
Ryan Cui54da0702012-04-19 18:38:08 -07001106 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:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001138 ret = cros_build_lib.RunCommand(
1139 'which %s' % program, shell=True, redirect_stderr=True,
1140 redirect_stdout=True, error_code_ok=True, print_cmd=False)
Brian Harring351ce442012-03-09 16:38:14 -08001141 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 Harring1b8c4c82012-05-29 23:03:04 -07001187 with cros_build_lib.ContextManagerStack() as stack:
Brian Harringc2d09d92012-05-13 22:03:15 -07001188 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:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001211 stack.Add(cros_build_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)