blob: 77fef0f18c9103bb0a5d823410c3bf16a28f1cf9 [file] [log] [blame]
Brian Harring3fec5a82012-03-01 05:57:03 -08001#!/usr/bin/python
2
3# Copyright (c) 2011-2012 The Chromium OS Authors. All rights reserved.
4# Use of this source code is governed by a BSD-style license that can be
5# found in the LICENSE file.
6
7"""Main builder code for Chromium OS.
8
9Used by Chromium OS buildbot configuration for all Chromium OS builds including
10full and pre-flight-queue builds.
11"""
12
13import distutils.version
14import glob
David James58e0c092012-03-04 20:31:12 -080015import multiprocessing
Brian Harring3fec5a82012-03-01 05:57:03 -080016import optparse
17import os
18import pprint
19import sys
20
21from chromite.buildbot import builderstage as bs
22from chromite.buildbot import cbuildbot_background as background
23from chromite.buildbot import cbuildbot_config
24from chromite.buildbot import cbuildbot_stages as stages
25from chromite.buildbot import cbuildbot_results as results_lib
Brian Harring3fec5a82012-03-01 05:57:03 -080026from chromite.buildbot import constants
27from chromite.buildbot import gerrit_helper
28from chromite.buildbot import patch as cros_patch
29from chromite.buildbot import remote_try
30from chromite.buildbot import repository
31from chromite.buildbot import tee
32
Brian Harringc92a7012012-02-29 10:11:34 -080033from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080034from chromite.lib import cleanup
Brian Harring3fec5a82012-03-01 05:57:03 -080035from chromite.lib import cros_build_lib as cros_lib
36from chromite.lib import sudo
37
Ryan Cuiadd49122012-03-21 22:19:58 -070038
Brian Harring3fec5a82012-03-01 05:57:03 -080039cros_lib.STRICT_SUDO = True
40
41_DEFAULT_LOG_DIR = 'cbuildbot_logs'
42_BUILDBOT_LOG_FILE = 'cbuildbot.log'
43_DEFAULT_EXT_BUILDROOT = 'trybot'
44_DEFAULT_INT_BUILDROOT = 'trybot-internal'
45_PATH_TO_CBUILDBOT = 'chromite/bin/cbuildbot'
46_DISTRIBUTED_TYPES = [constants.COMMIT_QUEUE_TYPE, constants.PFQ_TYPE,
47 constants.CANARY_TYPE, constants.CHROME_PFQ_TYPE,
48 constants.PALADIN_TYPE]
Brian Harring351ce442012-03-09 16:38:14 -080049_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Brian Harring3fec5a82012-03-01 05:57:03 -080050
51
52def _PrintValidConfigs(trybot_only=True):
53 """Print a list of valid buildbot configs.
54
55 Arguments:
56 trybot_only: Only print selected trybot configs, as specified by the
57 'trybot_list' config setting.
58 """
59 COLUMN_WIDTH = 45
60 print 'config'.ljust(COLUMN_WIDTH), 'description'
61 print '------'.ljust(COLUMN_WIDTH), '-----------'
62 config_names = cbuildbot_config.config.keys()
63 config_names.sort()
64 for name in config_names:
65 if not trybot_only or cbuildbot_config.config[name]['trybot_list']:
66 desc = ''
67 if cbuildbot_config.config[name]['description']:
68 desc = cbuildbot_config.config[name]['description']
69
70 print name.ljust(COLUMN_WIDTH), desc
71
72
73def _GetConfig(config_name):
74 """Gets the configuration for the build"""
75 if not cbuildbot_config.config.has_key(config_name):
76 print 'Non-existent configuration %s specified.' % config_name
77 print 'Please specify one of:'
78 _PrintValidConfigs()
79 sys.exit(1)
80
81 result = cbuildbot_config.config[config_name]
82
83 return result
84
85
86def _GetChromiteTrackingBranch():
David James66009462012-03-25 10:08:38 -070087 """Returns the remote branch associated with chromite."""
Brian Harring3fec5a82012-03-01 05:57:03 -080088 cwd = os.path.dirname(os.path.realpath(__file__))
David James66009462012-03-25 10:08:38 -070089 branch = cros_lib.GetCurrentBranch(cwd)
90 if branch:
91 tracking_branch = cros_lib.GetTrackingBranch(branch, cwd)[1]
92 if tracking_branch.startswith('refs/heads/'):
93 return tracking_branch.replace('refs/heads/', '')
94 # If we are not on a branch, or if the tracking branch is a revision,
95 # use the default manifest branch. This only works if we are in a
96 # repo repository. TODO(davidjames): Fix this to work if we're not in a repo
97 # repository.
98 return cros_lib.GetManifestDefaultBranch(cwd)
Brian Harring3fec5a82012-03-01 05:57:03 -080099
100
101def _CheckBuildRootBranch(buildroot, tracking_branch):
102 """Make sure buildroot branch is the same as Chromite branch."""
103 manifest_branch = cros_lib.GetManifestDefaultBranch(buildroot)
104 if manifest_branch != tracking_branch:
105 cros_lib.Die('Chromite is not on same branch as buildroot checkout\n' +
106 'Chromite is on branch %s.\n' % tracking_branch +
107 'Buildroot checked out to %s\n' % manifest_branch)
108
109
110def _PreProcessPatches(gerrit_patches, local_patches):
111 """Validate patches ASAP to catch user errors. Also generate patch info.
112
113 Args:
114 gerrit_patches: List of gerrit CL ID's passed in by user.
115 local_patches: List of local project branches to generate patches from.
116
117 Returns:
118 A tuple containing a list of cros_patch.GerritPatch and a list of
119 cros_patch.LocalPatch objects.
120 """
121 gerrit_patch_info = []
122 local_patch_info = []
123
124 try:
125 if gerrit_patches:
126 gerrit_patch_info = gerrit_helper.GetGerritPatchInfo(gerrit_patches)
127 for patch in gerrit_patch_info:
128 if patch.IsAlreadyMerged():
129 cros_lib.Warning('Patch %s has already been merged.' % str(patch))
130 except gerrit_helper.GerritException as e:
131 cros_lib.Die(str(e))
132
133 try:
134 if local_patches:
135 local_patch_info = cros_patch.PrepareLocalPatches(
136 local_patches,
137 _GetChromiteTrackingBranch())
138
139 except cros_patch.PatchException as e:
140 cros_lib.Die(str(e))
141
142 return gerrit_patch_info, local_patch_info
143
144
145def _IsIncrementalBuild(buildroot, clobber):
146 """Returns True if we are reusing an existing buildroot."""
147 repo_dir = os.path.join(buildroot, '.repo')
148 return not clobber and os.path.isdir(repo_dir)
149
150
151class Builder(object):
152 """Parent class for all builder types.
153
154 This class functions as a parent class for various build types. It's intended
155 use is builder_instance.Run().
156
157 Vars:
Brian Harring3fec5a82012-03-01 05:57:03 -0800158 build_config: The configuration dictionary from cbuildbot_config.
159 options: The options provided from optparse in main().
160 completed_stages_file: Where we store resume state.
161 archive_url: Where our artifacts for this builder will be archived.
162 tracking_branch: The tracking branch for this build.
163 release_tag: The associated "chrome os version" of this build.
164 gerrit_patches: Gerrit patches to be included in build.
165 local_patches: Local patches to be included in build.
166 """
167
David James944a48e2012-03-07 12:19:03 -0800168 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800169 """Initializes instance variables. Must be called by all subclasses."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800170 self.build_config = build_config
171 self.options = options
172
173 # TODO, Remove here and in config after bug chromium-os:14649 is fixed.
174 if self.build_config['chromeos_official']:
175 os.environ['CHROMEOS_OFFICIAL'] = '1'
176
177 self.completed_stages_file = os.path.join(options.buildroot,
178 '.completed_stages')
David James58e0c092012-03-04 20:31:12 -0800179 self.archive_stages = {}
Brian Harring3fec5a82012-03-01 05:57:03 -0800180 self.archive_urls = {}
181 self.release_tag = None
182 self.tracking_branch = _GetChromiteTrackingBranch()
183 self.gerrit_patches = None
184 self.local_patches = None
185
186 def Initialize(self):
187 """Runs through the initialization steps of an actual build."""
188 if self.options.resume and os.path.exists(self.completed_stages_file):
189 with open(self.completed_stages_file, 'r') as load_file:
190 results_lib.Results.RestoreCompletedStages(load_file)
191
192 # We only want to do this if we need to patch changes.
193 if not results_lib.Results.GetPrevious().get(
194 self._GetStageInstance(stages.PatchChangesStage, None, None).name):
195 self.gerrit_patches, self.local_patches = _PreProcessPatches(
196 self.options.gerrit_patches, self.options.local_patches)
197
198 bs.BuilderStage.SetTrackingBranch(self.tracking_branch)
199
200 # Check branch matching early.
201 if _IsIncrementalBuild(self.options.buildroot, self.options.clobber):
202 _CheckBuildRootBranch(self.options.buildroot, self.tracking_branch)
203
204 self._RunStage(stages.CleanUpStage)
205
206 def _GetStageInstance(self, stage, *args, **kwargs):
207 """Helper function to get an instance given the args.
208
David James944a48e2012-03-07 12:19:03 -0800209 Useful as almost all stages just take in options and build_config.
Brian Harring3fec5a82012-03-01 05:57:03 -0800210 """
David James944a48e2012-03-07 12:19:03 -0800211 config = kwargs.pop('config', self.build_config)
212 return stage(self.options, config, *args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800213
214 def _SetReleaseTag(self):
215 """Sets the release tag from the manifest_manager.
216
217 Must be run after sync stage as syncing enables us to have a release tag.
218 """
219 # Extract version we have decided to build into self.release_tag.
220 manifest_manager = stages.ManifestVersionedSyncStage.manifest_manager
221 if manifest_manager:
222 self.release_tag = manifest_manager.current_version
223
224 def _RunStage(self, stage, *args, **kwargs):
225 """Wrapper to run a stage."""
226 stage_instance = self._GetStageInstance(stage, *args, **kwargs)
227 return stage_instance.Run()
228
229 def GetSyncInstance(self):
230 """Returns an instance of a SyncStage that should be run.
231
232 Subclasses must override this method.
233 """
234 raise NotImplementedError()
235
236 def RunStages(self):
237 """Subclasses must override this method. Runs the appropriate code."""
238 raise NotImplementedError()
239
240 def _WriteCheckpoint(self):
241 """Drops a completed stages file with current state."""
242 with open(self.completed_stages_file, 'w+') as save_file:
243 results_lib.Results.SaveCompletedStages(save_file)
244
245 def _ShouldReExecuteInBuildRoot(self):
246 """Returns True if this build should be re-executed in the buildroot."""
247 abs_buildroot = os.path.abspath(self.options.buildroot)
248 return not os.path.abspath(__file__).startswith(abs_buildroot)
249
250 def _ReExecuteInBuildroot(self, sync_instance):
251 """Reexecutes self in buildroot and returns True if build succeeds.
252
253 This allows the buildbot code to test itself when changes are patched for
254 buildbot-related code. This is a no-op if the buildroot == buildroot
255 of the running chromite checkout.
256
257 Args:
258 sync_instance: Instance of the sync stage that was run to sync.
259
260 Returns:
261 True if the Build succeeded.
262 """
263 # If we are resuming, use last checkpoint.
264 if not self.options.resume:
265 self._WriteCheckpoint()
266
267 # Re-write paths to use absolute paths.
268 # Suppress any timeout options given from the commandline in the
269 # invoked cbuildbot; our timeout will enforce it instead.
270 args_to_append = ['--resume', '--timeout', '0', '--buildroot',
271 os.path.abspath(self.options.buildroot)]
272
273 if self.options.chrome_root:
274 args_to_append += ['--chrome_root',
275 os.path.abspath(self.options.chrome_root)]
276
277 if stages.ManifestVersionedSyncStage.manifest_manager:
278 ver = stages.ManifestVersionedSyncStage.manifest_manager.current_version
279 args_to_append += ['--version', ver]
280
281 if isinstance(sync_instance, stages.CommitQueueSyncStage):
282 vp_file = sync_instance.SaveValidationPool()
283 args_to_append += ['--validation_pool', vp_file]
284
285 # Re-run the command in the buildroot.
286 # Finally, be generous and give the invoked cbuildbot 30s to shutdown
287 # when something occurs. It should exit quicker, but the sigterm may
288 # hit while the system is particularly busy.
289 return_obj = cros_lib.RunCommand(
290 [_PATH_TO_CBUILDBOT] + sys.argv[1:] + args_to_append,
291 cwd=self.options.buildroot, error_code_ok=True, kill_timeout=30)
292 return return_obj.returncode == 0
293
294 def Run(self):
295 """Main runner for this builder class. Runs build and prints summary."""
296 print_report = True
297 success = True
298 try:
299 self.Initialize()
300 sync_instance = self.GetSyncInstance()
301 sync_instance.Run()
302 self._SetReleaseTag()
303
Ryan Cuicedd8a52012-03-22 02:28:35 -0700304 if (self.gerrit_patches or self.local_patches
305 or self.options.remote_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800306 self._RunStage(stages.PatchChangesStage,
307 self.gerrit_patches, self.local_patches)
308
309 if self._ShouldReExecuteInBuildRoot():
310 print_report = False
311 success = self._ReExecuteInBuildroot(sync_instance)
312 else:
313 self.RunStages()
314
315 finally:
316 if print_report:
317 self._WriteCheckpoint()
318 print '\n\n\n@@@BUILD_STEP Report@@@\n'
319 results_lib.Results.Report(sys.stdout, self.archive_urls,
320 self.release_tag)
321 success = results_lib.Results.BuildSucceededSoFar()
322
323 return success
324
325
326class SimpleBuilder(Builder):
327 """Builder that performs basic vetting operations."""
328
329 def GetSyncInstance(self):
330 """Sync to lkgm or TOT as necessary.
331
332 Returns: the instance of the sync stage that was run.
333 """
334 if self.options.lkgm or self.build_config['use_lkgm']:
335 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
336 else:
337 sync_stage = self._GetStageInstance(stages.SyncStage)
338
339 return sync_stage
340
David James58e0c092012-03-04 20:31:12 -0800341 def _RunBackgroundStagesForBoard(self, board):
342 """Run background board-specific stages for the specified board."""
David James58e0c092012-03-04 20:31:12 -0800343 archive_stage = self.archive_stages[board]
David James944a48e2012-03-07 12:19:03 -0800344 configs = self.build_config['board_specific_configs']
345 config = configs.get(board, self.build_config)
346 stage_list = [[stages.VMTestStage, board, archive_stage],
347 [stages.ChromeTestStage, board, archive_stage],
348 [stages.UnitTestStage, board],
349 [stages.UploadPrebuiltsStage, board]]
Brian Harring3fec5a82012-03-01 05:57:03 -0800350
David James58e0c092012-03-04 20:31:12 -0800351 # We can not run hw tests without archiving the payloads.
352 if self.options.archive:
David James944a48e2012-03-07 12:19:03 -0800353 for suite in config['hw_tests']:
354 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800355
David James944a48e2012-03-07 12:19:03 -0800356 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
357 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800358
359 def RunStages(self):
360 """Runs through build process."""
361 self._RunStage(stages.BuildBoardStage)
362
363 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800364 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
365 self._RunStage(stages.SDKTestStage)
366 self._RunStage(stages.UploadPrebuiltsStage,
367 constants.CHROOT_BUILDER_BOARD)
368 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
369 self._RunStage(stages.RefreshPackageStatusStage)
370 else:
371 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800372
David James944a48e2012-03-07 12:19:03 -0800373 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800374 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800375 config = configs.get(board, self.build_config)
376 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
377 config=config)
David James58e0c092012-03-04 20:31:12 -0800378 self.archive_stages[board] = archive_stage
379
David James944a48e2012-03-07 12:19:03 -0800380 # Set up a process pool to run test/archive stages in the background.
381 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800382 queue = multiprocessing.Queue()
383 task = self._RunBackgroundStagesForBoard
384 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800385 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800386 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800387 archive_stage = self.archive_stages[board]
388 config = configs.get(board, self.build_config)
389 self._RunStage(stages.BuildTargetStage, board, archive_stage,
390 config=config)
David James58e0c092012-03-04 20:31:12 -0800391 self.archive_urls[board] = archive_stage.GetDownloadUrl()
392
David James944a48e2012-03-07 12:19:03 -0800393 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800394 queue.put([board])
395
Brian Harring3fec5a82012-03-01 05:57:03 -0800396
397class DistributedBuilder(SimpleBuilder):
398 """Build class that has special logic to handle distributed builds.
399
400 These builds sync using git/manifest logic in manifest_versions. In general
401 they use a non-distributed builder code for the bulk of the work.
402 """
David James944a48e2012-03-07 12:19:03 -0800403 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800404 """Initializes a buildbot builder.
405
406 Extra variables:
407 completion_stage_class: Stage used to complete a build. Set in the Sync
408 stage.
409 """
David James944a48e2012-03-07 12:19:03 -0800410 super(DistributedBuilder, self).__init__(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800411 self.completion_stage_class = None
412
413 def GetSyncInstance(self):
414 """Syncs the tree using one of the distributed sync logic paths.
415
416 Returns: the instance of the sync stage that was run.
417 """
418 # Determine sync class to use. CQ overrides PFQ bits so should check it
419 # first.
420 if cbuildbot_config.IsCQType(self.build_config['build_type']):
421 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
422 self.completion_stage_class = stages.CommitQueueCompletionStage
423 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
424 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
425 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
426 else:
427 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
428 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
429
430 return sync_stage
431
432 def Publish(self, was_build_successful):
433 """Completes build by publishing any required information."""
434 completion_stage = self._GetStageInstance(self.completion_stage_class,
435 was_build_successful)
436 completion_stage.Run()
437 name = completion_stage.name
438 if not results_lib.Results.WasStageSuccessful(name):
439 should_publish_changes = False
440 else:
441 should_publish_changes = (self.build_config['master'] and
442 was_build_successful)
443
444 if should_publish_changes:
445 self._RunStage(stages.PublishUprevChangesStage)
446
447 def RunStages(self):
448 """Runs simple builder logic and publishes information to overlays."""
449 was_build_successful = False
450 try:
David Jamesf55709e2012-03-13 09:10:15 -0700451 super(DistributedBuilder, self).RunStages()
452 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800453 except SystemExit as ex:
454 # If a stage calls sys.exit(0), it's exiting with success, so that means
455 # we should mark ourselves as successful.
456 if ex.code == 0:
457 was_build_successful = True
458 raise
459 finally:
460 self.Publish(was_build_successful)
461
Brian Harring3fec5a82012-03-01 05:57:03 -0800462
463def _ConfirmBuildRoot(buildroot):
464 """Confirm with user the inferred buildroot, and mark it as confirmed."""
465 warning = 'Using default directory %s as buildroot' % buildroot
466 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
467 full=True)
468 if response == cros_lib.NO:
469 print('Please specify a buildroot with the --buildroot option.')
470 sys.exit(0)
471
472 if not os.path.exists(buildroot):
473 os.mkdir(buildroot)
474
475 repository.CreateTrybotMarker(buildroot)
476
477
478def _DetermineDefaultBuildRoot(internal_build):
479 """Default buildroot to be under the directory that contains current checkout.
480
481 Arguments:
482 internal_build: Whether the build is an internal build
483 """
484 repo_dir = cros_lib.FindRepoDir()
485 if not repo_dir:
486 cros_lib.Die('Could not find root of local checkout. Please specify'
487 'using --buildroot option.')
488
489 # Place trybot buildroot under the directory containing current checkout.
490 top_level = os.path.dirname(os.path.realpath(os.path.dirname(repo_dir)))
491 if internal_build:
492 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
493 else:
494 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
495
496 return buildroot
497
498
499def _BackupPreviousLog(log_file, backup_limit=25):
500 """Rename previous log.
501
502 Args:
503 log_file: The absolute path to the previous log.
504 """
505 if os.path.exists(log_file):
506 old_logs = sorted(glob.glob(log_file + '.*'),
507 key=distutils.version.LooseVersion)
508
509 if len(old_logs) >= backup_limit:
510 os.remove(old_logs[0])
511
512 last = 0
513 if old_logs:
514 last = int(old_logs.pop().rpartition('.')[2])
515
516 os.rename(log_file, log_file + '.' + str(last + 1))
517
518
David James944a48e2012-03-07 12:19:03 -0800519def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800520 """Helper function that wraps RunBuildStages()."""
521 def IsDistributedBuilder():
522 """Determines whether the build_config should be a DistributedBuilder."""
523 if not options.buildbot:
524 return False
525 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
526 chrome_rev = build_config['chrome_rev']
527 if options.chrome_rev: chrome_rev = options.chrome_rev
528 # We don't do distributed logic to TOT Chrome PFQ's, nor local
529 # chrome roots (e.g. chrome try bots)
530 if chrome_rev not in [constants.CHROME_REV_TOT,
531 constants.CHROME_REV_LOCAL,
532 constants.CHROME_REV_SPEC]:
533 return True
534
535 return False
536
537 # Start tee-ing output to file.
538 log_file = None
539 if options.tee:
540 default_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
541 dirname = options.log_dir or default_dir
542 log_file = os.path.join(dirname, _BUILDBOT_LOG_FILE)
543
544 cros_lib.SafeMakedirs(dirname)
545 _BackupPreviousLog(log_file)
546
547 try:
548 with cros_lib.AllowDisabling(options.tee, tee.Tee, log_file):
549 cros_lib.Info("cbuildbot executed with args %s"
550 % ' '.join(map(repr, sys.argv)))
551 if IsDistributedBuilder():
David James944a48e2012-03-07 12:19:03 -0800552 buildbot = DistributedBuilder(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800553 else:
David James944a48e2012-03-07 12:19:03 -0800554 buildbot = SimpleBuilder(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800555
556 if not buildbot.Run():
557 sys.exit(1)
558 finally:
559 if options.tee:
560 cros_lib.Info('Output should be saved to %s' % log_file)
561
562
563# Parser related functions
Ryan Cuicedd8a52012-03-22 02:28:35 -0700564def _CheckLocalPatches(local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800565 """Do an early quick check of the passed-in patches.
566
567 If the branch of a project is not specified we append the current branch the
568 project is on.
569 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700570 verified_patches = []
571 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800572 components = patch.split(':')
573 if len(components) > 2:
574 msg = 'Specify local patches in project[:branch] format.'
575 raise optparse.OptionValueError(msg)
576
577 # validate project
578 project = components[0]
579 if not cros_lib.DoesProjectExist('.', project):
580 raise optparse.OptionValueError('Project %s does not exist.' % project)
581
582 project_dir = cros_lib.GetProjectDir('.', project)
583
584 # If no branch was specified, we use the project's current branch.
585 if len(components) == 1:
586 branch = cros_lib.GetCurrentBranch(project_dir)
587 if not branch:
588 raise optparse.OptionValueError('project %s is not on a branch!'
589 % project)
590 # Append branch information to patch
591 patch = '%s:%s' % (project, branch)
592 else:
593 branch = components[1]
594 if not cros_lib.DoesLocalBranchExist(project_dir, branch):
595 raise optparse.OptionValueError('Project %s does not have branch %s'
596 % (project, branch))
597
Ryan Cuicedd8a52012-03-22 02:28:35 -0700598 verified_patches.append(patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800599
Ryan Cuicedd8a52012-03-22 02:28:35 -0700600 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800601
602
603def _CheckBuildRootOption(_option, _opt_str, value, parser):
604 """Validate and convert buildroot to full-path form."""
605 value = value.strip()
606 if not value or value == '/':
607 raise optparse.OptionValueError('Invalid buildroot specified')
608
609 parser.values.buildroot = os.path.realpath(os.path.expanduser(value))
610
611
612def _CheckLogDirOption(_option, _opt_str, value, parser):
613 """Validate and convert buildroot to full-path form."""
614 parser.values.log_dir = os.path.abspath(os.path.expanduser(value))
615
616
617def _CheckChromeVersionOption(_option, _opt_str, value, parser):
618 """Upgrade other options based on chrome_version being passed."""
619 value = value.strip()
620
621 if parser.values.chrome_rev is None and value:
622 parser.values.chrome_rev = constants.CHROME_REV_SPEC
623
624 parser.values.chrome_version = value
625
626
627def _CheckChromeRootOption(_option, _opt_str, value, parser):
628 """Validate and convert chrome_root to full-path form."""
629 value = value.strip()
630 if not value or value == '/':
631 raise optparse.OptionValueError('Invalid chrome_root specified')
632
633 if parser.values.chrome_rev is None:
634 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
635
636 parser.values.chrome_root = os.path.realpath(os.path.expanduser(value))
637
638
639def _CheckChromeRevOption(_option, _opt_str, value, parser):
640 """Validate the chrome_rev option."""
641 value = value.strip()
642 if value not in constants.VALID_CHROME_REVISIONS:
643 raise optparse.OptionValueError('Invalid chrome rev specified')
644
645 parser.values.chrome_rev = value
646
647
648def _CreateParser():
649 """Generate and return the parser with all the options."""
650 # Parse options
651 usage = "usage: %prog [options] buildbot_config"
652 parser = optparse.OptionParser(usage=usage)
653
654 # Main options
655 parser.add_option('-a', '--all', action='store_true', dest='print_all',
656 default=False,
657 help=('List all of the buildbot configs available. Use '
658 'with the --list option'))
659 parser.add_option('-r', '--buildroot', action='callback', dest='buildroot',
660 type='string', callback=_CheckBuildRootOption,
661 help=('Root directory where source is checked out to, and '
662 'where the build occurs. For external build configs, '
663 "defaults to 'trybot' directory at top level of your "
664 'repo-managed checkout.'))
665 parser.add_option('--chrome_rev', default=None, type='string',
666 action='callback', dest='chrome_rev',
667 callback=_CheckChromeRevOption,
668 help=('Revision of Chrome to use, of type '
669 '[%s]' % '|'.join(constants.VALID_CHROME_REVISIONS)))
Ryan Cuicedd8a52012-03-22 02:28:35 -0700670 parser.add_option('-g', '--gerrit-patches', action='append', default=[],
671 type='string', metavar="'Id1 *int_Id2...IdN'",
Brian Harring3fec5a82012-03-01 05:57:03 -0800672 help=("Space-separated list of short-form Gerrit "
673 "Change-Id's or change numbers to patch. Please "
674 "prepend '*' to internal Change-Id's"))
675 parser.add_option('-l', '--list', action='store_true', dest='list',
676 default=False,
677 help=('List the suggested trybot configs to use. Use '
678 '--all to list all of the available configs.'))
Ryan Cuicedd8a52012-03-22 02:28:35 -0700679 parser.add_option('-p', '--local-patches', action='append', default=[],
Brian Harring3fec5a82012-03-01 05:57:03 -0800680 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
681 help=('Space-separated list of project branches with '
682 'patches to apply. Projects are specified by name. '
683 'If no branch is specified the current branch of the '
684 'project will be used.'))
685 parser.add_option('--profile', default=None, type='string', action='store',
686 dest='profile',
687 help=('Name of profile to sub-specify board variant.'))
688 parser.add_option('--remote', default=False, action='store_true',
Brian Harring3fec5a82012-03-01 05:57:03 -0800689 help=('Specifies that this tryjob should be run remotely.'))
690
691 # Advanced options
692 group = optparse.OptionGroup(
693 parser,
694 'Advanced Options',
695 'Caution: use these options at your own risk.')
696
697 group.add_option('--buildbot', dest='buildbot', action='store_true',
698 default=False, help='This is running on a buildbot')
699 group.add_option('--buildnumber',
700 help='build number', type='int', default=0)
701 group.add_option('--chrome_root', default=None, type='string',
702 action='callback', dest='chrome_root',
703 callback=_CheckChromeRootOption,
704 help='Local checkout of Chrome to use.')
705 group.add_option('--chrome_version', default=None, type='string',
706 action='callback', dest='chrome_version',
707 callback=_CheckChromeVersionOption,
708 help='Used with SPEC logic to force a particular SVN '
709 'revision of chrome rather than the latest.')
710 group.add_option('--clobber', action='store_true', dest='clobber',
711 default=False,
712 help='Clears an old checkout before syncing')
713 group.add_option('--lkgm', action='store_true', dest='lkgm', default=False,
714 help='Sync to last known good manifest blessed by PFQ')
715 parser.add_option('--log_dir', action='callback', dest='log_dir',
716 type='string', callback=_CheckLogDirOption,
717 help=('Directory where logs are stored.'))
718 group.add_option('--maxarchives', dest='max_archive_builds',
719 default=3, type='int',
720 help="Change the local saved build count limit.")
721 group.add_option('--noarchive', action='store_false', dest='archive',
722 default=True,
723 help="Don't run archive stage.")
724 group.add_option('--nobuild', action='store_false', dest='build',
725 default=True,
726 help="Don't actually build (for cbuildbot dev")
727 group.add_option('--noclean', action='store_false', dest='clean',
728 default=True,
729 help="Don't clean the buildroot")
730 group.add_option('--noprebuilts', action='store_false', dest='prebuilts',
731 default=True,
732 help="Don't upload prebuilts.")
733 group.add_option('--nosync', action='store_false', dest='sync',
734 default=True,
735 help="Don't sync before building.")
736 group.add_option('--nocgroups', action='store_false', dest='cgroups',
737 default=True,
738 help='Disable cbuildbots usage of cgroups.')
Ryan Cuiadd49122012-03-21 22:19:58 -0700739 group.add_option('--notests', action='store_false', dest='tests',
740 default=True,
741 help='Override values from buildconfig and run no tests.')
742 group.add_option('--nouprev', action='store_false', dest='uprev',
743 default=True,
744 help='Override values from buildconfig and never uprev.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800745 group.add_option('--reference-repo', action='store', default=None,
746 dest='reference_repo',
747 help='Reuse git data stored in an existing repo '
748 'checkout. This can drastically reduce the network '
749 'time spent setting up the trybot checkout. By '
750 "default, if this option isn't given but cbuildbot "
751 'is invoked from a repo checkout, cbuildbot will '
752 'use the repo root.')
Ryan Cuicedd8a52012-03-22 02:28:35 -0700753 # Indicates this is running on a remote trybot machine. '
Ryan Cuiba41ad32012-03-08 17:15:29 -0800754 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
Ryan Cuicedd8a52012-03-22 02:28:35 -0700755 default=False, help=optparse.SUPPRESS_HELP)
756 # Patches uploaded by trybot client when run using the -p option.
757 group.add_option('--remote-patches', action='append', default=[],
758 help=optparse.SUPPRESS_HELP)
759 group.add_option('--resume', action='store_true', default=False,
Ryan Cuiadd49122012-03-21 22:19:58 -0700760 help='Skip stages already successfully completed.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800761 group.add_option('--timeout', action='store', type='int', default=0,
762 help="Specify the maximum amount of time this job can run "
763 "for, at which point the build will be aborted. If "
764 "set to zero, then there is no timeout")
Brian Harring3fec5a82012-03-01 05:57:03 -0800765 group.add_option('--validation_pool', default=None,
766 help='Path to a pickled validation pool. Intended for use '
767 'only with the commit queue.')
768 group.add_option('--version', dest='force_version', default=None,
769 help='Used with manifest logic. Forces use of this version '
770 'rather than create or get latest.')
771
772 parser.add_option_group(group)
773
774 # Debug options
775 group = optparse.OptionGroup(parser, "Debug Options")
776
Ryan Cui85867972012-02-23 18:21:49 -0800777 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800778 help='Override some options to run as a developer.')
779 group.add_option('--dump_config', action='store_true', dest='dump_config',
780 default=False,
781 help='Dump out build config options, and exit.')
782 group.add_option('--notee', action='store_false', dest='tee', default=True,
783 help="Disable logging and internal tee process. Primarily "
784 "used for debugging cbuildbot itself.")
785 parser.add_option_group(group)
786 return parser
787
788
Ryan Cui85867972012-02-23 18:21:49 -0800789def _FinishParsing(options, args):
790 """Perform some parsing tasks that need to take place after optparse.
791
792 This function needs to be easily testable! Keep it free of
793 environment-dependent code. Put more detailed usage validation in
794 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800795
796 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800797 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800798 """
Brian Harring3fec5a82012-03-01 05:57:03 -0800799 if options.chrome_root:
800 if options.chrome_rev != constants.CHROME_REV_LOCAL:
801 cros_lib.Die('Chrome rev must be %s if chrome_root is set.' %
802 constants.CHROME_REV_LOCAL)
803 else:
804 if options.chrome_rev == constants.CHROME_REV_LOCAL:
805 cros_lib.Die('Chrome root must be set if chrome_rev is %s.' %
806 constants.CHROME_REV_LOCAL)
807
808 if options.chrome_version:
809 if options.chrome_rev != constants.CHROME_REV_SPEC:
810 cros_lib.Die('Chrome rev must be %s if chrome_version is set.' %
811 constants.CHROME_REV_SPEC)
812 else:
813 if options.chrome_rev == constants.CHROME_REV_SPEC:
814 cros_lib.Die('Chrome rev must not be %s if chrome_version is not set.' %
815 constants.CHROME_REV_SPEC)
816
Ryan Cuicedd8a52012-03-22 02:28:35 -0700817 if options.remote and not (options.gerrit_patches or options.local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800818 cros_lib.Die('Must provide patches when running with --remote.')
819
820 if len(args) > 1 and not options.remote:
821 cros_lib.Die('Multiple configs not supported if not running with --remote.')
822
Ryan Cuiba41ad32012-03-08 17:15:29 -0800823 if options.buildbot and options.remote_trybot:
824 cros_lib.Die('--buildbot and --remote-trybot cannot be used together.')
825
Ryan Cui85867972012-02-23 18:21:49 -0800826 # Record whether --debug was set explicitly vs. it was inferred.
827 options.debug_forced = False
828 if options.debug:
829 options.debug_forced = True
830 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800831 # We don't set debug by default for
832 # 1. --buildbot invocations.
833 # 2. --remote invocations, because it needs to push changes to the tryjob
834 # repo.
835 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -0800836
Brian Harring3fec5a82012-03-01 05:57:03 -0800837
Ryan Cuicedd8a52012-03-22 02:28:35 -0700838def _SplitAndFlatten(appended_items):
839 """Given a list of space-separated items, split into flattened list.
840
841 Given ['abc def', 'hij'] return ['abc', 'def', 'hij'].
842 Arguments:
843 appended_items: List of delimiter-separated items.
844
845 Returns: Flattened list.
846 """
847 new_list = []
848 for item in appended_items:
Mike Frysinger4bd23892012-03-26 15:08:52 -0400849 new_list.extend(item.split())
Ryan Cuicedd8a52012-03-22 02:28:35 -0700850 return new_list
851
852
Ryan Cui85867972012-02-23 18:21:49 -0800853def _PostParseCheck(options, args):
854 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800855
Ryan Cui85867972012-02-23 18:21:49 -0800856 Args:
857 options/args: The options/args object returned by optparse
858 """
859 if not options.resume:
Ryan Cuicedd8a52012-03-22 02:28:35 -0700860 options.gerrit_patches = _SplitAndFlatten(options.gerrit_patches)
861 options.remote_patches = _SplitAndFlatten(options.remote_patches)
Ryan Cui85867972012-02-23 18:21:49 -0800862 try:
863 # TODO(rcui): Split this into two stages, one that parses, another that
864 # validates. Parsing step will be called by _FinishParsing().
Ryan Cuicedd8a52012-03-22 02:28:35 -0700865 options.local_patches = _CheckLocalPatches(
866 _SplitAndFlatten(options.local_patches))
Ryan Cui85867972012-02-23 18:21:49 -0800867 except optparse.OptionValueError as e:
868 cros_lib.Die(str(e))
869
870
871def _ParseCommandLine(parser, argv):
872 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800873 (options, args) = parser.parse_args(argv)
874 # Strip out null arguments.
875 # TODO(rcui): Remove when buildbot is fixed
876 args = [arg for arg in args if arg]
Ryan Cui85867972012-02-23 18:21:49 -0800877 _FinishParsing(options, args)
878 return options, args
879
880
881def main(argv):
882 # Set umask to 022 so files created by buildbot are readable.
883 os.umask(022)
884
885 if cros_lib.IsInsideChroot():
886 cros_lib.Die('Please run cbuildbot from outside the chroot.')
887
888 parser = _CreateParser()
889 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -0800890
891 if options.list:
892 _PrintValidConfigs(not options.print_all)
893 sys.exit(0)
894
895 _PostParseCheck(options, args)
896
897 if options.remote:
Ryan Cui16ca5812012-03-08 20:34:27 -0800898 cros_lib.DebugLevel.SetDebugLevel(cros_lib.DebugLevel.WARNING)
899
Brian Harring3fec5a82012-03-01 05:57:03 -0800900 # Verify configs are valid.
901 for bot in args:
902 _GetConfig(bot)
903
904 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -0800905 print 'Verifying patches...'
Ryan Cuicedd8a52012-03-22 02:28:35 -0700906 _, local_patches = _PreProcessPatches(options.gerrit_patches,
907 options.local_patches)
Ryan Cui16ca5812012-03-08 20:34:27 -0800908 print 'Submitting tryjob...'
Ryan Cuicedd8a52012-03-22 02:28:35 -0700909 tryjob = remote_try.RemoteTryJob(options, args, local_patches)
Ryan Cui16ca5812012-03-08 20:34:27 -0800910 tryjob.Submit(dryrun=options.debug)
911 print 'Tryjob submitted!'
912 print ('Go to %s to view the status of your job.'
913 % tryjob.GetTrybotConsoleLink())
Brian Harring3fec5a82012-03-01 05:57:03 -0800914 sys.exit(0)
915
916 if args:
917 # Only expecting one config
918 bot_id = args[-1]
919 build_config = _GetConfig(bot_id)
920 else:
921 parser.error('Invalid usage. Use -h to see usage.')
922
923 if options.reference_repo is None:
924 repo_path = os.path.join(constants.SOURCE_ROOT, '.repo')
925 # If we're being run from a repo checkout, reuse the repo's git pool to
926 # cut down on sync time.
927 if os.path.exists(repo_path):
928 options.reference_repo = constants.SOURCE_ROOT
929 elif options.reference_repo:
930 if not os.path.exists(options.reference_repo):
931 parser.error('Reference path %s does not exist'
932 % (options.reference_repo,))
933 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
934 parser.error('Reference path %s does not look to be the base of a '
935 'repo checkout; no .repo exists in the root.'
936 % (options.reference_repo,))
Brian Harring470f6112012-03-02 11:47:10 -0800937 if options.buildbot:
938 if not options.cgroups:
939 parser.error('Options --buildbot and --nocgroups cannot be used '
940 'together. Cgroup support is required for buildbot mode.')
941 if not cgroups.Cgroup.CgroupsSupported():
942 parser.error('Option --buildbot was given, but this system does not '
943 'support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800944
Brian Harring351ce442012-03-09 16:38:14 -0800945 missing = []
946 for program in _BUILDBOT_REQUIRED_BINARIES:
947 ret = cros_lib.RunCommand('which %s' % program, shell=True,
948 redirect_stderr=True, redirect_stdout=True,
949 error_code_ok=True, print_cmd=False)
950 if ret.returncode != 0:
951 missing.append(program)
952
953 if missing:
954 parser.error("Option --buildbot requires the following binaries which "
955 "couldn't be found in $PATH: %s"
956 % (', '.join(missing)))
957
Brian Harring3fec5a82012-03-01 05:57:03 -0800958 if options.reference_repo:
959 options.reference_repo = os.path.abspath(options.reference_repo)
960
961 if options.dump_config:
962 # This works, but option ordering is bad...
963 print 'Configuration %s:' % bot_id
964 pretty_printer = pprint.PrettyPrinter(indent=2)
965 pretty_printer.pprint(build_config)
966 sys.exit(0)
967
968 if not options.buildroot:
969 if options.buildbot:
970 parser.error('Please specify a buildroot with the --buildroot option.')
Brian Harring470f6112012-03-02 11:47:10 -0800971 options.buildroot = _DetermineDefaultBuildRoot(build_config['internal'])
972 # We use a marker file in the buildroot to indicate the user has
973 # consented to using this directory.
974 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
975 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800976
977 # Sanity check of buildroot- specifically that it's not pointing into the
978 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -0800979 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -0800980 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -0800981 parser.error('Configured buildroot %s points into a repository checkout, '
982 'rather than the root of it. This is not supported.'
983 % options.buildroot)
984
Brian Harringa184efa2012-03-04 11:51:25 -0800985 with cleanup.EnforcedCleanupSection() as critical_section:
986 with sudo.SudoKeepAlive():
987 with cros_lib.AllowDisabling(options.cgroups,
Brian Harring4e6412d2012-03-09 20:54:02 -0800988 cgroups.SimpleContainChildren, 'cbuildbot'):
Brian Harringa184efa2012-03-04 11:51:25 -0800989 # Mark everything between EnforcedCleanupSection and here as having to
990 # be rolled back via the contextmanager cleanup handlers. This ensures
991 # that sudo bits cannot outlive cbuildbot, that anything cgroups
992 # would kill gets killed, etc.
993 critical_section.ForkWatchdog()
994
995 with cros_lib.AllowDisabling(options.timeout > 0,
996 cros_lib.Timeout, options.timeout):
997 if not options.buildbot:
998 build_config = cbuildbot_config.OverrideConfigForTrybot(
Ryan Cui3d6b4742012-03-14 11:42:24 -0700999 build_config,
1000 options.remote_trybot)
Brian Harringa184efa2012-03-04 11:51:25 -08001001
1002 _RunBuildStagesWrapper(options, build_config)