blob: e772474390f11d727bd6f9971b89aba981acd0d1 [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']:
Jon Kliegmanc6b4fca2012-06-22 09:58:55 -0700411 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800412
David James944a48e2012-03-07 12:19:03 -0800413 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
414 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800415
416 def RunStages(self):
417 """Runs through build process."""
418 self._RunStage(stages.BuildBoardStage)
419
420 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800421 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
422 self._RunStage(stages.SDKTestStage)
423 self._RunStage(stages.UploadPrebuiltsStage,
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700424 constants.CHROOT_BUILDER_BOARD, None)
Brian Harring3fec5a82012-03-01 05:57:03 -0800425 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
426 self._RunStage(stages.RefreshPackageStatusStage)
427 else:
428 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800429
David James944a48e2012-03-07 12:19:03 -0800430 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800431 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800432 config = configs.get(board, self.build_config)
433 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
434 config=config)
David James58e0c092012-03-04 20:31:12 -0800435 self.archive_stages[board] = archive_stage
436
David James944a48e2012-03-07 12:19:03 -0800437 # Set up a process pool to run test/archive stages in the background.
438 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800439 queue = multiprocessing.Queue()
440 task = self._RunBackgroundStagesForBoard
441 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800442 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800443 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800444 archive_stage = self.archive_stages[board]
445 config = configs.get(board, self.build_config)
446 self._RunStage(stages.BuildTargetStage, board, archive_stage,
Chris Sosa1a87b3e2012-04-12 13:20:42 -0700447 self.release_tag, config=config)
David James58e0c092012-03-04 20:31:12 -0800448 self.archive_urls[board] = archive_stage.GetDownloadUrl()
449
David James944a48e2012-03-07 12:19:03 -0800450 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800451 queue.put([board])
452
Brian Harring3fec5a82012-03-01 05:57:03 -0800453
454class DistributedBuilder(SimpleBuilder):
455 """Build class that has special logic to handle distributed builds.
456
457 These builds sync using git/manifest logic in manifest_versions. In general
458 they use a non-distributed builder code for the bulk of the work.
459 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700460 def __init__(self, *args, **kwargs):
Brian Harring3fec5a82012-03-01 05:57:03 -0800461 """Initializes a buildbot builder.
462
463 Extra variables:
464 completion_stage_class: Stage used to complete a build. Set in the Sync
465 stage.
466 """
Ryan Cuif7f24692012-05-18 16:35:33 -0700467 super(DistributedBuilder, self).__init__(*args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800468 self.completion_stage_class = None
469
470 def GetSyncInstance(self):
471 """Syncs the tree using one of the distributed sync logic paths.
472
473 Returns: the instance of the sync stage that was run.
474 """
475 # Determine sync class to use. CQ overrides PFQ bits so should check it
476 # first.
477 if cbuildbot_config.IsCQType(self.build_config['build_type']):
478 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
479 self.completion_stage_class = stages.CommitQueueCompletionStage
480 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
481 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
482 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
483 else:
484 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
485 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
486
487 return sync_stage
488
489 def Publish(self, was_build_successful):
490 """Completes build by publishing any required information."""
491 completion_stage = self._GetStageInstance(self.completion_stage_class,
492 was_build_successful)
493 completion_stage.Run()
494 name = completion_stage.name
495 if not results_lib.Results.WasStageSuccessful(name):
496 should_publish_changes = False
497 else:
498 should_publish_changes = (self.build_config['master'] and
499 was_build_successful)
500
501 if should_publish_changes:
502 self._RunStage(stages.PublishUprevChangesStage)
503
504 def RunStages(self):
505 """Runs simple builder logic and publishes information to overlays."""
506 was_build_successful = False
507 try:
David Jamesf55709e2012-03-13 09:10:15 -0700508 super(DistributedBuilder, self).RunStages()
509 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800510 except SystemExit as ex:
511 # If a stage calls sys.exit(0), it's exiting with success, so that means
512 # we should mark ourselves as successful.
513 if ex.code == 0:
514 was_build_successful = True
515 raise
516 finally:
517 self.Publish(was_build_successful)
518
Brian Harring3fec5a82012-03-01 05:57:03 -0800519
520def _ConfirmBuildRoot(buildroot):
521 """Confirm with user the inferred buildroot, and mark it as confirmed."""
522 warning = 'Using default directory %s as buildroot' % buildroot
Brian Harring1b8c4c82012-05-29 23:03:04 -0700523 response = cros_build_lib.YesNoPrompt(
524 default=cros_build_lib.NO, warning=warning, full=True)
525 if response == cros_build_lib.NO:
Brian Harring3fec5a82012-03-01 05:57:03 -0800526 print('Please specify a buildroot with the --buildroot option.')
527 sys.exit(0)
528
529 if not os.path.exists(buildroot):
530 os.mkdir(buildroot)
531
532 repository.CreateTrybotMarker(buildroot)
533
534
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700535def _ConfirmRemoteBuildbotRun():
536 """Confirm user wants to run with --buildbot --remote."""
537 warning = ('You are about to launch a PRODUCTION job! This is *NOT* a '
538 'trybot run! Are you sure?')
Brian Harring1b8c4c82012-05-29 23:03:04 -0700539 response = cros_build_lib.YesNoPrompt(
540 default=cros_build_lib.NO, warning=warning, full=True)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700541
Brian Harring1b8c4c82012-05-29 23:03:04 -0700542 if response == cros_build_lib.NO:
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700543 print('Please specify --pass-through="--debug".')
544 sys.exit(0)
545
546
Ryan Cui5ba7e152012-05-10 14:36:52 -0700547def _DetermineDefaultBuildRoot(sourceroot, internal_build):
Brian Harring3fec5a82012-03-01 05:57:03 -0800548 """Default buildroot to be under the directory that contains current checkout.
549
550 Arguments:
551 internal_build: Whether the build is an internal build
Ryan Cui5ba7e152012-05-10 14:36:52 -0700552 sourceroot: Use specified sourceroot.
Brian Harring3fec5a82012-03-01 05:57:03 -0800553 """
Ryan Cui5ba7e152012-05-10 14:36:52 -0700554 if not repository.IsARepoRoot(sourceroot):
Brian Harring1b8c4c82012-05-29 23:03:04 -0700555 cros_build_lib.Die(
556 'Could not find root of local checkout at %s. Please specify '
557 'using the --sourceroot option.' % sourceroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800558
559 # Place trybot buildroot under the directory containing current checkout.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700560 top_level = os.path.dirname(os.path.realpath(sourceroot))
Brian Harring3fec5a82012-03-01 05:57:03 -0800561 if internal_build:
562 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
563 else:
564 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
565
566 return buildroot
567
568
569def _BackupPreviousLog(log_file, backup_limit=25):
570 """Rename previous log.
571
572 Args:
573 log_file: The absolute path to the previous log.
574 """
575 if os.path.exists(log_file):
576 old_logs = sorted(glob.glob(log_file + '.*'),
577 key=distutils.version.LooseVersion)
578
579 if len(old_logs) >= backup_limit:
580 os.remove(old_logs[0])
581
582 last = 0
583 if old_logs:
584 last = int(old_logs.pop().rpartition('.')[2])
585
586 os.rename(log_file, log_file + '.' + str(last + 1))
587
David James944a48e2012-03-07 12:19:03 -0800588def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800589 """Helper function that wraps RunBuildStages()."""
590 def IsDistributedBuilder():
591 """Determines whether the build_config should be a DistributedBuilder."""
592 if not options.buildbot:
593 return False
594 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
595 chrome_rev = build_config['chrome_rev']
596 if options.chrome_rev: chrome_rev = options.chrome_rev
597 # We don't do distributed logic to TOT Chrome PFQ's, nor local
598 # chrome roots (e.g. chrome try bots)
599 if chrome_rev not in [constants.CHROME_REV_TOT,
600 constants.CHROME_REV_LOCAL,
601 constants.CHROME_REV_SPEC]:
602 return True
603
604 return False
605
Brian Harring1b8c4c82012-05-29 23:03:04 -0700606 cros_build_lib.Info("cbuildbot executed with args %s"
607 % ' '.join(map(repr, sys.argv)))
Brian Harring3fec5a82012-03-01 05:57:03 -0800608
Ryan Cuif7f24692012-05-18 16:35:33 -0700609 target = DistributedBuilder if IsDistributedBuilder() else SimpleBuilder
Ryan Cuie1e4e662012-05-21 16:39:46 -0700610 buildbot = target(options, build_config)
Brian Harringd166aaf2012-05-14 18:31:53 -0700611 if not buildbot.Run():
612 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800613
614
615# Parser related functions
Ryan Cui5ba7e152012-05-10 14:36:52 -0700616def _CheckLocalPatches(sourceroot, local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800617 """Do an early quick check of the passed-in patches.
618
619 If the branch of a project is not specified we append the current branch the
620 project is on.
Ryan Cui5ba7e152012-05-10 14:36:52 -0700621
622 Args:
623 sourceroot: The checkout where patches are coming from.
Brian Harring3fec5a82012-03-01 05:57:03 -0800624 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700625 verified_patches = []
Brian Harring1b8c4c82012-05-29 23:03:04 -0700626 manifest = cros_build_lib.ManifestCheckout.Cached(sourceroot)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700627 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800628 components = patch.split(':')
629 if len(components) > 2:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700630 cros_build_lib.Die(
631 'Specify local patches in project[:branch] format. Got %s' % patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800632
633 # validate project
634 project = components[0]
Brian Harring3fec5a82012-03-01 05:57:03 -0800635
Brian Harring609dc4e2012-05-07 02:17:44 -0700636 try:
637 project_dir = manifest.GetProjectPath(project, True)
638 except KeyError:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700639 cros_build_lib.Die('Project %s does not exist.' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800640
641 # If no branch was specified, we use the project's current branch.
642 if len(components) == 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700643 branch = cros_build_lib.GetCurrentBranch(project_dir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800644 if not branch:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700645 cros_build_lib.Die('Project %s is not on a branch!' % project)
Brian Harring3fec5a82012-03-01 05:57:03 -0800646 else:
647 branch = components[1]
Brian Harring1b8c4c82012-05-29 23:03:04 -0700648 if not cros_build_lib.DoesLocalBranchExist(project_dir, branch):
649 cros_build_lib.Die('Project %s does not have branch %s'
650 % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800651
Brian Harring609dc4e2012-05-07 02:17:44 -0700652 verified_patches.append('%s:%s' % (project, branch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800653
Ryan Cuicedd8a52012-03-22 02:28:35 -0700654 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800655
656
Brian Harring3fec5a82012-03-01 05:57:03 -0800657def _CheckChromeVersionOption(_option, _opt_str, value, parser):
658 """Upgrade other options based on chrome_version being passed."""
659 value = value.strip()
660
661 if parser.values.chrome_rev is None and value:
662 parser.values.chrome_rev = constants.CHROME_REV_SPEC
663
664 parser.values.chrome_version = value
665
666
667def _CheckChromeRootOption(_option, _opt_str, value, parser):
668 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800669 if parser.values.chrome_rev is None:
670 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
671
Ryan Cui5ba7e152012-05-10 14:36:52 -0700672 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800673
674
675def _CheckChromeRevOption(_option, _opt_str, value, parser):
676 """Validate the chrome_rev option."""
677 value = value.strip()
678 if value not in constants.VALID_CHROME_REVISIONS:
679 raise optparse.OptionValueError('Invalid chrome rev specified')
680
681 parser.values.chrome_rev = value
682
683
Ryan Cui5ba7e152012-05-10 14:36:52 -0700684class CustomParser(optparse.OptionParser):
685 def add_remote_option(self, *args, **kwargs):
686 """For arguments that are passed-through to remote trybot."""
687 return optparse.OptionParser.add_option(self, *args,
688 remote_pass_through=True,
689 **kwargs)
690
691
692class CustomGroup(optparse.OptionGroup):
693 def add_remote_option(self, *args, **kwargs):
694 """For arguments that are passed-through to remote trybot."""
695 return optparse.OptionGroup.add_option(self, *args,
696 remote_pass_through=True,
697 **kwargs)
698
699
Ryan Cuif7f24692012-05-18 16:35:33 -0700700# pylint: disable=W0613
Ryan Cui5ba7e152012-05-10 14:36:52 -0700701def check_path(option, opt, value):
702 """Expand paths and make them absolute."""
703 expanded = osutils.ExpandPath(value)
704 if expanded == '/':
705 raise optparse.OptionValueError('Invalid path %s specified for %s'
706 % (expanded, opt))
707
708 return expanded
709
710
711class CustomOption(optparse.Option):
712 """Subclass Option class to implement pass-through and path evaluation."""
713 TYPES = optparse.Option.TYPES + ('path',)
714 TYPE_CHECKER = optparse.Option.TYPE_CHECKER.copy()
715 TYPE_CHECKER['path'] = check_path
716
Ryan Cui79319ab2012-05-21 12:59:18 -0700717 ACTIONS = optparse.Option.ACTIONS + ('extend',)
718 STORE_ACTIONS = optparse.Option.STORE_ACTIONS + ('extend',)
719 TYPED_ACTIONS = optparse.Option.TYPED_ACTIONS + ('extend',)
720 ALWAYS_TYPED_ACTIONS = optparse.Option.ALWAYS_TYPED_ACTIONS + ('extend',)
721
Ryan Cui5ba7e152012-05-10 14:36:52 -0700722 def __init__(self, *args, **kwargs):
723 # The remote_pass_through argument specifies whether we should directly
724 # pass the argument (with its value) onto the remote trybot.
725 self.pass_through = kwargs.pop('remote_pass_through', False)
726 optparse.Option.__init__(self, *args, **kwargs)
727
728 def take_action(self, action, dest, opt, value, values, parser):
Ryan Cui79319ab2012-05-21 12:59:18 -0700729 if action == 'extend':
730 lvalue = value.split(' ')
731 values.ensure_value(dest, []).extend(lvalue)
732 else:
733 optparse.Option.take_action(self, action, dest, opt, value, values,
734 parser)
735
Ryan Cui5ba7e152012-05-10 14:36:52 -0700736 if self.pass_through:
737 parser.values.pass_through_args.append(opt)
738 if self.nargs and self.nargs > 1:
739 # value is a tuple if nargs > 1
740 string_list = [str(val) for val in list(value)]
741 parser.values.pass_through_args.extend(string_list)
742 elif value:
743 parser.values.pass_through_args.append(str(value))
744
745
Brian Harring3fec5a82012-03-01 05:57:03 -0800746def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700747 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800748 # Parse options
749 usage = "usage: %prog [options] buildbot_config"
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700750 parser = CustomParser(usage=usage, option_class=CustomOption)
Brian Harring3fec5a82012-03-01 05:57:03 -0800751
752 # Main options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700753 # The remote_pass_through parameter to add_option is implemented by the
754 # CustomOption class. See CustomOption for more information.
Brian Harring3fec5a82012-03-01 05:57:03 -0800755 parser.add_option('-a', '--all', action='store_true', dest='print_all',
756 default=False,
757 help=('List all of the buildbot configs available. Use '
758 'with the --list option'))
Ryan Cuie1e4e662012-05-21 16:39:46 -0700759 parser.add_remote_option('-b', '--branch',
760 help='The manifest branch to test. The branch to '
761 'check the buildroot out to.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700762 parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700763 help='Root directory where source is checked out to, and '
764 'where the build occurs. For external build configs, '
765 "defaults to 'trybot' directory at top level of your "
766 'repo-managed checkout.')
767 parser.add_remote_option('--chrome_rev', default=None, type='string',
768 action='callback', dest='chrome_rev',
769 callback=_CheckChromeRevOption,
770 help=('Revision of Chrome to use, of type [%s]'
771 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cui79319ab2012-05-21 12:59:18 -0700772 parser.add_remote_option('-g', '--gerrit-patches', action='extend',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700773 default=[], type='string',
774 metavar="'Id1 *int_Id2...IdN'",
775 help=("Space-separated list of short-form Gerrit "
776 "Change-Id's or change numbers to patch. "
777 "Please prepend '*' to internal Change-Id's"))
Brian Harring3fec5a82012-03-01 05:57:03 -0800778 parser.add_option('-l', '--list', action='store_true', dest='list',
779 default=False,
780 help=('List the suggested trybot configs to use. Use '
781 '--all to list all of the available configs.'))
Ryan Cui54da0702012-04-19 18:38:08 -0700782 parser.add_option('--local', default=False, action='store_true',
783 help=('Specifies that this tryjob should be run locally.'))
Ryan Cui79319ab2012-05-21 12:59:18 -0700784 parser.add_option('-p', '--local-patches', action='extend', default=[],
Brian Harring3fec5a82012-03-01 05:57:03 -0800785 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
786 help=('Space-separated list of project branches with '
787 'patches to apply. Projects are specified by name. '
788 'If no branch is specified the current branch of the '
789 'project will be used.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700790 parser.add_remote_option('--profile', default=None, type='string',
791 action='store', dest='profile',
792 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800793 parser.add_option('--remote', default=False, action='store_true',
Brian Harring3fec5a82012-03-01 05:57:03 -0800794 help=('Specifies that this tryjob should be run remotely.'))
795
796 # Advanced options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700797 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800798 parser,
799 'Advanced Options',
800 'Caution: use these options at your own risk.')
801
Ryan Cui42aeae32012-05-21 17:09:09 -0700802 # bootstrap-args are not verified by the bootstrap code. It gets passed
803 # direcly to the bootstrap re-execution.
804 group.add_remote_option('--bootstrap-args', action='append',
805 default=[], help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700806 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
807 default=False, help='This is running on a buildbot')
808 group.add_remote_option('--buildnumber', help='build number', type='int',
809 default=0)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700810 group.add_option('--chrome_root', default=None, type='path',
811 action='callback', callback=_CheckChromeRootOption,
812 dest='chrome_root', help='Local checkout of Chrome to use.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700813 group.add_remote_option('--chrome_version', default=None, type='string',
814 action='callback', dest='chrome_version',
815 callback=_CheckChromeVersionOption,
816 help='Used with SPEC logic to force a particular SVN '
817 'revision of chrome rather than the latest.')
818 group.add_remote_option('--clobber', action='store_true', dest='clobber',
819 default=False,
820 help='Clears an old checkout before syncing')
821 group.add_remote_option('--lkgm', action='store_true', dest='lkgm',
822 default=False,
823 help='Sync to last known good manifest blessed by '
824 'PFQ')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700825 parser.add_option('--log_dir', dest='log_dir', type='path',
Brian Harring3fec5a82012-03-01 05:57:03 -0800826 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700827 group.add_remote_option('--maxarchives', dest='max_archive_builds',
828 default=3, type='int',
829 help="Change the local saved build count limit.")
830 group.add_remote_option('--noarchive', action='store_false', dest='archive',
831 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700832 group.add_remote_option('--nobootstrap', action='store_false',
833 dest='bootstrap', default=True,
834 help="Don't checkout and run from a standalone "
835 "chromite repo.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700836 group.add_remote_option('--nobuild', action='store_false', dest='build',
837 default=True,
838 help="Don't actually build (for cbuildbot dev)")
839 group.add_remote_option('--noclean', action='store_false', dest='clean',
840 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700841 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
842 default=True,
843 help='Disable cbuildbots usage of cgroups.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700844 group.add_remote_option('--noprebuilts', action='store_false',
845 dest='prebuilts', default=True,
846 help="Don't upload prebuilts.")
847 group.add_remote_option('--nosync', action='store_false', dest='sync',
848 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700849 group.add_remote_option('--notests', action='store_false', dest='tests',
850 default=True,
851 help='Override values from buildconfig and run no '
852 'tests.')
853 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
854 default=True,
855 help='Override values from buildconfig and never '
856 'uprev.')
857 group.add_option('--pass-through', dest='pass_through_args', action='append',
858 type='string', default=[], help=optparse.SUPPRESS_HELP)
Brian Harring3fec5a82012-03-01 05:57:03 -0800859 group.add_option('--reference-repo', action='store', default=None,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700860 dest='reference_repo',
861 help='Reuse git data stored in an existing repo '
862 'checkout. This can drastically reduce the network '
863 'time spent setting up the trybot checkout. By '
864 "default, if this option isn't given but cbuildbot "
865 'is invoked from a repo checkout, cbuildbot will '
866 'use the repo root.')
Brian Harring37e559b2012-05-22 20:47:32 -0700867 # Used for handling forwards/backwards compatibility for --resume and
868 # --bootstrap.
869 group.add_option('--reexec-api-version', dest='output_api_version',
870 action='store_true', default=False,
871 help=optparse.SUPPRESS_HELP)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700872 # Indicates this is running on a remote trybot machine.
Ryan Cuiba41ad32012-03-08 17:15:29 -0800873 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700874 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700875 # Patches uploaded by trybot client when run using the -p option.
Ryan Cui79319ab2012-05-21 12:59:18 -0700876 group.add_remote_option('--remote-patches', action='extend', default=[],
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700877 help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700878 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700879 help='Skip stages already successfully completed.')
880 group.add_remote_option('--timeout', action='store', type='int', default=0,
881 help='Specify the maximum amount of time this job '
882 'can run for, at which point the build will be '
883 'aborted. If set to zero, then there is no '
884 'timeout.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700885 # Specify specific remote tryslaves to run on.
886 group.add_option('--slaves', action='extend', default=[],
887 help=optparse.SUPPRESS_HELP)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700888 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT,
889 help=optparse.SUPPRESS_HELP)
Ryan Cuif7f24692012-05-18 16:35:33 -0700890 # Causes cbuildbot to bootstrap itself twice, in the sequence A->B->C.
891 # A(unpatched) patches and bootstraps B. B patches and bootstraps C.
892 group.add_remote_option('--test-bootstrap', action='store_true',
893 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cui39bdbbf2012-02-29 16:15:39 -0800894 group.add_option('--test-tryjob', action='store_true',
895 default=False,
896 help='Submit a tryjob to the test repository. Will not '
897 'show up on the production trybot waterfall.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700898 group.add_remote_option('--validation_pool', default=None,
899 help='Path to a pickled validation pool. Intended '
900 'for use only with the commit queue.')
901 group.add_remote_option('--version', dest='force_version', default=None,
902 help='Used with manifest logic. Forces use of this '
903 'version rather than create or get latest.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800904
905 parser.add_option_group(group)
906
907 # Debug options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700908 group = CustomGroup(parser, "Debug Options")
Brian Harring3fec5a82012-03-01 05:57:03 -0800909
Ryan Cui85867972012-02-23 18:21:49 -0800910 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800911 help='Override some options to run as a developer.')
912 group.add_option('--dump_config', action='store_true', dest='dump_config',
913 default=False,
914 help='Dump out build config options, and exit.')
915 group.add_option('--notee', action='store_false', dest='tee', default=True,
916 help="Disable logging and internal tee process. Primarily "
917 "used for debugging cbuildbot itself.")
918 parser.add_option_group(group)
919 return parser
920
921
Ryan Cui85867972012-02-23 18:21:49 -0800922def _FinishParsing(options, args):
923 """Perform some parsing tasks that need to take place after optparse.
924
925 This function needs to be easily testable! Keep it free of
926 environment-dependent code. Put more detailed usage validation in
927 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800928
929 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800930 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800931 """
Brian Harring07039b52012-05-13 17:56:47 -0700932 # Setup logging levels first so any parsing triggered log messages
933 # are appropriately filtered.
934 logging.getLogger().setLevel(
935 logging.DEBUG if options.debug else logging.INFO)
936
Brian Harring3fec5a82012-03-01 05:57:03 -0800937 if options.chrome_root:
938 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700939 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
940 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800941 else:
942 if options.chrome_rev == constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700943 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
944 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800945
946 if options.chrome_version:
947 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700948 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
949 constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800950 else:
951 if options.chrome_rev == constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700952 cros_build_lib.Die(
953 'Chrome rev must not be %s if chrome_version is not set.'
954 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800955
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700956 patches = bool(options.gerrit_patches or options.local_patches)
957 if options.remote:
958 if options.local:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700959 cros_build_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -0700960
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700961 if not options.buildbot and not patches:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700962 cros_build_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800963
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700964 # --debug needs to be explicitly passed through for remote invocations.
965 release_mode_with_patches = (options.buildbot and patches and
966 '--debug' not in options.pass_through_args)
967 else:
968 if len(args) > 1:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700969 cros_build_lib.Die('Multiple configs not supported if not running with '
970 '--remote.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700971
Ryan Cui79319ab2012-05-21 12:59:18 -0700972 if options.slaves:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700973 cros_build_lib.Die('Cannot use --slaves if not running with --remote.')
Ryan Cui79319ab2012-05-21 12:59:18 -0700974
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700975 release_mode_with_patches = (options.buildbot and patches and
976 not options.debug)
977
978 # When running in release mode, make sure we are running with checked-in code.
979 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
980 # a release image with checked-in code for CrOS packages.
981 if release_mode_with_patches:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700982 cros_build_lib.Die(
983 'Cannot provide patches when running with --buildbot!')
Brian Harring3fec5a82012-03-01 05:57:03 -0800984
Ryan Cuiba41ad32012-03-08 17:15:29 -0800985 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700986 cros_build_lib.Die(
987 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800988
Ryan Cui85867972012-02-23 18:21:49 -0800989 # Record whether --debug was set explicitly vs. it was inferred.
990 options.debug_forced = False
991 if options.debug:
992 options.debug_forced = True
993 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800994 # We don't set debug by default for
995 # 1. --buildbot invocations.
996 # 2. --remote invocations, because it needs to push changes to the tryjob
997 # repo.
998 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -0800999
Brian Harring3fec5a82012-03-01 05:57:03 -08001000
Brian Harring1d7ba942012-04-24 06:37:18 -07001001# pylint: disable=W0613
Ryan Cui85867972012-02-23 18:21:49 -08001002def _PostParseCheck(options, args):
1003 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -08001004
Ryan Cui85867972012-02-23 18:21:49 -08001005 Args:
1006 options/args: The options/args object returned by optparse
1007 """
Ryan Cuie1e4e662012-05-21 16:39:46 -07001008 if not options.branch:
1009 options.branch = _GetChromiteTrackingBranch()
1010
Ryan Cui5ba7e152012-05-10 14:36:52 -07001011 if options.local_patches and not repository.IsARepoRoot(options.sourceroot):
1012 raise Exception('Could not find repo checkout at %s!'
1013 % options.sourceroot)
1014
Brian Harring609dc4e2012-05-07 02:17:44 -07001015 if options.local_patches:
Brian Harring1d7ba942012-04-24 06:37:18 -07001016 options.local_patches = _CheckLocalPatches(
Brian Harring609dc4e2012-05-07 02:17:44 -07001017 options.sourceroot, options.local_patches)
Brian Harring1d7ba942012-04-24 06:37:18 -07001018
1019 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
1020 if (default and not any([options.local, options.buildbot,
1021 options.remote, options.remote_trybot])):
Brian Harring1b8c4c82012-05-29 23:03:04 -07001022 cros_build_lib.Info("CBUILDBOT_DEFAULT_MODE=%s env var detected, using it."
1023 % default)
Brian Harring1d7ba942012-04-24 06:37:18 -07001024 default = default.lower()
1025 if default == 'local':
1026 options.local = True
1027 elif default == 'remote':
1028 options.remote = True
1029 elif default == 'buildbot':
1030 options.buildbot = True
1031 else:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001032 cros_build_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
1033 % default)
Ryan Cui85867972012-02-23 18:21:49 -08001034
1035
1036def _ParseCommandLine(parser, argv):
1037 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -08001038 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -07001039
1040 if options.output_api_version:
1041 print _REEXEC_API_VERSION
1042 sys.exit(0)
1043
Ryan Cui54da0702012-04-19 18:38:08 -07001044 if options.list:
1045 _PrintValidConfigs(options.print_all)
1046 sys.exit(0)
1047
Ryan Cui8be16062012-04-24 12:05:26 -07001048 # Strip out null arguments.
1049 # TODO(rcui): Remove when buildbot is fixed
1050 args = [arg for arg in args if arg]
1051 if not args:
1052 parser.error('Invalid usage. Use -h to see usage. Use -l to list '
1053 'supported configs.')
1054
Ryan Cui85867972012-02-23 18:21:49 -08001055 _FinishParsing(options, args)
1056 return options, args
1057
1058
1059def main(argv):
1060 # Set umask to 022 so files created by buildbot are readable.
1061 os.umask(022)
1062
Brian Harring1b8c4c82012-05-29 23:03:04 -07001063 if cros_build_lib.IsInsideChroot():
1064 cros_build_lib.Die('Please run cbuildbot from outside the chroot.')
Ryan Cui85867972012-02-23 18:21:49 -08001065
1066 parser = _CreateParser()
1067 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -08001068
Brian Harring3fec5a82012-03-01 05:57:03 -08001069 _PostParseCheck(options, args)
1070
1071 if options.remote:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001072 cros_build_lib.logger.setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001073
Brian Harring3fec5a82012-03-01 05:57:03 -08001074 # Verify configs are valid.
1075 for bot in args:
1076 _GetConfig(bot)
1077
1078 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -08001079 print 'Verifying patches...'
Ryan Cuie1e4e662012-05-21 16:39:46 -07001080 patch_pool = AcquirePoolFromOptions(options)
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001081
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001082 # --debug need to be explicitly passed through for remote invocations.
1083 if options.buildbot and '--debug' not in options.pass_through_args:
1084 _ConfirmRemoteBuildbotRun()
1085
Ryan Cui16ca5812012-03-08 20:34:27 -08001086 print 'Submitting tryjob...'
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001087 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cui39bdbbf2012-02-29 16:15:39 -08001088 tryjob.Submit(testjob=options.test_tryjob, dryrun=options.debug)
Ryan Cui16ca5812012-03-08 20:34:27 -08001089 print 'Tryjob submitted!'
1090 print ('Go to %s to view the status of your job.'
Ryan Cui4906e1c2012-04-03 20:09:34 -07001091 % tryjob.GetTrybotWaterfallLink())
Brian Harringe2078b92012-05-24 03:21:38 -07001092 if options.debug:
1093 print
1094 print "Keep in mind that you had --debug enabled, thus nothing was"
1095 print "actually submitted."
Brian Harring3fec5a82012-03-01 05:57:03 -08001096 sys.exit(0)
Ryan Cui54da0702012-04-19 18:38:08 -07001097 elif (not options.buildbot and not options.remote_trybot
1098 and not options.resume and not options.local):
Brian Harring1b8c4c82012-05-29 23:03:04 -07001099 cros_build_lib.Warning(
1100 'Running in LOCAL TRYBOT mode! Use --remote to submit REMOTE '
1101 'tryjobs. Use --local to suppress this message.')
1102 cros_build_lib.Warning(
1103 'Starting April 30th, --local will be required to run the local '
1104 'trybot.')
Ryan Cui54da0702012-04-19 18:38:08 -07001105 time.sleep(5)
Brian Harring3fec5a82012-03-01 05:57:03 -08001106
Ryan Cui8be16062012-04-24 12:05:26 -07001107 # Only expecting one config
1108 bot_id = args[-1]
1109 build_config = _GetConfig(bot_id)
Brian Harring3fec5a82012-03-01 05:57:03 -08001110
1111 if options.reference_repo is None:
Ryan Cui5ba7e152012-05-10 14:36:52 -07001112 repo_path = os.path.join(options.sourceroot, '.repo')
Brian Harring3fec5a82012-03-01 05:57:03 -08001113 # If we're being run from a repo checkout, reuse the repo's git pool to
1114 # cut down on sync time.
1115 if os.path.exists(repo_path):
Ryan Cui5ba7e152012-05-10 14:36:52 -07001116 options.reference_repo = options.sourceroot
Brian Harring3fec5a82012-03-01 05:57:03 -08001117 elif options.reference_repo:
1118 if not os.path.exists(options.reference_repo):
1119 parser.error('Reference path %s does not exist'
1120 % (options.reference_repo,))
1121 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1122 parser.error('Reference path %s does not look to be the base of a '
1123 'repo checkout; no .repo exists in the root.'
1124 % (options.reference_repo,))
Ryan Cuid4a24212012-04-04 18:08:12 -07001125
Brian Harringf11bf682012-05-14 15:53:43 -07001126 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001127 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001128 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1129 'be used together. Cgroup support is required for '
1130 'buildbot/remote-trybot mode.')
Brian Harring470f6112012-03-02 11:47:10 -08001131 if not cgroups.Cgroup.CgroupsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001132 parser.error('Option --buildbot/--remote-trybot was given, but this '
1133 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001134
Brian Harring351ce442012-03-09 16:38:14 -08001135 missing = []
1136 for program in _BUILDBOT_REQUIRED_BINARIES:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001137 ret = cros_build_lib.RunCommand(
1138 'which %s' % program, shell=True, redirect_stderr=True,
1139 redirect_stdout=True, error_code_ok=True, print_cmd=False)
Brian Harring351ce442012-03-09 16:38:14 -08001140 if ret.returncode != 0:
1141 missing.append(program)
1142
1143 if missing:
Ryan Cuid4a24212012-04-04 18:08:12 -07001144 parser.error("Option --buildbot/--remote-trybot requires the following "
1145 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001146 % (', '.join(missing)))
1147
Brian Harring3fec5a82012-03-01 05:57:03 -08001148 if options.reference_repo:
1149 options.reference_repo = os.path.abspath(options.reference_repo)
1150
1151 if options.dump_config:
1152 # This works, but option ordering is bad...
1153 print 'Configuration %s:' % bot_id
1154 pretty_printer = pprint.PrettyPrinter(indent=2)
1155 pretty_printer.pprint(build_config)
1156 sys.exit(0)
1157
1158 if not options.buildroot:
1159 if options.buildbot:
1160 parser.error('Please specify a buildroot with the --buildroot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001161
Ryan Cui5ba7e152012-05-10 14:36:52 -07001162 options.buildroot = _DetermineDefaultBuildRoot(options.sourceroot,
1163 build_config['internal'])
Brian Harring470f6112012-03-02 11:47:10 -08001164 # We use a marker file in the buildroot to indicate the user has
1165 # consented to using this directory.
1166 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1167 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001168
1169 # Sanity check of buildroot- specifically that it's not pointing into the
1170 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001171 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -08001172 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001173 parser.error('Configured buildroot %s points into a repository checkout, '
1174 'rather than the root of it. This is not supported.'
1175 % options.buildroot)
1176
Brian Harringd166aaf2012-05-14 18:31:53 -07001177 log_file = None
1178 if options.tee:
1179 default_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1180 dirname = options.log_dir or default_dir
1181 log_file = os.path.join(dirname, _BUILDBOT_LOG_FILE)
1182
1183 osutils.SafeMakedirs(dirname)
1184 _BackupPreviousLog(log_file)
1185
Brian Harring1b8c4c82012-05-29 23:03:04 -07001186 with cros_build_lib.ContextManagerStack() as stack:
Brian Harringc2d09d92012-05-13 22:03:15 -07001187 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1188 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001189
Brian Harringc2d09d92012-05-13 22:03:15 -07001190 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001191 # If we're in resume mode, use our parents tempdir rather than
1192 # nesting another layer.
Brian Harringc2d09d92012-05-13 22:03:15 -07001193 stack.Add(osutils.TempDirContextManager, 'cbuildbot-tmp')
1194 logging.debug("Cbuildbot tempdir is %r.", os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001195
1196 if log_file is not None:
1197 stack.Add(tee.Tee, log_file)
1198 options.preserve_paths = set([_DEFAULT_LOG_DIR])
1199
Brian Harringc2d09d92012-05-13 22:03:15 -07001200 if options.cgroups:
1201 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001202
Brian Harringc2d09d92012-05-13 22:03:15 -07001203 # Mark everything between EnforcedCleanupSection and here as having to
1204 # be rolled back via the contextmanager cleanup handlers. This
1205 # ensures that sudo bits cannot outlive cbuildbot, that anything
1206 # cgroups would kill gets killed, etc.
1207 critical_section.ForkWatchdog()
Brian Harringd166aaf2012-05-14 18:31:53 -07001208
Brian Harringc2d09d92012-05-13 22:03:15 -07001209 if options.timeout > 0:
Brian Harring1b8c4c82012-05-29 23:03:04 -07001210 stack.Add(cros_build_lib.Timeout, options.timeout)
Brian Harringa184efa2012-03-04 11:51:25 -08001211
Brian Harringc2d09d92012-05-13 22:03:15 -07001212 if not options.buildbot:
1213 build_config = cbuildbot_config.OverrideConfigForTrybot(
1214 build_config,
1215 options.remote_trybot)
1216
1217 _RunBuildStagesWrapper(options, build_config)