blob: 9deaa0580e6d13aa6a19944accde8b565d1d670b [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
15import optparse
16import os
17import pprint
18import sys
19
20from chromite.buildbot import builderstage as bs
21from chromite.buildbot import cbuildbot_background as background
22from chromite.buildbot import cbuildbot_config
23from chromite.buildbot import cbuildbot_stages as stages
24from chromite.buildbot import cbuildbot_results as results_lib
Brian Harringde588b52012-02-17 19:31:44 -080025from chromite.buildbot import cgroup as cgroups
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
33from chromite.lib import cros_build_lib as cros_lib
34from chromite.lib import sudo
35
36cros_lib.STRICT_SUDO = True
37
38_DEFAULT_LOG_DIR = 'cbuildbot_logs'
39_BUILDBOT_LOG_FILE = 'cbuildbot.log'
40_DEFAULT_EXT_BUILDROOT = 'trybot'
41_DEFAULT_INT_BUILDROOT = 'trybot-internal'
42_PATH_TO_CBUILDBOT = 'chromite/bin/cbuildbot'
43_DISTRIBUTED_TYPES = [constants.COMMIT_QUEUE_TYPE, constants.PFQ_TYPE,
44 constants.CANARY_TYPE, constants.CHROME_PFQ_TYPE,
45 constants.PALADIN_TYPE]
46
47
48def _PrintValidConfigs(trybot_only=True):
49 """Print a list of valid buildbot configs.
50
51 Arguments:
52 trybot_only: Only print selected trybot configs, as specified by the
53 'trybot_list' config setting.
54 """
55 COLUMN_WIDTH = 45
56 print 'config'.ljust(COLUMN_WIDTH), 'description'
57 print '------'.ljust(COLUMN_WIDTH), '-----------'
58 config_names = cbuildbot_config.config.keys()
59 config_names.sort()
60 for name in config_names:
61 if not trybot_only or cbuildbot_config.config[name]['trybot_list']:
62 desc = ''
63 if cbuildbot_config.config[name]['description']:
64 desc = cbuildbot_config.config[name]['description']
65
66 print name.ljust(COLUMN_WIDTH), desc
67
68
69def _GetConfig(config_name):
70 """Gets the configuration for the build"""
71 if not cbuildbot_config.config.has_key(config_name):
72 print 'Non-existent configuration %s specified.' % config_name
73 print 'Please specify one of:'
74 _PrintValidConfigs()
75 sys.exit(1)
76
77 result = cbuildbot_config.config[config_name]
78
79 return result
80
81
82def _GetChromiteTrackingBranch():
83 """Returns the current Chromite tracking_branch.
84
85 If Chromite is on a detached HEAD, we assume it's the manifest branch.
86 """
87 cwd = os.path.dirname(os.path.realpath(__file__))
88 current_branch = cros_lib.GetCurrentBranch(cwd)
89 if current_branch:
90 (_, tracking_branch) = cros_lib.GetPushBranch(current_branch, cwd)
91 else:
92 tracking_branch = cros_lib.GetManifestDefaultBranch(cwd)
93
94 return tracking_branch
95
96
97def _CheckBuildRootBranch(buildroot, tracking_branch):
98 """Make sure buildroot branch is the same as Chromite branch."""
99 manifest_branch = cros_lib.GetManifestDefaultBranch(buildroot)
100 if manifest_branch != tracking_branch:
101 cros_lib.Die('Chromite is not on same branch as buildroot checkout\n' +
102 'Chromite is on branch %s.\n' % tracking_branch +
103 'Buildroot checked out to %s\n' % manifest_branch)
104
105
106def _PreProcessPatches(gerrit_patches, local_patches):
107 """Validate patches ASAP to catch user errors. Also generate patch info.
108
109 Args:
110 gerrit_patches: List of gerrit CL ID's passed in by user.
111 local_patches: List of local project branches to generate patches from.
112
113 Returns:
114 A tuple containing a list of cros_patch.GerritPatch and a list of
115 cros_patch.LocalPatch objects.
116 """
117 gerrit_patch_info = []
118 local_patch_info = []
119
120 try:
121 if gerrit_patches:
122 gerrit_patch_info = gerrit_helper.GetGerritPatchInfo(gerrit_patches)
123 for patch in gerrit_patch_info:
124 if patch.IsAlreadyMerged():
125 cros_lib.Warning('Patch %s has already been merged.' % str(patch))
126 except gerrit_helper.GerritException as e:
127 cros_lib.Die(str(e))
128
129 try:
130 if local_patches:
131 local_patch_info = cros_patch.PrepareLocalPatches(
132 local_patches,
133 _GetChromiteTrackingBranch())
134
135 except cros_patch.PatchException as e:
136 cros_lib.Die(str(e))
137
138 return gerrit_patch_info, local_patch_info
139
140
141def _IsIncrementalBuild(buildroot, clobber):
142 """Returns True if we are reusing an existing buildroot."""
143 repo_dir = os.path.join(buildroot, '.repo')
144 return not clobber and os.path.isdir(repo_dir)
145
146
147class Builder(object):
148 """Parent class for all builder types.
149
150 This class functions as a parent class for various build types. It's intended
151 use is builder_instance.Run().
152
153 Vars:
154 bot_id: Name of the build configuration.
155 build_config: The configuration dictionary from cbuildbot_config.
156 options: The options provided from optparse in main().
157 completed_stages_file: Where we store resume state.
158 archive_url: Where our artifacts for this builder will be archived.
159 tracking_branch: The tracking branch for this build.
160 release_tag: The associated "chrome os version" of this build.
161 gerrit_patches: Gerrit patches to be included in build.
162 local_patches: Local patches to be included in build.
163 """
164
165 def __init__(self, bot_id, options, build_config):
166 """Initializes instance variables. Must be called by all subclasses."""
167 self.bot_id = bot_id
168 self.build_config = build_config
169 self.options = options
170
171 # TODO, Remove here and in config after bug chromium-os:14649 is fixed.
172 if self.build_config['chromeos_official']:
173 os.environ['CHROMEOS_OFFICIAL'] = '1'
174
175 self.completed_stages_file = os.path.join(options.buildroot,
176 '.completed_stages')
177 self.archive_urls = {}
178 self.release_tag = None
179 self.tracking_branch = _GetChromiteTrackingBranch()
180 self.gerrit_patches = None
181 self.local_patches = None
182
183 def Initialize(self):
184 """Runs through the initialization steps of an actual build."""
185 if self.options.resume and os.path.exists(self.completed_stages_file):
186 with open(self.completed_stages_file, 'r') as load_file:
187 results_lib.Results.RestoreCompletedStages(load_file)
188
189 # We only want to do this if we need to patch changes.
190 if not results_lib.Results.GetPrevious().get(
191 self._GetStageInstance(stages.PatchChangesStage, None, None).name):
192 self.gerrit_patches, self.local_patches = _PreProcessPatches(
193 self.options.gerrit_patches, self.options.local_patches)
194
195 bs.BuilderStage.SetTrackingBranch(self.tracking_branch)
196
197 # Check branch matching early.
198 if _IsIncrementalBuild(self.options.buildroot, self.options.clobber):
199 _CheckBuildRootBranch(self.options.buildroot, self.tracking_branch)
200
201 self._RunStage(stages.CleanUpStage)
202
203 def _GetStageInstance(self, stage, *args, **kwargs):
204 """Helper function to get an instance given the args.
205
206 Useful as almost all stages just take in bot_id, options, and build_config.
207 """
208 return stage(self.bot_id, self.options, self.build_config, *args, **kwargs)
209
210 def _SetReleaseTag(self):
211 """Sets the release tag from the manifest_manager.
212
213 Must be run after sync stage as syncing enables us to have a release tag.
214 """
215 # Extract version we have decided to build into self.release_tag.
216 manifest_manager = stages.ManifestVersionedSyncStage.manifest_manager
217 if manifest_manager:
218 self.release_tag = manifest_manager.current_version
219
220 def _RunStage(self, stage, *args, **kwargs):
221 """Wrapper to run a stage."""
222 stage_instance = self._GetStageInstance(stage, *args, **kwargs)
223 return stage_instance.Run()
224
225 def GetSyncInstance(self):
226 """Returns an instance of a SyncStage that should be run.
227
228 Subclasses must override this method.
229 """
230 raise NotImplementedError()
231
232 def RunStages(self):
233 """Subclasses must override this method. Runs the appropriate code."""
234 raise NotImplementedError()
235
236 def _WriteCheckpoint(self):
237 """Drops a completed stages file with current state."""
238 with open(self.completed_stages_file, 'w+') as save_file:
239 results_lib.Results.SaveCompletedStages(save_file)
240
241 def _ShouldReExecuteInBuildRoot(self):
242 """Returns True if this build should be re-executed in the buildroot."""
243 abs_buildroot = os.path.abspath(self.options.buildroot)
244 return not os.path.abspath(__file__).startswith(abs_buildroot)
245
246 def _ReExecuteInBuildroot(self, sync_instance):
247 """Reexecutes self in buildroot and returns True if build succeeds.
248
249 This allows the buildbot code to test itself when changes are patched for
250 buildbot-related code. This is a no-op if the buildroot == buildroot
251 of the running chromite checkout.
252
253 Args:
254 sync_instance: Instance of the sync stage that was run to sync.
255
256 Returns:
257 True if the Build succeeded.
258 """
259 # If we are resuming, use last checkpoint.
260 if not self.options.resume:
261 self._WriteCheckpoint()
262
263 # Re-write paths to use absolute paths.
264 # Suppress any timeout options given from the commandline in the
265 # invoked cbuildbot; our timeout will enforce it instead.
266 args_to_append = ['--resume', '--timeout', '0', '--buildroot',
267 os.path.abspath(self.options.buildroot)]
268
269 if self.options.chrome_root:
270 args_to_append += ['--chrome_root',
271 os.path.abspath(self.options.chrome_root)]
272
273 if stages.ManifestVersionedSyncStage.manifest_manager:
274 ver = stages.ManifestVersionedSyncStage.manifest_manager.current_version
275 args_to_append += ['--version', ver]
276
277 if isinstance(sync_instance, stages.CommitQueueSyncStage):
278 vp_file = sync_instance.SaveValidationPool()
279 args_to_append += ['--validation_pool', vp_file]
280
281 # Re-run the command in the buildroot.
282 # Finally, be generous and give the invoked cbuildbot 30s to shutdown
283 # when something occurs. It should exit quicker, but the sigterm may
284 # hit while the system is particularly busy.
285 return_obj = cros_lib.RunCommand(
286 [_PATH_TO_CBUILDBOT] + sys.argv[1:] + args_to_append,
287 cwd=self.options.buildroot, error_code_ok=True, kill_timeout=30)
288 return return_obj.returncode == 0
289
290 def Run(self):
291 """Main runner for this builder class. Runs build and prints summary."""
292 print_report = True
293 success = True
294 try:
295 self.Initialize()
296 sync_instance = self.GetSyncInstance()
297 sync_instance.Run()
298 self._SetReleaseTag()
299
300 if self.gerrit_patches or self.local_patches:
301 self._RunStage(stages.PatchChangesStage,
302 self.gerrit_patches, self.local_patches)
303
304 if self._ShouldReExecuteInBuildRoot():
305 print_report = False
306 success = self._ReExecuteInBuildroot(sync_instance)
307 else:
308 self.RunStages()
309
310 finally:
311 if print_report:
312 self._WriteCheckpoint()
313 print '\n\n\n@@@BUILD_STEP Report@@@\n'
314 results_lib.Results.Report(sys.stdout, self.archive_urls,
315 self.release_tag)
316 success = results_lib.Results.BuildSucceededSoFar()
317
318 return success
319
320
321class SimpleBuilder(Builder):
322 """Builder that performs basic vetting operations."""
323
324 def GetSyncInstance(self):
325 """Sync to lkgm or TOT as necessary.
326
327 Returns: the instance of the sync stage that was run.
328 """
329 if self.options.lkgm or self.build_config['use_lkgm']:
330 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
331 else:
332 sync_stage = self._GetStageInstance(stages.SyncStage)
333
334 return sync_stage
335
336 def _RunStagesForBoard(self, board):
337 """Run board-specific stages for the specified board.
338
339 Returns: True if the stages completed successfully.
340 """
341 archive_stage = self._GetStageInstance(stages.ArchiveStage, board)
342 self._RunStage(stages.BuildTargetStage, board, archive_stage)
343
344 bg = background.BackgroundSteps()
345
346 vm_test_stage = self._GetStageInstance(stages.VMTestStage, board,
347 archive_stage)
348 chrome_test_stage = self._GetStageInstance(stages.ChromeTestStage,
349 board, archive_stage)
350 unit_test_stage = self._GetStageInstance(stages.UnitTestStage, board)
351 prebuilts_stage = self._GetStageInstance(stages.UploadPrebuiltsStage,
352 board)
353 self.archive_urls[board] = archive_stage.GetDownloadUrl()
354 try:
355 bg.AddStep(archive_stage.Run)
356 bg.start()
357
358 steps = []
359 if self.build_config['vm_tests']:
360 steps.append(vm_test_stage.Run)
361 if self.build_config['chrome_tests']:
362 steps.append(chrome_test_stage.Run)
David James62c7dfb2012-03-02 18:08:58 -0800363 if self.options.archive:
364 for suite in self.build_config['hw_tests']:
365 hw_test_stage = self._GetStageInstance(
366 stages.HWTestStage,
367 board,
368 archive_stage=archive_stage,
369 suite=suite)
370 steps.append(hw_test_stage.Run)
Brian Harring3fec5a82012-03-01 05:57:03 -0800371 steps += [unit_test_stage.Run, prebuilts_stage.Run]
372 # Run the steps in parallel. If any exceptions occur, RunParallelSteps
373 # will combine them into a single BackgroundException and throw it.
374 background.RunParallelSteps(steps)
375
376 return True
377
378 # We skipped out of this build block early, so one of the tests we ran in
379 # the background or in parallel must have failed.
380 except background.BackgroundException:
381 return False
382 finally:
383 # Wait for archive stage to finish. Ignore any errors.
384 while not bg.Empty(): bg.WaitForStep()
385 bg.join()
386
387 def RunStages(self):
388 """Runs through build process."""
389 self._RunStage(stages.BuildBoardStage)
390
391 # TODO(sosa): Split these out into classes.
392 success = True
393 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
394 self._RunStage(stages.SDKTestStage)
395 self._RunStage(stages.UploadPrebuiltsStage,
396 constants.CHROOT_BUILDER_BOARD)
397 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
398 self._RunStage(stages.RefreshPackageStatusStage)
399 else:
400 self._RunStage(stages.UprevStage)
401 for board in self.build_config['boards']:
402 if not self._RunStagesForBoard(board):
403 success = False
404
405 return success
406
407
408class DistributedBuilder(SimpleBuilder):
409 """Build class that has special logic to handle distributed builds.
410
411 These builds sync using git/manifest logic in manifest_versions. In general
412 they use a non-distributed builder code for the bulk of the work.
413 """
414 def __init__(self, bot_id, options, build_config):
415 """Initializes a buildbot builder.
416
417 Extra variables:
418 completion_stage_class: Stage used to complete a build. Set in the Sync
419 stage.
420 """
421 super(DistributedBuilder, self).__init__(bot_id, options, build_config)
422 self.completion_stage_class = None
423
424 def GetSyncInstance(self):
425 """Syncs the tree using one of the distributed sync logic paths.
426
427 Returns: the instance of the sync stage that was run.
428 """
429 # Determine sync class to use. CQ overrides PFQ bits so should check it
430 # first.
431 if cbuildbot_config.IsCQType(self.build_config['build_type']):
432 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
433 self.completion_stage_class = stages.CommitQueueCompletionStage
434 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
435 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
436 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
437 else:
438 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
439 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
440
441 return sync_stage
442
443 def Publish(self, was_build_successful):
444 """Completes build by publishing any required information."""
445 completion_stage = self._GetStageInstance(self.completion_stage_class,
446 was_build_successful)
447 completion_stage.Run()
448 name = completion_stage.name
449 if not results_lib.Results.WasStageSuccessful(name):
450 should_publish_changes = False
451 else:
452 should_publish_changes = (self.build_config['master'] and
453 was_build_successful)
454
455 if should_publish_changes:
456 self._RunStage(stages.PublishUprevChangesStage)
457
458 def RunStages(self):
459 """Runs simple builder logic and publishes information to overlays."""
460 was_build_successful = False
461 try:
462 was_build_successful = super(DistributedBuilder, self).RunStages()
463 except SystemExit as ex:
464 # If a stage calls sys.exit(0), it's exiting with success, so that means
465 # we should mark ourselves as successful.
466 if ex.code == 0:
467 was_build_successful = True
468 raise
469 finally:
470 self.Publish(was_build_successful)
471
472 return was_build_successful
473
474
475def _ConfirmBuildRoot(buildroot):
476 """Confirm with user the inferred buildroot, and mark it as confirmed."""
477 warning = 'Using default directory %s as buildroot' % buildroot
478 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
479 full=True)
480 if response == cros_lib.NO:
481 print('Please specify a buildroot with the --buildroot option.')
482 sys.exit(0)
483
484 if not os.path.exists(buildroot):
485 os.mkdir(buildroot)
486
487 repository.CreateTrybotMarker(buildroot)
488
489
490def _DetermineDefaultBuildRoot(internal_build):
491 """Default buildroot to be under the directory that contains current checkout.
492
493 Arguments:
494 internal_build: Whether the build is an internal build
495 """
496 repo_dir = cros_lib.FindRepoDir()
497 if not repo_dir:
498 cros_lib.Die('Could not find root of local checkout. Please specify'
499 'using --buildroot option.')
500
501 # Place trybot buildroot under the directory containing current checkout.
502 top_level = os.path.dirname(os.path.realpath(os.path.dirname(repo_dir)))
503 if internal_build:
504 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
505 else:
506 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
507
508 return buildroot
509
510
511def _BackupPreviousLog(log_file, backup_limit=25):
512 """Rename previous log.
513
514 Args:
515 log_file: The absolute path to the previous log.
516 """
517 if os.path.exists(log_file):
518 old_logs = sorted(glob.glob(log_file + '.*'),
519 key=distutils.version.LooseVersion)
520
521 if len(old_logs) >= backup_limit:
522 os.remove(old_logs[0])
523
524 last = 0
525 if old_logs:
526 last = int(old_logs.pop().rpartition('.')[2])
527
528 os.rename(log_file, log_file + '.' + str(last + 1))
529
530
531def _RunBuildStagesWrapper(bot_id, options, build_config):
532 """Helper function that wraps RunBuildStages()."""
533 def IsDistributedBuilder():
534 """Determines whether the build_config should be a DistributedBuilder."""
535 if not options.buildbot:
536 return False
537 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
538 chrome_rev = build_config['chrome_rev']
539 if options.chrome_rev: chrome_rev = options.chrome_rev
540 # We don't do distributed logic to TOT Chrome PFQ's, nor local
541 # chrome roots (e.g. chrome try bots)
542 if chrome_rev not in [constants.CHROME_REV_TOT,
543 constants.CHROME_REV_LOCAL,
544 constants.CHROME_REV_SPEC]:
545 return True
546
547 return False
548
549 # Start tee-ing output to file.
550 log_file = None
551 if options.tee:
552 default_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
553 dirname = options.log_dir or default_dir
554 log_file = os.path.join(dirname, _BUILDBOT_LOG_FILE)
555
556 cros_lib.SafeMakedirs(dirname)
557 _BackupPreviousLog(log_file)
558
559 try:
560 with cros_lib.AllowDisabling(options.tee, tee.Tee, log_file):
561 cros_lib.Info("cbuildbot executed with args %s"
562 % ' '.join(map(repr, sys.argv)))
563 if IsDistributedBuilder():
564 buildbot = DistributedBuilder(bot_id, options, build_config)
565 else:
566 buildbot = SimpleBuilder(bot_id, options, build_config)
567
568 if not buildbot.Run():
569 sys.exit(1)
570 finally:
571 if options.tee:
572 cros_lib.Info('Output should be saved to %s' % log_file)
573
574
575# Parser related functions
576
577
578def _CheckAndSplitLocalPatches(options):
579 """Do an early quick check of the passed-in patches.
580
581 If the branch of a project is not specified we append the current branch the
582 project is on.
583 """
584 patch_args = options.local_patches.split()
585 options.local_patches = []
586 for patch in patch_args:
587 components = patch.split(':')
588 if len(components) > 2:
589 msg = 'Specify local patches in project[:branch] format.'
590 raise optparse.OptionValueError(msg)
591
592 # validate project
593 project = components[0]
594 if not cros_lib.DoesProjectExist('.', project):
595 raise optparse.OptionValueError('Project %s does not exist.' % project)
596
597 project_dir = cros_lib.GetProjectDir('.', project)
598
599 # If no branch was specified, we use the project's current branch.
600 if len(components) == 1:
601 branch = cros_lib.GetCurrentBranch(project_dir)
602 if not branch:
603 raise optparse.OptionValueError('project %s is not on a branch!'
604 % project)
605 # Append branch information to patch
606 patch = '%s:%s' % (project, branch)
607 else:
608 branch = components[1]
609 if not cros_lib.DoesLocalBranchExist(project_dir, branch):
610 raise optparse.OptionValueError('Project %s does not have branch %s'
611 % (project, branch))
612
613 options.local_patches.append(patch)
614
615
616def _CheckAndSplitGerritPatches(_option, _opt_str, value, parser):
617 """Early quick check of patches and convert them into a list."""
618 parser.values.gerrit_patches = value.split()
619
620
621def _CheckBuildRootOption(_option, _opt_str, value, parser):
622 """Validate and convert buildroot to full-path form."""
623 value = value.strip()
624 if not value or value == '/':
625 raise optparse.OptionValueError('Invalid buildroot specified')
626
627 parser.values.buildroot = os.path.realpath(os.path.expanduser(value))
628
629
630def _CheckLogDirOption(_option, _opt_str, value, parser):
631 """Validate and convert buildroot to full-path form."""
632 parser.values.log_dir = os.path.abspath(os.path.expanduser(value))
633
634
635def _CheckChromeVersionOption(_option, _opt_str, value, parser):
636 """Upgrade other options based on chrome_version being passed."""
637 value = value.strip()
638
639 if parser.values.chrome_rev is None and value:
640 parser.values.chrome_rev = constants.CHROME_REV_SPEC
641
642 parser.values.chrome_version = value
643
644
645def _CheckChromeRootOption(_option, _opt_str, value, parser):
646 """Validate and convert chrome_root to full-path form."""
647 value = value.strip()
648 if not value or value == '/':
649 raise optparse.OptionValueError('Invalid chrome_root specified')
650
651 if parser.values.chrome_rev is None:
652 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
653
654 parser.values.chrome_root = os.path.realpath(os.path.expanduser(value))
655
656
657def _CheckChromeRevOption(_option, _opt_str, value, parser):
658 """Validate the chrome_rev option."""
659 value = value.strip()
660 if value not in constants.VALID_CHROME_REVISIONS:
661 raise optparse.OptionValueError('Invalid chrome rev specified')
662
663 parser.values.chrome_rev = value
664
665
666def _CreateParser():
667 """Generate and return the parser with all the options."""
668 # Parse options
669 usage = "usage: %prog [options] buildbot_config"
670 parser = optparse.OptionParser(usage=usage)
671
672 # Main options
673 parser.add_option('-a', '--all', action='store_true', dest='print_all',
674 default=False,
675 help=('List all of the buildbot configs available. Use '
676 'with the --list option'))
677 parser.add_option('-r', '--buildroot', action='callback', dest='buildroot',
678 type='string', callback=_CheckBuildRootOption,
679 help=('Root directory where source is checked out to, and '
680 'where the build occurs. For external build configs, '
681 "defaults to 'trybot' directory at top level of your "
682 'repo-managed checkout.'))
683 parser.add_option('--chrome_rev', default=None, type='string',
684 action='callback', dest='chrome_rev',
685 callback=_CheckChromeRevOption,
686 help=('Revision of Chrome to use, of type '
687 '[%s]' % '|'.join(constants.VALID_CHROME_REVISIONS)))
688 parser.add_option('-g', '--gerrit-patches', action='callback',
689 type='string', callback=_CheckAndSplitGerritPatches,
690 metavar="'Id1 *int_Id2...IdN'",
691 help=("Space-separated list of short-form Gerrit "
692 "Change-Id's or change numbers to patch. Please "
693 "prepend '*' to internal Change-Id's"))
694 parser.add_option('-l', '--list', action='store_true', dest='list',
695 default=False,
696 help=('List the suggested trybot configs to use. Use '
697 '--all to list all of the available configs.'))
698 parser.add_option('-p', '--local-patches', action='store', type='string',
699 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
700 help=('Space-separated list of project branches with '
701 'patches to apply. Projects are specified by name. '
702 'If no branch is specified the current branch of the '
703 'project will be used.'))
704 parser.add_option('--profile', default=None, type='string', action='store',
705 dest='profile',
706 help=('Name of profile to sub-specify board variant.'))
707 parser.add_option('--remote', default=False, action='store_true',
708 dest='remote',
709 help=('Specifies that this tryjob should be run remotely.'))
710
711 # Advanced options
712 group = optparse.OptionGroup(
713 parser,
714 'Advanced Options',
715 'Caution: use these options at your own risk.')
716
717 group.add_option('--buildbot', dest='buildbot', action='store_true',
718 default=False, help='This is running on a buildbot')
719 group.add_option('--buildnumber',
720 help='build number', type='int', default=0)
721 group.add_option('--chrome_root', default=None, type='string',
722 action='callback', dest='chrome_root',
723 callback=_CheckChromeRootOption,
724 help='Local checkout of Chrome to use.')
725 group.add_option('--chrome_version', default=None, type='string',
726 action='callback', dest='chrome_version',
727 callback=_CheckChromeVersionOption,
728 help='Used with SPEC logic to force a particular SVN '
729 'revision of chrome rather than the latest.')
730 group.add_option('--clobber', action='store_true', dest='clobber',
731 default=False,
732 help='Clears an old checkout before syncing')
733 group.add_option('--lkgm', action='store_true', dest='lkgm', default=False,
734 help='Sync to last known good manifest blessed by PFQ')
735 parser.add_option('--log_dir', action='callback', dest='log_dir',
736 type='string', callback=_CheckLogDirOption,
737 help=('Directory where logs are stored.'))
738 group.add_option('--maxarchives', dest='max_archive_builds',
739 default=3, type='int',
740 help="Change the local saved build count limit.")
741 group.add_option('--noarchive', action='store_false', dest='archive',
742 default=True,
743 help="Don't run archive stage.")
744 group.add_option('--nobuild', action='store_false', dest='build',
745 default=True,
746 help="Don't actually build (for cbuildbot dev")
747 group.add_option('--noclean', action='store_false', dest='clean',
748 default=True,
749 help="Don't clean the buildroot")
750 group.add_option('--noprebuilts', action='store_false', dest='prebuilts',
751 default=True,
752 help="Don't upload prebuilts.")
753 group.add_option('--nosync', action='store_false', dest='sync',
754 default=True,
755 help="Don't sync before building.")
756 group.add_option('--nocgroups', action='store_false', dest='cgroups',
757 default=True,
758 help='Disable cbuildbots usage of cgroups.')
759 group.add_option('--reference-repo', action='store', default=None,
760 dest='reference_repo',
761 help='Reuse git data stored in an existing repo '
762 'checkout. This can drastically reduce the network '
763 'time spent setting up the trybot checkout. By '
764 "default, if this option isn't given but cbuildbot "
765 'is invoked from a repo checkout, cbuildbot will '
766 'use the repo root.')
767 group.add_option('--timeout', action='store', type='int', default=0,
768 help="Specify the maximum amount of time this job can run "
769 "for, at which point the build will be aborted. If "
770 "set to zero, then there is no timeout")
771 group.add_option('--notests', action='store_false', dest='tests',
772 default=True,
773 help='Override values from buildconfig and run no tests.')
774 group.add_option('--nouprev', action='store_false', dest='uprev',
775 default=True,
776 help='Override values from buildconfig and never uprev.')
777 group.add_option('--resume', action='store_true',
778 default=False,
779 help='Skip stages already successfully completed.')
780 group.add_option('--validation_pool', default=None,
781 help='Path to a pickled validation pool. Intended for use '
782 'only with the commit queue.')
783 group.add_option('--version', dest='force_version', default=None,
784 help='Used with manifest logic. Forces use of this version '
785 'rather than create or get latest.')
786
787 parser.add_option_group(group)
788
789 # Debug options
790 group = optparse.OptionGroup(parser, "Debug Options")
791
792 group.add_option('--debug', action='store_true', dest='debug',
793 default=False,
794 help='Override some options to run as a developer.')
795 group.add_option('--dump_config', action='store_true', dest='dump_config',
796 default=False,
797 help='Dump out build config options, and exit.')
798 group.add_option('--notee', action='store_false', dest='tee', default=True,
799 help="Disable logging and internal tee process. Primarily "
800 "used for debugging cbuildbot itself.")
801 parser.add_option_group(group)
802 return parser
803
804
805def _PostParseCheck(options, args):
806 """Perform some usage validation after we've parsed the arguments
807
808 Args:
809 options: The options object returned by optparse
810 """
811 if cros_lib.IsInsideChroot():
812 cros_lib.Die('Please run cbuildbot from outside the chroot.')
813
814 if options.chrome_root:
815 if options.chrome_rev != constants.CHROME_REV_LOCAL:
816 cros_lib.Die('Chrome rev must be %s if chrome_root is set.' %
817 constants.CHROME_REV_LOCAL)
818 else:
819 if options.chrome_rev == constants.CHROME_REV_LOCAL:
820 cros_lib.Die('Chrome root must be set if chrome_rev is %s.' %
821 constants.CHROME_REV_LOCAL)
822
823 if options.chrome_version:
824 if options.chrome_rev != constants.CHROME_REV_SPEC:
825 cros_lib.Die('Chrome rev must be %s if chrome_version is set.' %
826 constants.CHROME_REV_SPEC)
827 else:
828 if options.chrome_rev == constants.CHROME_REV_SPEC:
829 cros_lib.Die('Chrome rev must not be %s if chrome_version is not set.' %
830 constants.CHROME_REV_SPEC)
831
832 if options.remote and options.local_patches:
833 cros_lib.Die('Local patching not yet supported with remote tryjobs.')
834
835 # Set debug correctly. If --debug is set explicitly, always set
836 # options.debug to true, o/w if not buildbot.
837 options.debug = options.debug | (not options.buildbot)
838
839 if not options.resume:
840 try:
841 if options.local_patches:
842 _CheckAndSplitLocalPatches(options)
843
844 except optparse.OptionValueError as e:
845 cros_lib.Die(str(e))
846
847 if options.remote and not options.gerrit_patches:
848 cros_lib.Die('Must provide patches when running with --remote.')
849
850 if len(args) > 1 and not options.remote:
851 cros_lib.Die('Multiple configs not supported if not running with --remote.')
852
853
854def main(argv):
855
856 # Set umask to 022 so files created by buildbot are readable.
857 os.umask(022)
858
859 parser = _CreateParser()
860 (options, args) = parser.parse_args(argv)
861 # Strip out null arguments.
862 # TODO(rcui): Remove when buildbot is fixed
863 args = [arg for arg in args if arg]
864
865 if options.list:
866 _PrintValidConfigs(not options.print_all)
867 sys.exit(0)
868
869 _PostParseCheck(options, args)
870
871 if options.remote:
872 # Verify configs are valid.
873 for bot in args:
874 _GetConfig(bot)
875
876 # Verify gerrit patches are valid.
877 _PreProcessPatches(options.gerrit_patches, options.local_patches)
878
879 remote_try.RemoteTryJob(options, args).Submit()
880 sys.exit(0)
881
882 if args:
883 # Only expecting one config
884 bot_id = args[-1]
885 build_config = _GetConfig(bot_id)
886 else:
887 parser.error('Invalid usage. Use -h to see usage.')
888
889 if options.reference_repo is None:
890 repo_path = os.path.join(constants.SOURCE_ROOT, '.repo')
891 # If we're being run from a repo checkout, reuse the repo's git pool to
892 # cut down on sync time.
893 if os.path.exists(repo_path):
894 options.reference_repo = constants.SOURCE_ROOT
895 elif options.reference_repo:
896 if not os.path.exists(options.reference_repo):
897 parser.error('Reference path %s does not exist'
898 % (options.reference_repo,))
899 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
900 parser.error('Reference path %s does not look to be the base of a '
901 'repo checkout; no .repo exists in the root.'
902 % (options.reference_repo,))
903
904 if options.reference_repo:
905 options.reference_repo = os.path.abspath(options.reference_repo)
906
907 if options.dump_config:
908 # This works, but option ordering is bad...
909 print 'Configuration %s:' % bot_id
910 pretty_printer = pprint.PrettyPrinter(indent=2)
911 pretty_printer.pprint(build_config)
912 sys.exit(0)
913
914 if not options.buildroot:
915 if options.buildbot:
916 parser.error('Please specify a buildroot with the --buildroot option.')
917 else:
918 options.buildroot = _DetermineDefaultBuildRoot(build_config['internal'])
919 # We use a marker file in the buildroot to indicate the user has
920 # consented to using this directory.
921 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
922 _ConfirmBuildRoot(options.buildroot)
923
924 # Sanity check of buildroot- specifically that it's not pointing into the
925 # midst of an existing repo since git-repo doesn't support nesting.
926
927 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -0800928 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -0800929 parser.error('Configured buildroot %s points into a repository checkout, '
930 'rather than the root of it. This is not supported.'
931 % options.buildroot)
932
933 with sudo.SudoKeepAlive():
Brian Harringde588b52012-02-17 19:31:44 -0800934 with cros_lib.AllowDisabling(options.cgroups,
935 cgroups.ContainChildren, 'cbuildbot'):
Brian Harring3fec5a82012-03-01 05:57:03 -0800936 with cros_lib.AllowDisabling(options.timeout > 0,
937 cros_lib.Timeout, options.timeout):
938 if not options.buildbot:
939 build_config = cbuildbot_config.OverrideConfigForTrybot(build_config)
940 _RunBuildStagesWrapper(bot_id, options, build_config)