blob: e38f6686ce3707008ddde7caceb4adef293d350b [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
David James62d2be12012-06-16 21:02:26 -0700376 print >> sys.stderr, "\n" + constants.STEP_WARNINGS + """
David James3d4d3502012-04-09 15:12:06 -0700377Exception thrown, but all stages marked successful. This is an internal error,
378because the stage that threw the exception should be marked as failing."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800379
380 return success
381
382
383class SimpleBuilder(Builder):
384 """Builder that performs basic vetting operations."""
385
386 def GetSyncInstance(self):
387 """Sync to lkgm or TOT as necessary.
388
389 Returns: the instance of the sync stage that was run.
390 """
391 if self.options.lkgm or self.build_config['use_lkgm']:
392 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
393 else:
394 sync_stage = self._GetStageInstance(stages.SyncStage)
395
396 return sync_stage
397
David James58e0c092012-03-04 20:31:12 -0800398 def _RunBackgroundStagesForBoard(self, board):
399 """Run background board-specific stages for the specified board."""
David James58e0c092012-03-04 20:31:12 -0800400 archive_stage = self.archive_stages[board]
David James944a48e2012-03-07 12:19:03 -0800401 configs = self.build_config['board_specific_configs']
402 config = configs.get(board, self.build_config)
403 stage_list = [[stages.VMTestStage, board, archive_stage],
404 [stages.ChromeTestStage, board, archive_stage],
405 [stages.UnitTestStage, board],
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700406 [stages.UploadPrebuiltsStage, board, archive_stage]]
Brian Harring3fec5a82012-03-01 05:57:03 -0800407
David James58e0c092012-03-04 20:31:12 -0800408 # We can not run hw tests without archiving the payloads.
409 if self.options.archive:
David James944a48e2012-03-07 12:19:03 -0800410 for suite in config['hw_tests']:
Chris Sosa56c9d6c2012-06-18 16:11:09 -0700411 if cbuildbot_config.IsCQType(config['build_type']):
412 stage_list.append([stages.PaladinHWTestStage, board, archive_stage,
413 suite])
414 else:
415 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800416
David James944a48e2012-03-07 12:19:03 -0800417 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
418 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800419
420 def RunStages(self):
421 """Runs through build process."""
422 self._RunStage(stages.BuildBoardStage)
423
424 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800425 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
426 self._RunStage(stages.SDKTestStage)
427 self._RunStage(stages.UploadPrebuiltsStage,
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700428 constants.CHROOT_BUILDER_BOARD, None)
Brian Harring3fec5a82012-03-01 05:57:03 -0800429 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
430 self._RunStage(stages.RefreshPackageStatusStage)
431 else:
432 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800433
David James944a48e2012-03-07 12:19:03 -0800434 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800435 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800436 config = configs.get(board, self.build_config)
437 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
438 config=config)
David James58e0c092012-03-04 20:31:12 -0800439 self.archive_stages[board] = archive_stage
440
David James944a48e2012-03-07 12:19:03 -0800441 # Set up a process pool to run test/archive stages in the background.
442 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800443 queue = multiprocessing.Queue()
444 task = self._RunBackgroundStagesForBoard
445 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800446 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800447 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800448 archive_stage = self.archive_stages[board]
449 config = configs.get(board, self.build_config)
450 self._RunStage(stages.BuildTargetStage, board, archive_stage,
Chris Sosa1a87b3e2012-04-12 13:20:42 -0700451 self.release_tag, config=config)
David James58e0c092012-03-04 20:31:12 -0800452 self.archive_urls[board] = archive_stage.GetDownloadUrl()
453
David James944a48e2012-03-07 12:19:03 -0800454 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800455 queue.put([board])
456
Brian Harring3fec5a82012-03-01 05:57:03 -0800457
458class DistributedBuilder(SimpleBuilder):
459 """Build class that has special logic to handle distributed builds.
460
461 These builds sync using git/manifest logic in manifest_versions. In general
462 they use a non-distributed builder code for the bulk of the work.
463 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700464 def __init__(self, *args, **kwargs):
Brian Harring3fec5a82012-03-01 05:57:03 -0800465 """Initializes a buildbot builder.
466
467 Extra variables:
468 completion_stage_class: Stage used to complete a build. Set in the Sync
469 stage.
470 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700471 super(DistributedBuilder, self).__init__(*args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800472 self.completion_stage_class = None
473
474 def GetSyncInstance(self):
475 """Syncs the tree using one of the distributed sync logic paths.
476
477 Returns: the instance of the sync stage that was run.
478 """
479 # Determine sync class to use. CQ overrides PFQ bits so should check it
480 # first.
481 if cbuildbot_config.IsCQType(self.build_config['build_type']):
482 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
483 self.completion_stage_class = stages.CommitQueueCompletionStage
484 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
485 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
486 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
487 else:
488 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
489 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
490
491 return sync_stage
492
493 def Publish(self, was_build_successful):
494 """Completes build by publishing any required information."""
495 completion_stage = self._GetStageInstance(self.completion_stage_class,
496 was_build_successful)
497 completion_stage.Run()
498 name = completion_stage.name
499 if not results_lib.Results.WasStageSuccessful(name):
500 should_publish_changes = False
501 else:
502 should_publish_changes = (self.build_config['master'] and
503 was_build_successful)
504
505 if should_publish_changes:
506 self._RunStage(stages.PublishUprevChangesStage)
507
508 def RunStages(self):
509 """Runs simple builder logic and publishes information to overlays."""
510 was_build_successful = False
511 try:
David Jamesf55709e2012-03-13 09:10:15 -0700512 super(DistributedBuilder, self).RunStages()
513 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800514 except SystemExit as ex:
515 # If a stage calls sys.exit(0), it's exiting with success, so that means
516 # we should mark ourselves as successful.
517 if ex.code == 0:
518 was_build_successful = True
519 raise
520 finally:
521 self.Publish(was_build_successful)
522
Brian Harring3fec5a82012-03-01 05:57:03 -0800523
524def _ConfirmBuildRoot(buildroot):
525 """Confirm with user the inferred buildroot, and mark it as confirmed."""
526 warning = 'Using default directory %s as buildroot' % buildroot
Brian Harring1b8c4c82012-05-29 23:03:04 -0700527 response = cros_build_lib.YesNoPrompt(
528 default=cros_build_lib.NO, warning=warning, full=True)
529 if response == cros_build_lib.NO:
Brian Harring3fec5a82012-03-01 05:57:03 -0800530 print('Please specify a buildroot with the --buildroot option.')
531 sys.exit(0)
532
533 if not os.path.exists(buildroot):
534 os.mkdir(buildroot)
535
536 repository.CreateTrybotMarker(buildroot)
537
538
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700539def _ConfirmRemoteBuildbotRun():
540 """Confirm user wants to run with --buildbot --remote."""
541 warning = ('You are about to launch a PRODUCTION job! This is *NOT* a '
542 'trybot run! Are you sure?')
Brian Harring1b8c4c82012-05-29 23:03:04 -0700543 response = cros_build_lib.YesNoPrompt(
544 default=cros_build_lib.NO, warning=warning, full=True)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700545
Brian Harring1b8c4c82012-05-29 23:03:04 -0700546 if response == cros_build_lib.NO:
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700547 print('Please specify --pass-through="--debug".')
548 sys.exit(0)
549
550
Ryan Cui5ba7e152012-05-10 14:36:52 -0700551def _DetermineDefaultBuildRoot(sourceroot, internal_build):
Brian Harring3fec5a82012-03-01 05:57:03 -0800552 """Default buildroot to be under the directory that contains current checkout.
553
554 Arguments:
555 internal_build: Whether the build is an internal build
Ryan Cui5ba7e152012-05-10 14:36:52 -0700556 sourceroot: Use specified sourceroot.
Brian Harring3fec5a82012-03-01 05:57:03 -0800557 """
Ryan Cui5ba7e152012-05-10 14:36:52 -0700558 if not repository.IsARepoRoot(sourceroot):
Brian Harring1b8c4c82012-05-29 23:03:04 -0700559 cros_build_lib.Die(
560 '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 Harring1b8c4c82012-05-29 23:03:04 -0700610 cros_build_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 = []
Brian Harring1b8c4c82012-05-29 23:03:04 -0700630 manifest = cros_build_lib.ManifestCheckout.Cached(sourceroot)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700631 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800632 components = patch.split(':')
633 if len(components) > 2:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700634 cros_build_lib.Die(
635 'Specify local patches in project[:branch] format. Got %s' % patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800636
637 # validate project
638 project = components[0]
Brian Harring3fec5a82012-03-01 05:57:03 -0800639
Brian Harring609dc4e2012-05-07 02:17:44 -0700640 try:
641 project_dir = manifest.GetProjectPath(project, True)
642 except KeyError:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700643 cros_build_lib.Die('Project %s does not exist.' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800644
645 # If no branch was specified, we use the project's current branch.
646 if len(components) == 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700647 branch = cros_build_lib.GetCurrentBranch(project_dir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800648 if not branch:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700649 cros_build_lib.Die('Project %s is not on a branch!' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800650 else:
651 branch = components[1]
Brian Harring1b8c4c82012-05-29 23:03:04 -0700652 if not cros_build_lib.DoesLocalBranchExist(project_dir, branch):
653 cros_build_lib.Die('Project %s does not have branch %s'
654 % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800655
Brian Harring609dc4e2012-05-07 02:17:44 -0700656 verified_patches.append('%s:%s' % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800657
Ryan Cuicedd8a52012-03-22 02:28:35 -0700658 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800659
660
Brian Harring3fec5a82012-03-01 05:57:03 -0800661def _CheckChromeVersionOption(_option, _opt_str, value, parser):
662 """Upgrade other options based on chrome_version being passed."""
663 value = value.strip()
664
665 if parser.values.chrome_rev is None and value:
666 parser.values.chrome_rev = constants.CHROME_REV_SPEC
667
668 parser.values.chrome_version = value
669
670
671def _CheckChromeRootOption(_option, _opt_str, value, parser):
672 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800673 if parser.values.chrome_rev is None:
674 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
675
Ryan Cui5ba7e152012-05-10 14:36:52 -0700676 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800677
678
679def _CheckChromeRevOption(_option, _opt_str, value, parser):
680 """Validate the chrome_rev option."""
681 value = value.strip()
682 if value not in constants.VALID_CHROME_REVISIONS:
683 raise optparse.OptionValueError('Invalid chrome rev specified')
684
685 parser.values.chrome_rev = value
686
687
Ryan Cui5ba7e152012-05-10 14:36:52 -0700688class CustomParser(optparse.OptionParser):
689 def add_remote_option(self, *args, **kwargs):
690 """For arguments that are passed-through to remote trybot."""
691 return optparse.OptionParser.add_option(self, *args,
692 remote_pass_through=True,
693 **kwargs)
694
695
696class CustomGroup(optparse.OptionGroup):
697 def add_remote_option(self, *args, **kwargs):
698 """For arguments that are passed-through to remote trybot."""
699 return optparse.OptionGroup.add_option(self, *args,
700 remote_pass_through=True,
701 **kwargs)
702
703
Ryan Cuif7f24692012-05-18 16:35:33 -0700704# pylint: disable=W0613
Ryan Cui5ba7e152012-05-10 14:36:52 -0700705def check_path(option, opt, value):
706 """Expand paths and make them absolute."""
707 expanded = osutils.ExpandPath(value)
708 if expanded == '/':
709 raise optparse.OptionValueError('Invalid path %s specified for %s'
710 % (expanded, opt))
711
712 return expanded
713
714
715class CustomOption(optparse.Option):
716 """Subclass Option class to implement pass-through and path evaluation."""
717 TYPES = optparse.Option.TYPES + ('path',)
718 TYPE_CHECKER = optparse.Option.TYPE_CHECKER.copy()
719 TYPE_CHECKER['path'] = check_path
720
Ryan Cui79319ab2012-05-21 12:59:18 -0700721 ACTIONS = optparse.Option.ACTIONS + ('extend',)
722 STORE_ACTIONS = optparse.Option.STORE_ACTIONS + ('extend',)
723 TYPED_ACTIONS = optparse.Option.TYPED_ACTIONS + ('extend',)
724 ALWAYS_TYPED_ACTIONS = optparse.Option.ALWAYS_TYPED_ACTIONS + ('extend',)
725
Ryan Cui5ba7e152012-05-10 14:36:52 -0700726 def __init__(self, *args, **kwargs):
727 # The remote_pass_through argument specifies whether we should directly
728 # pass the argument (with its value) onto the remote trybot.
729 self.pass_through = kwargs.pop('remote_pass_through', False)
730 optparse.Option.__init__(self, *args, **kwargs)
731
732 def take_action(self, action, dest, opt, value, values, parser):
Ryan Cui79319ab2012-05-21 12:59:18 -0700733 if action == 'extend':
734 lvalue = value.split(' ')
735 values.ensure_value(dest, []).extend(lvalue)
736 else:
737 optparse.Option.take_action(self, action, dest, opt, value, values,
738 parser)
739
Ryan Cui5ba7e152012-05-10 14:36:52 -0700740 if self.pass_through:
741 parser.values.pass_through_args.append(opt)
742 if self.nargs and self.nargs > 1:
743 # value is a tuple if nargs > 1
744 string_list = [str(val) for val in list(value)]
745 parser.values.pass_through_args.extend(string_list)
746 elif value:
747 parser.values.pass_through_args.append(str(value))
748
749
Brian Harring3fec5a82012-03-01 05:57:03 -0800750def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700751 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800752 # Parse options
753 usage = "usage: %prog [options] buildbot_config"
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700754 parser = CustomParser(usage=usage, option_class=CustomOption)
Brian Harring3fec5a82012-03-01 05:57:03 -0800755
756 # Main options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700757 # The remote_pass_through parameter to add_option is implemented by the
758 # CustomOption class. See CustomOption for more information.
Brian Harring3fec5a82012-03-01 05:57:03 -0800759 parser.add_option('-a', '--all', action='store_true', dest='print_all',
760 default=False,
761 help=('List all of the buildbot configs available. Use '
762 'with the --list option'))
Ryan Cuie1e4e662012-05-21 16:39:46 -0700763 parser.add_remote_option('-b', '--branch',
764 help='The manifest branch to test. The branch to '
765 'check the buildroot out to.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700766 parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700767 help='Root directory where source is checked out to, and '
768 'where the build occurs. For external build configs, '
769 "defaults to 'trybot' directory at top level of your "
770 'repo-managed checkout.')
771 parser.add_remote_option('--chrome_rev', default=None, type='string',
772 action='callback', dest='chrome_rev',
773 callback=_CheckChromeRevOption,
774 help=('Revision of Chrome to use, of type [%s]'
775 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cui79319ab2012-05-21 12:59:18 -0700776 parser.add_remote_option('-g', '--gerrit-patches', action='extend',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700777 default=[], type='string',
778 metavar="'Id1 *int_Id2...IdN'",
779 help=("Space-separated list of short-form Gerrit "
780 "Change-Id's or change numbers to patch. "
781 "Please prepend '*' to internal Change-Id's"))
Brian Harring3fec5a82012-03-01 05:57:03 -0800782 parser.add_option('-l', '--list', action='store_true', dest='list',
783 default=False,
784 help=('List the suggested trybot configs to use. Use '
785 '--all to list all of the available configs.'))
Ryan Cui54da0702012-04-19 18:38:08 -0700786 parser.add_option('--local', default=False, action='store_true',
787 help=('Specifies that this tryjob should be run locally.'))
Ryan Cui79319ab2012-05-21 12:59:18 -0700788 parser.add_option('-p', '--local-patches', action='extend', default=[],
Brian Harring3fec5a82012-03-01 05:57:03 -0800789 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
790 help=('Space-separated list of project branches with '
791 'patches to apply. Projects are specified by name. '
792 'If no branch is specified the current branch of the '
793 'project will be used.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700794 parser.add_remote_option('--profile', default=None, type='string',
795 action='store', dest='profile',
796 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800797 parser.add_option('--remote', default=False, action='store_true',
Brian Harring3fec5a82012-03-01 05:57:03 -0800798 help=('Specifies that this tryjob should be run remotely.'))
799
800 # Advanced options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700801 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800802 parser,
803 'Advanced Options',
804 'Caution: use these options at your own risk.')
805
Ryan Cui42aeae32012-05-21 17:09:09 -0700806 # bootstrap-args are not verified by the bootstrap code. It gets passed
807 # direcly to the bootstrap re-execution.
808 group.add_remote_option('--bootstrap-args', action='append',
809 default=[], help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700810 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
811 default=False, help='This is running on a buildbot')
812 group.add_remote_option('--buildnumber', help='build number', type='int',
813 default=0)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700814 group.add_option('--chrome_root', default=None, type='path',
815 action='callback', callback=_CheckChromeRootOption,
816 dest='chrome_root', help='Local checkout of Chrome to use.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700817 group.add_remote_option('--chrome_version', default=None, type='string',
818 action='callback', dest='chrome_version',
819 callback=_CheckChromeVersionOption,
820 help='Used with SPEC logic to force a particular SVN '
821 'revision of chrome rather than the latest.')
822 group.add_remote_option('--clobber', action='store_true', dest='clobber',
823 default=False,
824 help='Clears an old checkout before syncing')
825 group.add_remote_option('--lkgm', action='store_true', dest='lkgm',
826 default=False,
827 help='Sync to last known good manifest blessed by '
828 'PFQ')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700829 parser.add_option('--log_dir', dest='log_dir', type='path',
Brian Harring3fec5a82012-03-01 05:57:03 -0800830 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700831 group.add_remote_option('--maxarchives', dest='max_archive_builds',
832 default=3, type='int',
833 help="Change the local saved build count limit.")
834 group.add_remote_option('--noarchive', action='store_false', dest='archive',
835 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700836 group.add_remote_option('--nobootstrap', action='store_false',
837 dest='bootstrap', default=True,
838 help="Don't checkout and run from a standalone "
839 "chromite repo.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700840 group.add_remote_option('--nobuild', action='store_false', dest='build',
841 default=True,
842 help="Don't actually build (for cbuildbot dev)")
843 group.add_remote_option('--noclean', action='store_false', dest='clean',
844 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700845 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
846 default=True,
847 help='Disable cbuildbots usage of cgroups.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700848 group.add_remote_option('--noprebuilts', action='store_false',
849 dest='prebuilts', default=True,
850 help="Don't upload prebuilts.")
851 group.add_remote_option('--nosync', action='store_false', dest='sync',
852 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700853 group.add_remote_option('--notests', action='store_false', dest='tests',
854 default=True,
855 help='Override values from buildconfig and run no '
856 'tests.')
857 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
858 default=True,
859 help='Override values from buildconfig and never '
860 'uprev.')
861 group.add_option('--pass-through', dest='pass_through_args', action='append',
862 type='string', default=[], help=optparse.SUPPRESS_HELP)
Brian Harring3fec5a82012-03-01 05:57:03 -0800863 group.add_option('--reference-repo', action='store', default=None,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700864 dest='reference_repo',
865 help='Reuse git data stored in an existing repo '
866 'checkout. This can drastically reduce the network '
867 'time spent setting up the trybot checkout. By '
868 "default, if this option isn't given but cbuildbot "
869 'is invoked from a repo checkout, cbuildbot will '
870 'use the repo root.')
Brian Harring37e559b2012-05-22 20:47:32 -0700871 # Used for handling forwards/backwards compatibility for --resume and
872 # --bootstrap.
873 group.add_option('--reexec-api-version', dest='output_api_version',
874 action='store_true', default=False,
875 help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700876 # Indicates this is running on a remote trybot machine.
Ryan Cuiba41ad32012-03-08 17:15:29 -0800877 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700878 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700879 # Patches uploaded by trybot client when run using the -p option.
Ryan Cui79319ab2012-05-21 12:59:18 -0700880 group.add_remote_option('--remote-patches', action='extend', default=[],
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700881 help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700882 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700883 help='Skip stages already successfully completed.')
884 group.add_remote_option('--timeout', action='store', type='int', default=0,
885 help='Specify the maximum amount of time this job '
886 'can run for, at which point the build will be '
887 'aborted. If set to zero, then there is no '
888 'timeout.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700889 # Specify specific remote tryslaves to run on.
890 group.add_option('--slaves', action='extend', default=[],
891 help=optparse.SUPPRESS_HELP)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700892 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT,
893 help=optparse.SUPPRESS_HELP)
Ryan Cuif7f24692012-05-18 16:35:33 -0700894 # Causes cbuildbot to bootstrap itself twice, in the sequence A->B->C.
895 # A(unpatched) patches and bootstraps B. B patches and bootstraps C.
896 group.add_remote_option('--test-bootstrap', action='store_true',
897 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cui39bdbbf2012-02-29 16:15:39 -0800898 group.add_option('--test-tryjob', action='store_true',
899 default=False,
900 help='Submit a tryjob to the test repository. Will not '
901 'show up on the production trybot waterfall.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700902 group.add_remote_option('--validation_pool', default=None,
903 help='Path to a pickled validation pool. Intended '
904 'for use only with the commit queue.')
905 group.add_remote_option('--version', dest='force_version', default=None,
906 help='Used with manifest logic. Forces use of this '
907 'version rather than create or get latest.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800908
909 parser.add_option_group(group)
910
911 # Debug options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700912 group = CustomGroup(parser, "Debug Options")
Brian Harring3fec5a82012-03-01 05:57:03 -0800913
Ryan Cui85867972012-02-23 18:21:49 -0800914 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800915 help='Override some options to run as a developer.')
916 group.add_option('--dump_config', action='store_true', dest='dump_config',
917 default=False,
918 help='Dump out build config options, and exit.')
919 group.add_option('--notee', action='store_false', dest='tee', default=True,
920 help="Disable logging and internal tee process. Primarily "
921 "used for debugging cbuildbot itself.")
922 parser.add_option_group(group)
923 return parser
924
925
Ryan Cui85867972012-02-23 18:21:49 -0800926def _FinishParsing(options, args):
927 """Perform some parsing tasks that need to take place after optparse.
928
929 This function needs to be easily testable! Keep it free of
930 environment-dependent code. Put more detailed usage validation in
931 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800932
933 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800934 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800935 """
Brian Harring07039b52012-05-13 17:56:47 -0700936 # Setup logging levels first so any parsing triggered log messages
937 # are appropriately filtered.
938 logging.getLogger().setLevel(
939 logging.DEBUG if options.debug else logging.INFO)
940
Brian Harring3fec5a82012-03-01 05:57:03 -0800941 if options.chrome_root:
942 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700943 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
944 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800945 else:
946 if options.chrome_rev == constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700947 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
948 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800949
950 if options.chrome_version:
951 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700952 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
953 constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800954 else:
955 if options.chrome_rev == constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700956 cros_build_lib.Die(
957 'Chrome rev must not be %s if chrome_version is not set.'
958 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800959
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:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700963 cros_build_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:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700966 cros_build_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:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700973 cros_build_lib.Die('Multiple configs not supported if not running with '
974 '--remote.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700975
Ryan Cui79319ab2012-05-21 12:59:18 -0700976 if options.slaves:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700977 cros_build_lib.Die('Cannot use --slaves if not running with --remote.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700978
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:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700986 cros_build_lib.Die(
987 'Cannot provide patches when running with --buildbot!')
Brian Harring3fec5a82012-03-01 05:57:03 -0800988
Ryan Cuiba41ad32012-03-08 17:15:29 -0800989 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700990 cros_build_lib.Die(
991 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800992
Ryan Cui85867972012-02-23 18:21:49 -0800993 # Record whether --debug was set explicitly vs. it was inferred.
994 options.debug_forced = False
995 if options.debug:
996 options.debug_forced = True
997 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800998 # We don't set debug by default for
999 # 1. --buildbot invocations.
1000 # 2. --remote invocations, because it needs to push changes to the tryjob
1001 # repo.
1002 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -08001003
Brian Harring3fec5a82012-03-01 05:57:03 -08001004
Brian Harring1d7ba942012-04-24 06:37:18 -07001005# pylint: disable=W0613
Ryan Cui85867972012-02-23 18:21:49 -08001006def _PostParseCheck(options, args):
1007 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -08001008
Ryan Cui85867972012-02-23 18:21:49 -08001009 Args:
1010 options/args: The options/args object returned by optparse
1011 """
Ryan Cuie1e4e662012-05-21 16:39:46 -07001012 if not options.branch:
1013 options.branch = _GetChromiteTrackingBranch()
1014
Ryan Cui5ba7e152012-05-10 14:36:52 -07001015 if options.local_patches and not repository.IsARepoRoot(options.sourceroot):
1016 raise Exception('Could not find repo checkout at %s!'
1017 % options.sourceroot)
1018
Brian Harring609dc4e2012-05-07 02:17:44 -07001019 if options.local_patches:
Brian Harring1d7ba942012-04-24 06:37:18 -07001020 options.local_patches = _CheckLocalPatches(
Brian Harring609dc4e2012-05-07 02:17:44 -07001021 options.sourceroot, options.local_patches)
Brian Harring1d7ba942012-04-24 06:37:18 -07001022
1023 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
1024 if (default and not any([options.local, options.buildbot,
1025 options.remote, options.remote_trybot])):
Brian Harring1b8c4c82012-05-29 23:03:04 -07001026 cros_build_lib.Info("CBUILDBOT_DEFAULT_MODE=%s env var detected, using it."
1027 % default)
Brian Harring1d7ba942012-04-24 06:37:18 -07001028 default = default.lower()
1029 if default == 'local':
1030 options.local = True
1031 elif default == 'remote':
1032 options.remote = True
1033 elif default == 'buildbot':
1034 options.buildbot = True
1035 else:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001036 cros_build_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
1037 % default)
Ryan Cui85867972012-02-23 18:21:49 -08001038
1039
1040def _ParseCommandLine(parser, argv):
1041 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -08001042 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -07001043
1044 if options.output_api_version:
1045 print _REEXEC_API_VERSION
1046 sys.exit(0)
1047
Ryan Cui54da0702012-04-19 18:38:08 -07001048 if options.list:
1049 _PrintValidConfigs(options.print_all)
1050 sys.exit(0)
1051
Ryan Cui8be16062012-04-24 12:05:26 -07001052 # Strip out null arguments.
1053 # TODO(rcui): Remove when buildbot is fixed
1054 args = [arg for arg in args if arg]
1055 if not args:
1056 parser.error('Invalid usage. Use -h to see usage. Use -l to list '
1057 'supported configs.')
1058
Ryan Cui85867972012-02-23 18:21:49 -08001059 _FinishParsing(options, args)
1060 return options, args
1061
1062
1063def main(argv):
1064 # Set umask to 022 so files created by buildbot are readable.
1065 os.umask(022)
1066
Brian Harring1b8c4c82012-05-29 23:03:04 -07001067 if cros_build_lib.IsInsideChroot():
1068 cros_build_lib.Die('Please run cbuildbot from outside the chroot.')
Ryan Cui85867972012-02-23 18:21:49 -08001069
1070 parser = _CreateParser()
1071 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -08001072
Brian Harring3fec5a82012-03-01 05:57:03 -08001073 _PostParseCheck(options, args)
1074
1075 if options.remote:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001076 cros_build_lib.logger.setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001077
Brian Harring3fec5a82012-03-01 05:57:03 -08001078 # Verify configs are valid.
1079 for bot in args:
1080 _GetConfig(bot)
1081
1082 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -08001083 print 'Verifying patches...'
Ryan Cuie1e4e662012-05-21 16:39:46 -07001084 patch_pool = AcquirePoolFromOptions(options)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001085
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001086 # --debug need to be explicitly passed through for remote invocations.
1087 if options.buildbot and '--debug' not in options.pass_through_args:
1088 _ConfirmRemoteBuildbotRun()
1089
Ryan Cui16ca5812012-03-08 20:34:27 -08001090 print 'Submitting tryjob...'
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001091 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cui39bdbbf2012-02-29 16:15:39 -08001092 tryjob.Submit(testjob=options.test_tryjob, dryrun=options.debug)
Ryan Cui16ca5812012-03-08 20:34:27 -08001093 print 'Tryjob submitted!'
1094 print ('Go to %s to view the status of your job.'
Ryan Cui4906e1c2012-04-03 20:09:34 -07001095 % tryjob.GetTrybotWaterfallLink())
Brian Harringe2078b92012-05-24 03:21:38 -07001096 if options.debug:
1097 print
1098 print "Keep in mind that you had --debug enabled, thus nothing was"
1099 print "actually submitted."
Brian Harring3fec5a82012-03-01 05:57:03 -08001100 sys.exit(0)
Ryan Cui54da0702012-04-19 18:38:08 -07001101 elif (not options.buildbot and not options.remote_trybot
1102 and not options.resume and not options.local):
Brian Harring1b8c4c82012-05-29 23:03:04 -07001103 cros_build_lib.Warning(
1104 'Running in LOCAL TRYBOT mode! Use --remote to submit REMOTE '
1105 'tryjobs. Use --local to suppress this message.')
1106 cros_build_lib.Warning(
1107 'Starting April 30th, --local will be required to run the local '
1108 'trybot.')
Ryan Cui54da0702012-04-19 18:38:08 -07001109 time.sleep(5)
Brian Harring3fec5a82012-03-01 05:57:03 -08001110
Ryan Cui8be16062012-04-24 12:05:26 -07001111 # Only expecting one config
1112 bot_id = args[-1]
1113 build_config = _GetConfig(bot_id)
Brian Harring3fec5a82012-03-01 05:57:03 -08001114
1115 if options.reference_repo is None:
Ryan Cui5ba7e152012-05-10 14:36:52 -07001116 repo_path = os.path.join(options.sourceroot, '.repo')
Brian Harring3fec5a82012-03-01 05:57:03 -08001117 # If we're being run from a repo checkout, reuse the repo's git pool to
1118 # cut down on sync time.
1119 if os.path.exists(repo_path):
Ryan Cui5ba7e152012-05-10 14:36:52 -07001120 options.reference_repo = options.sourceroot
Brian Harring3fec5a82012-03-01 05:57:03 -08001121 elif options.reference_repo:
1122 if not os.path.exists(options.reference_repo):
1123 parser.error('Reference path %s does not exist'
1124 % (options.reference_repo,))
1125 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1126 parser.error('Reference path %s does not look to be the base of a '
1127 'repo checkout; no .repo exists in the root.'
1128 % (options.reference_repo,))
Ryan Cuid4a24212012-04-04 18:08:12 -07001129
Brian Harringf11bf682012-05-14 15:53:43 -07001130 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001131 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001132 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1133 'be used together. Cgroup support is required for '
1134 'buildbot/remote-trybot mode.')
Brian Harring470f6112012-03-02 11:47:10 -08001135 if not cgroups.Cgroup.CgroupsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001136 parser.error('Option --buildbot/--remote-trybot was given, but this '
1137 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001138
Brian Harring351ce442012-03-09 16:38:14 -08001139 missing = []
1140 for program in _BUILDBOT_REQUIRED_BINARIES:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001141 ret = cros_build_lib.RunCommand(
1142 'which %s' % program, shell=True, redirect_stderr=True,
1143 redirect_stdout=True, error_code_ok=True, print_cmd=False)
Brian Harring351ce442012-03-09 16:38:14 -08001144 if ret.returncode != 0:
1145 missing.append(program)
1146
1147 if missing:
Ryan Cuid4a24212012-04-04 18:08:12 -07001148 parser.error("Option --buildbot/--remote-trybot requires the following "
1149 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001150 % (', '.join(missing)))
1151
Brian Harring3fec5a82012-03-01 05:57:03 -08001152 if options.reference_repo:
1153 options.reference_repo = os.path.abspath(options.reference_repo)
1154
1155 if options.dump_config:
1156 # This works, but option ordering is bad...
1157 print 'Configuration %s:' % bot_id
1158 pretty_printer = pprint.PrettyPrinter(indent=2)
1159 pretty_printer.pprint(build_config)
1160 sys.exit(0)
1161
1162 if not options.buildroot:
1163 if options.buildbot:
1164 parser.error('Please specify a buildroot with the --buildroot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001165
Ryan Cui5ba7e152012-05-10 14:36:52 -07001166 options.buildroot = _DetermineDefaultBuildRoot(options.sourceroot,
1167 build_config['internal'])
Brian Harring470f6112012-03-02 11:47:10 -08001168 # We use a marker file in the buildroot to indicate the user has
1169 # consented to using this directory.
1170 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1171 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001172
1173 # Sanity check of buildroot- specifically that it's not pointing into the
1174 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001175 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -08001176 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001177 parser.error('Configured buildroot %s points into a repository checkout, '
1178 'rather than the root of it. This is not supported.'
1179 % options.buildroot)
1180
Brian Harringd166aaf2012-05-14 18:31:53 -07001181 log_file = None
1182 if options.tee:
1183 default_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1184 dirname = options.log_dir or default_dir
1185 log_file = os.path.join(dirname, _BUILDBOT_LOG_FILE)
1186
1187 osutils.SafeMakedirs(dirname)
1188 _BackupPreviousLog(log_file)
1189
Brian Harring1b8c4c82012-05-29 23:03:04 -07001190 with cros_build_lib.ContextManagerStack() as stack:
Brian Harringc2d09d92012-05-13 22:03:15 -07001191 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1192 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001193
Brian Harringc2d09d92012-05-13 22:03:15 -07001194 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001195 # If we're in resume mode, use our parents tempdir rather than
1196 # nesting another layer.
Brian Harringc2d09d92012-05-13 22:03:15 -07001197 stack.Add(osutils.TempDirContextManager, 'cbuildbot-tmp')
1198 logging.debug("Cbuildbot tempdir is %r.", os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001199
1200 if log_file is not None:
1201 stack.Add(tee.Tee, log_file)
1202 options.preserve_paths = set([_DEFAULT_LOG_DIR])
1203
Brian Harringc2d09d92012-05-13 22:03:15 -07001204 if options.cgroups:
1205 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001206
Brian Harringc2d09d92012-05-13 22:03:15 -07001207 # Mark everything between EnforcedCleanupSection and here as having to
1208 # be rolled back via the contextmanager cleanup handlers. This
1209 # ensures that sudo bits cannot outlive cbuildbot, that anything
1210 # cgroups would kill gets killed, etc.
1211 critical_section.ForkWatchdog()
Brian Harringd166aaf2012-05-14 18:31:53 -07001212
Brian Harringc2d09d92012-05-13 22:03:15 -07001213 if options.timeout > 0:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001214 stack.Add(cros_build_lib.Timeout, options.timeout)
Brian Harringa184efa2012-03-04 11:51:25 -08001215
Brian Harringc2d09d92012-05-13 22:03:15 -07001216 if not options.buildbot:
1217 build_config = cbuildbot_config.OverrideConfigForTrybot(
1218 build_config,
1219 options.remote_trybot)
1220
1221 _RunBuildStagesWrapper(options, build_config)