blob: 8500b05cbc3c53a873b31afe0ae7eaef07247eec [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():
87 """Returns the current Chromite tracking_branch.
88
89 If Chromite is on a detached HEAD, we assume it's the manifest branch.
90 """
91 cwd = os.path.dirname(os.path.realpath(__file__))
92 current_branch = cros_lib.GetCurrentBranch(cwd)
93 if current_branch:
94 (_, tracking_branch) = cros_lib.GetPushBranch(current_branch, cwd)
95 else:
96 tracking_branch = cros_lib.GetManifestDefaultBranch(cwd)
97
98 return tracking_branch
99
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
304 if self.gerrit_patches or self.local_patches:
305 self._RunStage(stages.PatchChangesStage,
306 self.gerrit_patches, self.local_patches)
307
308 if self._ShouldReExecuteInBuildRoot():
309 print_report = False
310 success = self._ReExecuteInBuildroot(sync_instance)
311 else:
312 self.RunStages()
313
314 finally:
315 if print_report:
316 self._WriteCheckpoint()
317 print '\n\n\n@@@BUILD_STEP Report@@@\n'
318 results_lib.Results.Report(sys.stdout, self.archive_urls,
319 self.release_tag)
320 success = results_lib.Results.BuildSucceededSoFar()
321
322 return success
323
324
325class SimpleBuilder(Builder):
326 """Builder that performs basic vetting operations."""
327
328 def GetSyncInstance(self):
329 """Sync to lkgm or TOT as necessary.
330
331 Returns: the instance of the sync stage that was run.
332 """
333 if self.options.lkgm or self.build_config['use_lkgm']:
334 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
335 else:
336 sync_stage = self._GetStageInstance(stages.SyncStage)
337
338 return sync_stage
339
David James58e0c092012-03-04 20:31:12 -0800340 def _RunBackgroundStagesForBoard(self, board):
341 """Run background board-specific stages for the specified board."""
David James58e0c092012-03-04 20:31:12 -0800342 archive_stage = self.archive_stages[board]
David James944a48e2012-03-07 12:19:03 -0800343 configs = self.build_config['board_specific_configs']
344 config = configs.get(board, self.build_config)
345 stage_list = [[stages.VMTestStage, board, archive_stage],
346 [stages.ChromeTestStage, board, archive_stage],
347 [stages.UnitTestStage, board],
348 [stages.UploadPrebuiltsStage, board]]
Brian Harring3fec5a82012-03-01 05:57:03 -0800349
David James58e0c092012-03-04 20:31:12 -0800350 # We can not run hw tests without archiving the payloads.
351 if self.options.archive:
David James944a48e2012-03-07 12:19:03 -0800352 for suite in config['hw_tests']:
353 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800354
David James944a48e2012-03-07 12:19:03 -0800355 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
356 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800357
358 def RunStages(self):
359 """Runs through build process."""
360 self._RunStage(stages.BuildBoardStage)
361
362 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800363 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
364 self._RunStage(stages.SDKTestStage)
365 self._RunStage(stages.UploadPrebuiltsStage,
366 constants.CHROOT_BUILDER_BOARD)
367 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
368 self._RunStage(stages.RefreshPackageStatusStage)
369 else:
370 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800371
David James944a48e2012-03-07 12:19:03 -0800372 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800373 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800374 config = configs.get(board, self.build_config)
375 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
376 config=config)
David James58e0c092012-03-04 20:31:12 -0800377 self.archive_stages[board] = archive_stage
378
David James944a48e2012-03-07 12:19:03 -0800379 # Set up a process pool to run test/archive stages in the background.
380 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800381 queue = multiprocessing.Queue()
382 task = self._RunBackgroundStagesForBoard
383 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800384 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800385 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800386 archive_stage = self.archive_stages[board]
387 config = configs.get(board, self.build_config)
388 self._RunStage(stages.BuildTargetStage, board, archive_stage,
389 config=config)
David James58e0c092012-03-04 20:31:12 -0800390 self.archive_urls[board] = archive_stage.GetDownloadUrl()
391
David James944a48e2012-03-07 12:19:03 -0800392 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800393 queue.put([board])
394
Brian Harring3fec5a82012-03-01 05:57:03 -0800395
396class DistributedBuilder(SimpleBuilder):
397 """Build class that has special logic to handle distributed builds.
398
399 These builds sync using git/manifest logic in manifest_versions. In general
400 they use a non-distributed builder code for the bulk of the work.
401 """
David James944a48e2012-03-07 12:19:03 -0800402 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800403 """Initializes a buildbot builder.
404
405 Extra variables:
406 completion_stage_class: Stage used to complete a build. Set in the Sync
407 stage.
408 """
David James944a48e2012-03-07 12:19:03 -0800409 super(DistributedBuilder, self).__init__(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800410 self.completion_stage_class = None
411
412 def GetSyncInstance(self):
413 """Syncs the tree using one of the distributed sync logic paths.
414
415 Returns: the instance of the sync stage that was run.
416 """
417 # Determine sync class to use. CQ overrides PFQ bits so should check it
418 # first.
419 if cbuildbot_config.IsCQType(self.build_config['build_type']):
420 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
421 self.completion_stage_class = stages.CommitQueueCompletionStage
422 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
423 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
424 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
425 else:
426 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
427 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
428
429 return sync_stage
430
431 def Publish(self, was_build_successful):
432 """Completes build by publishing any required information."""
433 completion_stage = self._GetStageInstance(self.completion_stage_class,
434 was_build_successful)
435 completion_stage.Run()
436 name = completion_stage.name
437 if not results_lib.Results.WasStageSuccessful(name):
438 should_publish_changes = False
439 else:
440 should_publish_changes = (self.build_config['master'] and
441 was_build_successful)
442
443 if should_publish_changes:
444 self._RunStage(stages.PublishUprevChangesStage)
445
446 def RunStages(self):
447 """Runs simple builder logic and publishes information to overlays."""
448 was_build_successful = False
449 try:
David Jamesf55709e2012-03-13 09:10:15 -0700450 super(DistributedBuilder, self).RunStages()
451 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800452 except SystemExit as ex:
453 # If a stage calls sys.exit(0), it's exiting with success, so that means
454 # we should mark ourselves as successful.
455 if ex.code == 0:
456 was_build_successful = True
457 raise
458 finally:
459 self.Publish(was_build_successful)
460
Brian Harring3fec5a82012-03-01 05:57:03 -0800461
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',
Brian Harring3fec5a82012-03-01 05:57:03 -0800695 help=('Specifies that this tryjob should be run remotely.'))
696
697 # Advanced options
698 group = optparse.OptionGroup(
699 parser,
700 'Advanced Options',
701 'Caution: use these options at your own risk.')
702
703 group.add_option('--buildbot', dest='buildbot', action='store_true',
704 default=False, help='This is running on a buildbot')
705 group.add_option('--buildnumber',
706 help='build number', type='int', default=0)
707 group.add_option('--chrome_root', default=None, type='string',
708 action='callback', dest='chrome_root',
709 callback=_CheckChromeRootOption,
710 help='Local checkout of Chrome to use.')
711 group.add_option('--chrome_version', default=None, type='string',
712 action='callback', dest='chrome_version',
713 callback=_CheckChromeVersionOption,
714 help='Used with SPEC logic to force a particular SVN '
715 'revision of chrome rather than the latest.')
716 group.add_option('--clobber', action='store_true', dest='clobber',
717 default=False,
718 help='Clears an old checkout before syncing')
719 group.add_option('--lkgm', action='store_true', dest='lkgm', default=False,
720 help='Sync to last known good manifest blessed by PFQ')
721 parser.add_option('--log_dir', action='callback', dest='log_dir',
722 type='string', callback=_CheckLogDirOption,
723 help=('Directory where logs are stored.'))
724 group.add_option('--maxarchives', dest='max_archive_builds',
725 default=3, type='int',
726 help="Change the local saved build count limit.")
727 group.add_option('--noarchive', action='store_false', dest='archive',
728 default=True,
729 help="Don't run archive stage.")
730 group.add_option('--nobuild', action='store_false', dest='build',
731 default=True,
732 help="Don't actually build (for cbuildbot dev")
733 group.add_option('--noclean', action='store_false', dest='clean',
734 default=True,
735 help="Don't clean the buildroot")
736 group.add_option('--noprebuilts', action='store_false', dest='prebuilts',
737 default=True,
738 help="Don't upload prebuilts.")
739 group.add_option('--nosync', action='store_false', dest='sync',
740 default=True,
741 help="Don't sync before building.")
742 group.add_option('--nocgroups', action='store_false', dest='cgroups',
743 default=True,
744 help='Disable cbuildbots usage of cgroups.')
Ryan Cuiadd49122012-03-21 22:19:58 -0700745 group.add_option('--notests', action='store_false', dest='tests',
746 default=True,
747 help='Override values from buildconfig and run no tests.')
748 group.add_option('--nouprev', action='store_false', dest='uprev',
749 default=True,
750 help='Override values from buildconfig and never uprev.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800751 group.add_option('--reference-repo', action='store', default=None,
752 dest='reference_repo',
753 help='Reuse git data stored in an existing repo '
754 'checkout. This can drastically reduce the network '
755 'time spent setting up the trybot checkout. By '
756 "default, if this option isn't given but cbuildbot "
757 'is invoked from a repo checkout, cbuildbot will '
758 'use the repo root.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800759 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
760 default=False,
Ryan Cuiadd49122012-03-21 22:19:58 -0700761 help=('This is running on a remote trybot machine. '))
762 group.add_option('--resume', action='store_true',
763 default=False,
764 help='Skip stages already successfully completed.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800765 group.add_option('--timeout', action='store', type='int', default=0,
766 help="Specify the maximum amount of time this job can run "
767 "for, at which point the build will be aborted. If "
768 "set to zero, then there is no timeout")
Brian Harring3fec5a82012-03-01 05:57:03 -0800769 group.add_option('--validation_pool', default=None,
770 help='Path to a pickled validation pool. Intended for use '
771 'only with the commit queue.')
772 group.add_option('--version', dest='force_version', default=None,
773 help='Used with manifest logic. Forces use of this version '
774 'rather than create or get latest.')
775
776 parser.add_option_group(group)
777
778 # Debug options
779 group = optparse.OptionGroup(parser, "Debug Options")
780
Ryan Cui85867972012-02-23 18:21:49 -0800781 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800782 help='Override some options to run as a developer.')
783 group.add_option('--dump_config', action='store_true', dest='dump_config',
784 default=False,
785 help='Dump out build config options, and exit.')
786 group.add_option('--notee', action='store_false', dest='tee', default=True,
787 help="Disable logging and internal tee process. Primarily "
788 "used for debugging cbuildbot itself.")
789 parser.add_option_group(group)
790 return parser
791
792
Ryan Cui85867972012-02-23 18:21:49 -0800793def _FinishParsing(options, args):
794 """Perform some parsing tasks that need to take place after optparse.
795
796 This function needs to be easily testable! Keep it free of
797 environment-dependent code. Put more detailed usage validation in
798 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800799
800 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800801 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800802 """
Brian Harring3fec5a82012-03-01 05:57:03 -0800803 if options.chrome_root:
804 if options.chrome_rev != constants.CHROME_REV_LOCAL:
805 cros_lib.Die('Chrome rev must be %s if chrome_root is set.' %
806 constants.CHROME_REV_LOCAL)
807 else:
808 if options.chrome_rev == constants.CHROME_REV_LOCAL:
809 cros_lib.Die('Chrome root must be set if chrome_rev is %s.' %
810 constants.CHROME_REV_LOCAL)
811
812 if options.chrome_version:
813 if options.chrome_rev != constants.CHROME_REV_SPEC:
814 cros_lib.Die('Chrome rev must be %s if chrome_version is set.' %
815 constants.CHROME_REV_SPEC)
816 else:
817 if options.chrome_rev == constants.CHROME_REV_SPEC:
818 cros_lib.Die('Chrome rev must not be %s if chrome_version is not set.' %
819 constants.CHROME_REV_SPEC)
820
821 if options.remote and options.local_patches:
822 cros_lib.Die('Local patching not yet supported with remote tryjobs.')
823
Brian Harring3fec5a82012-03-01 05:57:03 -0800824 if options.remote and not options.gerrit_patches:
825 cros_lib.Die('Must provide patches when running with --remote.')
826
827 if len(args) > 1 and not options.remote:
828 cros_lib.Die('Multiple configs not supported if not running with --remote.')
829
Ryan Cuiba41ad32012-03-08 17:15:29 -0800830 if options.buildbot and options.remote_trybot:
831 cros_lib.Die('--buildbot and --remote-trybot cannot be used together.')
832
Ryan Cui85867972012-02-23 18:21:49 -0800833 # Record whether --debug was set explicitly vs. it was inferred.
834 options.debug_forced = False
835 if options.debug:
836 options.debug_forced = True
837 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800838 # We don't set debug by default for
839 # 1. --buildbot invocations.
840 # 2. --remote invocations, because it needs to push changes to the tryjob
841 # repo.
842 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -0800843
Brian Harring3fec5a82012-03-01 05:57:03 -0800844
Ryan Cui85867972012-02-23 18:21:49 -0800845def _PostParseCheck(options, args):
846 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800847
Ryan Cui85867972012-02-23 18:21:49 -0800848 Args:
849 options/args: The options/args object returned by optparse
850 """
851 if not options.resume:
852 try:
853 # TODO(rcui): Split this into two stages, one that parses, another that
854 # validates. Parsing step will be called by _FinishParsing().
855 if options.local_patches:
856 _CheckAndSplitLocalPatches(options)
857
858 except optparse.OptionValueError as e:
859 cros_lib.Die(str(e))
860
861
862def _ParseCommandLine(parser, argv):
863 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800864 (options, args) = parser.parse_args(argv)
865 # Strip out null arguments.
866 # TODO(rcui): Remove when buildbot is fixed
867 args = [arg for arg in args if arg]
Ryan Cui85867972012-02-23 18:21:49 -0800868 _FinishParsing(options, args)
869 return options, args
870
871
872def main(argv):
873 # Set umask to 022 so files created by buildbot are readable.
874 os.umask(022)
875
876 if cros_lib.IsInsideChroot():
877 cros_lib.Die('Please run cbuildbot from outside the chroot.')
878
879 parser = _CreateParser()
880 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -0800881
882 if options.list:
883 _PrintValidConfigs(not options.print_all)
884 sys.exit(0)
885
886 _PostParseCheck(options, args)
887
888 if options.remote:
Ryan Cui16ca5812012-03-08 20:34:27 -0800889 cros_lib.DebugLevel.SetDebugLevel(cros_lib.DebugLevel.WARNING)
890
Brian Harring3fec5a82012-03-01 05:57:03 -0800891 # Verify configs are valid.
892 for bot in args:
893 _GetConfig(bot)
894
895 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -0800896 print 'Verifying patches...'
Brian Harring3fec5a82012-03-01 05:57:03 -0800897 _PreProcessPatches(options.gerrit_patches, options.local_patches)
Ryan Cui16ca5812012-03-08 20:34:27 -0800898 print 'Submitting tryjob...'
899 tryjob = remote_try.RemoteTryJob(options, args)
900 tryjob.Submit(dryrun=options.debug)
901 print 'Tryjob submitted!'
902 print ('Go to %s to view the status of your job.'
903 % tryjob.GetTrybotConsoleLink())
Brian Harring3fec5a82012-03-01 05:57:03 -0800904 sys.exit(0)
905
906 if args:
907 # Only expecting one config
908 bot_id = args[-1]
909 build_config = _GetConfig(bot_id)
910 else:
911 parser.error('Invalid usage. Use -h to see usage.')
912
913 if options.reference_repo is None:
914 repo_path = os.path.join(constants.SOURCE_ROOT, '.repo')
915 # If we're being run from a repo checkout, reuse the repo's git pool to
916 # cut down on sync time.
917 if os.path.exists(repo_path):
918 options.reference_repo = constants.SOURCE_ROOT
919 elif options.reference_repo:
920 if not os.path.exists(options.reference_repo):
921 parser.error('Reference path %s does not exist'
922 % (options.reference_repo,))
923 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
924 parser.error('Reference path %s does not look to be the base of a '
925 'repo checkout; no .repo exists in the root.'
926 % (options.reference_repo,))
Brian Harring470f6112012-03-02 11:47:10 -0800927 if options.buildbot:
928 if not options.cgroups:
929 parser.error('Options --buildbot and --nocgroups cannot be used '
930 'together. Cgroup support is required for buildbot mode.')
931 if not cgroups.Cgroup.CgroupsSupported():
932 parser.error('Option --buildbot was given, but this system does not '
933 'support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800934
Brian Harring351ce442012-03-09 16:38:14 -0800935 missing = []
936 for program in _BUILDBOT_REQUIRED_BINARIES:
937 ret = cros_lib.RunCommand('which %s' % program, shell=True,
938 redirect_stderr=True, redirect_stdout=True,
939 error_code_ok=True, print_cmd=False)
940 if ret.returncode != 0:
941 missing.append(program)
942
943 if missing:
944 parser.error("Option --buildbot requires the following binaries which "
945 "couldn't be found in $PATH: %s"
946 % (', '.join(missing)))
947
948
949
Brian Harring3fec5a82012-03-01 05:57:03 -0800950 if options.reference_repo:
951 options.reference_repo = os.path.abspath(options.reference_repo)
952
953 if options.dump_config:
954 # This works, but option ordering is bad...
955 print 'Configuration %s:' % bot_id
956 pretty_printer = pprint.PrettyPrinter(indent=2)
957 pretty_printer.pprint(build_config)
958 sys.exit(0)
959
960 if not options.buildroot:
961 if options.buildbot:
962 parser.error('Please specify a buildroot with the --buildroot option.')
Brian Harring470f6112012-03-02 11:47:10 -0800963 options.buildroot = _DetermineDefaultBuildRoot(build_config['internal'])
964 # We use a marker file in the buildroot to indicate the user has
965 # consented to using this directory.
966 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
967 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800968
969 # Sanity check of buildroot- specifically that it's not pointing into the
970 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -0800971 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -0800972 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -0800973 parser.error('Configured buildroot %s points into a repository checkout, '
974 'rather than the root of it. This is not supported.'
975 % options.buildroot)
976
Brian Harringa184efa2012-03-04 11:51:25 -0800977 with cleanup.EnforcedCleanupSection() as critical_section:
978 with sudo.SudoKeepAlive():
979 with cros_lib.AllowDisabling(options.cgroups,
Brian Harring4e6412d2012-03-09 20:54:02 -0800980 cgroups.SimpleContainChildren, 'cbuildbot'):
Brian Harringa184efa2012-03-04 11:51:25 -0800981 # Mark everything between EnforcedCleanupSection and here as having to
982 # be rolled back via the contextmanager cleanup handlers. This ensures
983 # that sudo bits cannot outlive cbuildbot, that anything cgroups
984 # would kill gets killed, etc.
985 critical_section.ForkWatchdog()
986
987 with cros_lib.AllowDisabling(options.timeout > 0,
988 cros_lib.Timeout, options.timeout):
989 if not options.buildbot:
990 build_config = cbuildbot_config.OverrideConfigForTrybot(
Ryan Cui3d6b4742012-03-14 11:42:24 -0700991 build_config,
992 options.remote_trybot)
Brian Harringa184efa2012-03-04 11:51:25 -0800993
994 _RunBuildStagesWrapper(options, build_config)