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