blob: 0b469e8c9f0c5d5e10b5ca2fa45506184112c30b [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
Chris Sosa4f6ffaf2012-05-01 17:05:44 -070015import logging
David James58e0c092012-03-04 20:31:12 -080016import multiprocessing
Brian Harring3fec5a82012-03-01 05:57:03 -080017import optparse
18import os
19import pprint
20import sys
Ryan Cui54da0702012-04-19 18:38:08 -070021import time
Brian Harring3fec5a82012-03-01 05:57:03 -080022
23from chromite.buildbot import builderstage as bs
24from chromite.buildbot import cbuildbot_background as background
25from chromite.buildbot import cbuildbot_config
26from chromite.buildbot import cbuildbot_stages as stages
27from chromite.buildbot import cbuildbot_results as results_lib
Brian Harring3fec5a82012-03-01 05:57:03 -080028from chromite.buildbot import constants
29from chromite.buildbot import gerrit_helper
30from chromite.buildbot import patch as cros_patch
31from chromite.buildbot import remote_try
32from chromite.buildbot import repository
33from chromite.buildbot import tee
34
Brian Harringc92a7012012-02-29 10:11:34 -080035from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080036from chromite.lib import cleanup
Brian Harring3fec5a82012-03-01 05:57:03 -080037from chromite.lib import cros_build_lib as cros_lib
Brian Harringaf019fb2012-05-10 15:06:13 -070038from chromite.lib import osutils
Brian Harring3fec5a82012-03-01 05:57:03 -080039from chromite.lib import sudo
40
Ryan Cuiadd49122012-03-21 22:19:58 -070041
Brian Harring3fec5a82012-03-01 05:57:03 -080042cros_lib.STRICT_SUDO = True
43
44_DEFAULT_LOG_DIR = 'cbuildbot_logs'
45_BUILDBOT_LOG_FILE = 'cbuildbot.log'
46_DEFAULT_EXT_BUILDROOT = 'trybot'
47_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Matt Tennantf1e30972012-03-02 16:30:07 -080048_PATH_TO_CBUILDBOT = os.path.join(constants.CHROMITE_BIN_SUBDIR, 'cbuildbot')
Brian Harring3fec5a82012-03-01 05:57:03 -080049_DISTRIBUTED_TYPES = [constants.COMMIT_QUEUE_TYPE, constants.PFQ_TYPE,
50 constants.CANARY_TYPE, constants.CHROME_PFQ_TYPE,
51 constants.PALADIN_TYPE]
Brian Harring351ce442012-03-09 16:38:14 -080052_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Brian Harring3fec5a82012-03-01 05:57:03 -080053
54
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070055def _PrintValidConfigs(display_all=False):
Brian Harring3fec5a82012-03-01 05:57:03 -080056 """Print a list of valid buildbot configs.
57
58 Arguments:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070059 display_all: Print all configs. Otherwise, prints only configs with
60 trybot_list=True.
Brian Harring3fec5a82012-03-01 05:57:03 -080061 """
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070062 def _GetSortKey(config_name):
63 config_dict = cbuildbot_config.config[config_name]
64 return (not config_dict['trybot_list'], config_dict['description'],
65 config_name)
66
Brian Harring3fec5a82012-03-01 05:57:03 -080067 COLUMN_WIDTH = 45
68 print 'config'.ljust(COLUMN_WIDTH), 'description'
69 print '------'.ljust(COLUMN_WIDTH), '-----------'
70 config_names = cbuildbot_config.config.keys()
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070071 config_names.sort(key=_GetSortKey)
Brian Harring3fec5a82012-03-01 05:57:03 -080072 for name in config_names:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070073 if display_all or cbuildbot_config.config[name]['trybot_list']:
74 desc = cbuildbot_config.config[name].get('description')
75 desc = desc if desc else ''
Brian Harring3fec5a82012-03-01 05:57:03 -080076 print name.ljust(COLUMN_WIDTH), desc
77
78
79def _GetConfig(config_name):
80 """Gets the configuration for the build"""
81 if not cbuildbot_config.config.has_key(config_name):
82 print 'Non-existent configuration %s specified.' % config_name
83 print 'Please specify one of:'
84 _PrintValidConfigs()
85 sys.exit(1)
86
87 result = cbuildbot_config.config[config_name]
88
89 return result
90
91
92def _GetChromiteTrackingBranch():
David James66009462012-03-25 10:08:38 -070093 """Returns the remote branch associated with chromite."""
Brian Harring3fec5a82012-03-01 05:57:03 -080094 cwd = os.path.dirname(os.path.realpath(__file__))
David James66009462012-03-25 10:08:38 -070095 branch = cros_lib.GetCurrentBranch(cwd)
96 if branch:
97 tracking_branch = cros_lib.GetTrackingBranch(branch, cwd)[1]
98 if tracking_branch.startswith('refs/heads/'):
99 return tracking_branch.replace('refs/heads/', '')
100 # If we are not on a branch, or if the tracking branch is a revision,
David James8b3c1bf2012-03-28 09:10:16 -0700101 # use the push branch. For repo repositories, this will be the manifest
102 # branch configured for this project. For other repositories, we'll just
103 # guess 'master', since there's no easy way to find out what branch
104 # we're on.
105 return cros_lib.GetPushBranch(cwd)[1]
Brian Harring3fec5a82012-03-01 05:57:03 -0800106
107
108def _CheckBuildRootBranch(buildroot, tracking_branch):
109 """Make sure buildroot branch is the same as Chromite branch."""
110 manifest_branch = cros_lib.GetManifestDefaultBranch(buildroot)
111 if manifest_branch != tracking_branch:
112 cros_lib.Die('Chromite is not on same branch as buildroot checkout\n' +
113 'Chromite is on branch %s.\n' % tracking_branch +
114 'Buildroot checked out to %s\n' % manifest_branch)
115
116
117def _PreProcessPatches(gerrit_patches, local_patches):
118 """Validate patches ASAP to catch user errors. Also generate patch info.
119
120 Args:
121 gerrit_patches: List of gerrit CL ID's passed in by user.
122 local_patches: List of local project branches to generate patches from.
123
124 Returns:
125 A tuple containing a list of cros_patch.GerritPatch and a list of
Matt Tennantd55b1f42012-04-13 14:15:01 -0700126 cros_patch.LocalGitRepoPatch objects.
Brian Harring3fec5a82012-03-01 05:57:03 -0800127 """
128 gerrit_patch_info = []
129 local_patch_info = []
130
131 try:
132 if gerrit_patches:
133 gerrit_patch_info = gerrit_helper.GetGerritPatchInfo(gerrit_patches)
134 for patch in gerrit_patch_info:
135 if patch.IsAlreadyMerged():
136 cros_lib.Warning('Patch %s has already been merged.' % str(patch))
137 except gerrit_helper.GerritException as e:
138 cros_lib.Die(str(e))
139
140 try:
141 if local_patches:
142 local_patch_info = cros_patch.PrepareLocalPatches(
143 local_patches,
144 _GetChromiteTrackingBranch())
145
146 except cros_patch.PatchException as e:
147 cros_lib.Die(str(e))
148
149 return gerrit_patch_info, local_patch_info
150
151
152def _IsIncrementalBuild(buildroot, clobber):
153 """Returns True if we are reusing an existing buildroot."""
154 repo_dir = os.path.join(buildroot, '.repo')
155 return not clobber and os.path.isdir(repo_dir)
156
157
158class Builder(object):
159 """Parent class for all builder types.
160
161 This class functions as a parent class for various build types. It's intended
162 use is builder_instance.Run().
163
164 Vars:
Brian Harring3fec5a82012-03-01 05:57:03 -0800165 build_config: The configuration dictionary from cbuildbot_config.
166 options: The options provided from optparse in main().
167 completed_stages_file: Where we store resume state.
168 archive_url: Where our artifacts for this builder will be archived.
169 tracking_branch: The tracking branch for this build.
170 release_tag: The associated "chrome os version" of this build.
171 gerrit_patches: Gerrit patches to be included in build.
172 local_patches: Local patches to be included in build.
173 """
174
David James944a48e2012-03-07 12:19:03 -0800175 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800176 """Initializes instance variables. Must be called by all subclasses."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800177 self.build_config = build_config
178 self.options = options
179
180 # TODO, Remove here and in config after bug chromium-os:14649 is fixed.
181 if self.build_config['chromeos_official']:
182 os.environ['CHROMEOS_OFFICIAL'] = '1'
183
184 self.completed_stages_file = os.path.join(options.buildroot,
185 '.completed_stages')
David James58e0c092012-03-04 20:31:12 -0800186 self.archive_stages = {}
Brian Harring3fec5a82012-03-01 05:57:03 -0800187 self.archive_urls = {}
188 self.release_tag = None
Brian Harringeb237932012-05-07 02:08:06 -0700189 self.target_manifest_branch = _GetChromiteTrackingBranch()
Brian Harring3fec5a82012-03-01 05:57:03 -0800190 self.gerrit_patches = None
191 self.local_patches = None
192
193 def Initialize(self):
194 """Runs through the initialization steps of an actual build."""
195 if self.options.resume and os.path.exists(self.completed_stages_file):
196 with open(self.completed_stages_file, 'r') as load_file:
197 results_lib.Results.RestoreCompletedStages(load_file)
198
199 # We only want to do this if we need to patch changes.
200 if not results_lib.Results.GetPrevious().get(
201 self._GetStageInstance(stages.PatchChangesStage, None, None).name):
202 self.gerrit_patches, self.local_patches = _PreProcessPatches(
203 self.options.gerrit_patches, self.options.local_patches)
204
Brian Harringeb237932012-05-07 02:08:06 -0700205 bs.BuilderStage.SetManifestBranch(self.target_manifest_branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800206
207 # Check branch matching early.
208 if _IsIncrementalBuild(self.options.buildroot, self.options.clobber):
Brian Harringeb237932012-05-07 02:08:06 -0700209 _CheckBuildRootBranch(self.options.buildroot, self.target_manifest_branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800210
211 self._RunStage(stages.CleanUpStage)
212
213 def _GetStageInstance(self, stage, *args, **kwargs):
214 """Helper function to get an instance given the args.
215
David James944a48e2012-03-07 12:19:03 -0800216 Useful as almost all stages just take in options and build_config.
Brian Harring3fec5a82012-03-01 05:57:03 -0800217 """
David James944a48e2012-03-07 12:19:03 -0800218 config = kwargs.pop('config', self.build_config)
219 return stage(self.options, config, *args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800220
221 def _SetReleaseTag(self):
222 """Sets the release tag from the manifest_manager.
223
224 Must be run after sync stage as syncing enables us to have a release tag.
225 """
226 # Extract version we have decided to build into self.release_tag.
227 manifest_manager = stages.ManifestVersionedSyncStage.manifest_manager
228 if manifest_manager:
229 self.release_tag = manifest_manager.current_version
230
231 def _RunStage(self, stage, *args, **kwargs):
232 """Wrapper to run a stage."""
233 stage_instance = self._GetStageInstance(stage, *args, **kwargs)
234 return stage_instance.Run()
235
236 def GetSyncInstance(self):
237 """Returns an instance of a SyncStage that should be run.
238
239 Subclasses must override this method.
240 """
241 raise NotImplementedError()
242
243 def RunStages(self):
244 """Subclasses must override this method. Runs the appropriate code."""
245 raise NotImplementedError()
246
247 def _WriteCheckpoint(self):
248 """Drops a completed stages file with current state."""
249 with open(self.completed_stages_file, 'w+') as save_file:
250 results_lib.Results.SaveCompletedStages(save_file)
251
252 def _ShouldReExecuteInBuildRoot(self):
253 """Returns True if this build should be re-executed in the buildroot."""
254 abs_buildroot = os.path.abspath(self.options.buildroot)
255 return not os.path.abspath(__file__).startswith(abs_buildroot)
256
257 def _ReExecuteInBuildroot(self, sync_instance):
258 """Reexecutes self in buildroot and returns True if build succeeds.
259
260 This allows the buildbot code to test itself when changes are patched for
261 buildbot-related code. This is a no-op if the buildroot == buildroot
262 of the running chromite checkout.
263
264 Args:
265 sync_instance: Instance of the sync stage that was run to sync.
266
267 Returns:
268 True if the Build succeeded.
269 """
270 # If we are resuming, use last checkpoint.
271 if not self.options.resume:
272 self._WriteCheckpoint()
273
274 # Re-write paths to use absolute paths.
275 # Suppress any timeout options given from the commandline in the
276 # invoked cbuildbot; our timeout will enforce it instead.
Brian Harringf11bf682012-05-14 15:53:43 -0700277 args_to_append = ['--resume', '--timeout', '0', '--notee', '--nocgroups',
278 '--buildroot', os.path.abspath(self.options.buildroot)]
Brian Harring3fec5a82012-03-01 05:57:03 -0800279
280 if self.options.chrome_root:
281 args_to_append += ['--chrome_root',
282 os.path.abspath(self.options.chrome_root)]
283
284 if stages.ManifestVersionedSyncStage.manifest_manager:
285 ver = stages.ManifestVersionedSyncStage.manifest_manager.current_version
286 args_to_append += ['--version', ver]
287
288 if isinstance(sync_instance, stages.CommitQueueSyncStage):
289 vp_file = sync_instance.SaveValidationPool()
290 args_to_append += ['--validation_pool', vp_file]
291
292 # Re-run the command in the buildroot.
293 # Finally, be generous and give the invoked cbuildbot 30s to shutdown
294 # when something occurs. It should exit quicker, but the sigterm may
295 # hit while the system is particularly busy.
296 return_obj = cros_lib.RunCommand(
297 [_PATH_TO_CBUILDBOT] + sys.argv[1:] + args_to_append,
298 cwd=self.options.buildroot, error_code_ok=True, kill_timeout=30)
299 return return_obj.returncode == 0
300
301 def Run(self):
302 """Main runner for this builder class. Runs build and prints summary."""
303 print_report = True
David James3d4d3502012-04-09 15:12:06 -0700304 exception_thrown = False
Brian Harring3fec5a82012-03-01 05:57:03 -0800305 success = True
306 try:
307 self.Initialize()
308 sync_instance = self.GetSyncInstance()
309 sync_instance.Run()
310 self._SetReleaseTag()
311
Ryan Cuicedd8a52012-03-22 02:28:35 -0700312 if (self.gerrit_patches or self.local_patches
313 or self.options.remote_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800314 self._RunStage(stages.PatchChangesStage,
315 self.gerrit_patches, self.local_patches)
316
317 if self._ShouldReExecuteInBuildRoot():
318 print_report = False
319 success = self._ReExecuteInBuildroot(sync_instance)
320 else:
321 self.RunStages()
David James3d4d3502012-04-09 15:12:06 -0700322 except Exception:
323 exception_thrown = True
324 raise
Brian Harring3fec5a82012-03-01 05:57:03 -0800325 finally:
326 if print_report:
327 self._WriteCheckpoint()
328 print '\n\n\n@@@BUILD_STEP Report@@@\n'
329 results_lib.Results.Report(sys.stdout, self.archive_urls,
330 self.release_tag)
331 success = results_lib.Results.BuildSucceededSoFar()
David James3d4d3502012-04-09 15:12:06 -0700332 if exception_thrown and success:
333 success = False
334 print >> sys.stderr, """
335@@@STEP_FAILURE@@@
336Exception thrown, but all stages marked successful. This is an internal error,
337because the stage that threw the exception should be marked as failing."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800338
339 return success
340
341
342class SimpleBuilder(Builder):
343 """Builder that performs basic vetting operations."""
344
345 def GetSyncInstance(self):
346 """Sync to lkgm or TOT as necessary.
347
348 Returns: the instance of the sync stage that was run.
349 """
350 if self.options.lkgm or self.build_config['use_lkgm']:
351 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
352 else:
353 sync_stage = self._GetStageInstance(stages.SyncStage)
354
355 return sync_stage
356
David James58e0c092012-03-04 20:31:12 -0800357 def _RunBackgroundStagesForBoard(self, board):
358 """Run background board-specific stages for the specified board."""
David James58e0c092012-03-04 20:31:12 -0800359 archive_stage = self.archive_stages[board]
David James944a48e2012-03-07 12:19:03 -0800360 configs = self.build_config['board_specific_configs']
361 config = configs.get(board, self.build_config)
362 stage_list = [[stages.VMTestStage, board, archive_stage],
363 [stages.ChromeTestStage, board, archive_stage],
364 [stages.UnitTestStage, board],
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700365 [stages.UploadPrebuiltsStage, board, archive_stage]]
Brian Harring3fec5a82012-03-01 05:57:03 -0800366
David James58e0c092012-03-04 20:31:12 -0800367 # We can not run hw tests without archiving the payloads.
368 if self.options.archive:
David James944a48e2012-03-07 12:19:03 -0800369 for suite in config['hw_tests']:
370 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800371
David James944a48e2012-03-07 12:19:03 -0800372 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
373 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800374
375 def RunStages(self):
376 """Runs through build process."""
377 self._RunStage(stages.BuildBoardStage)
378
379 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800380 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
381 self._RunStage(stages.SDKTestStage)
382 self._RunStage(stages.UploadPrebuiltsStage,
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700383 constants.CHROOT_BUILDER_BOARD, None)
Brian Harring3fec5a82012-03-01 05:57:03 -0800384 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
385 self._RunStage(stages.RefreshPackageStatusStage)
386 else:
387 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800388
David James944a48e2012-03-07 12:19:03 -0800389 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800390 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800391 config = configs.get(board, self.build_config)
392 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
393 config=config)
David James58e0c092012-03-04 20:31:12 -0800394 self.archive_stages[board] = archive_stage
395
David James944a48e2012-03-07 12:19:03 -0800396 # Set up a process pool to run test/archive stages in the background.
397 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800398 queue = multiprocessing.Queue()
399 task = self._RunBackgroundStagesForBoard
400 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800401 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800402 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800403 archive_stage = self.archive_stages[board]
404 config = configs.get(board, self.build_config)
405 self._RunStage(stages.BuildTargetStage, board, archive_stage,
Chris Sosa1a87b3e2012-04-12 13:20:42 -0700406 self.release_tag, config=config)
David James58e0c092012-03-04 20:31:12 -0800407 self.archive_urls[board] = archive_stage.GetDownloadUrl()
408
David James944a48e2012-03-07 12:19:03 -0800409 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800410 queue.put([board])
411
Brian Harring3fec5a82012-03-01 05:57:03 -0800412
413class DistributedBuilder(SimpleBuilder):
414 """Build class that has special logic to handle distributed builds.
415
416 These builds sync using git/manifest logic in manifest_versions. In general
417 they use a non-distributed builder code for the bulk of the work.
418 """
David James944a48e2012-03-07 12:19:03 -0800419 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800420 """Initializes a buildbot builder.
421
422 Extra variables:
423 completion_stage_class: Stage used to complete a build. Set in the Sync
424 stage.
425 """
David James944a48e2012-03-07 12:19:03 -0800426 super(DistributedBuilder, self).__init__(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800427 self.completion_stage_class = None
428
429 def GetSyncInstance(self):
430 """Syncs the tree using one of the distributed sync logic paths.
431
432 Returns: the instance of the sync stage that was run.
433 """
434 # Determine sync class to use. CQ overrides PFQ bits so should check it
435 # first.
436 if cbuildbot_config.IsCQType(self.build_config['build_type']):
437 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
438 self.completion_stage_class = stages.CommitQueueCompletionStage
439 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
440 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
441 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
442 else:
443 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
444 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
445
446 return sync_stage
447
448 def Publish(self, was_build_successful):
449 """Completes build by publishing any required information."""
450 completion_stage = self._GetStageInstance(self.completion_stage_class,
451 was_build_successful)
452 completion_stage.Run()
453 name = completion_stage.name
454 if not results_lib.Results.WasStageSuccessful(name):
455 should_publish_changes = False
456 else:
457 should_publish_changes = (self.build_config['master'] and
458 was_build_successful)
459
460 if should_publish_changes:
461 self._RunStage(stages.PublishUprevChangesStage)
462
463 def RunStages(self):
464 """Runs simple builder logic and publishes information to overlays."""
465 was_build_successful = False
466 try:
David Jamesf55709e2012-03-13 09:10:15 -0700467 super(DistributedBuilder, self).RunStages()
468 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800469 except SystemExit as ex:
470 # If a stage calls sys.exit(0), it's exiting with success, so that means
471 # we should mark ourselves as successful.
472 if ex.code == 0:
473 was_build_successful = True
474 raise
475 finally:
476 self.Publish(was_build_successful)
477
Brian Harring3fec5a82012-03-01 05:57:03 -0800478
479def _ConfirmBuildRoot(buildroot):
480 """Confirm with user the inferred buildroot, and mark it as confirmed."""
481 warning = 'Using default directory %s as buildroot' % buildroot
482 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
483 full=True)
484 if response == cros_lib.NO:
485 print('Please specify a buildroot with the --buildroot option.')
486 sys.exit(0)
487
488 if not os.path.exists(buildroot):
489 os.mkdir(buildroot)
490
491 repository.CreateTrybotMarker(buildroot)
492
493
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700494def _ConfirmRemoteBuildbotRun():
495 """Confirm user wants to run with --buildbot --remote."""
496 warning = ('You are about to launch a PRODUCTION job! This is *NOT* a '
497 'trybot run! Are you sure?')
498 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
499 full=True)
500
501 if response == cros_lib.NO:
502 print('Please specify --pass-through="--debug".')
503 sys.exit(0)
504
505
Brian Harring3fec5a82012-03-01 05:57:03 -0800506def _DetermineDefaultBuildRoot(internal_build):
507 """Default buildroot to be under the directory that contains current checkout.
508
509 Arguments:
510 internal_build: Whether the build is an internal build
511 """
512 repo_dir = cros_lib.FindRepoDir()
513 if not repo_dir:
514 cros_lib.Die('Could not find root of local checkout. Please specify'
515 'using --buildroot option.')
516
517 # Place trybot buildroot under the directory containing current checkout.
518 top_level = os.path.dirname(os.path.realpath(os.path.dirname(repo_dir)))
519 if internal_build:
520 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
521 else:
522 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
523
524 return buildroot
525
526
527def _BackupPreviousLog(log_file, backup_limit=25):
528 """Rename previous log.
529
530 Args:
531 log_file: The absolute path to the previous log.
532 """
533 if os.path.exists(log_file):
534 old_logs = sorted(glob.glob(log_file + '.*'),
535 key=distutils.version.LooseVersion)
536
537 if len(old_logs) >= backup_limit:
538 os.remove(old_logs[0])
539
540 last = 0
541 if old_logs:
542 last = int(old_logs.pop().rpartition('.')[2])
543
544 os.rename(log_file, log_file + '.' + str(last + 1))
545
546
David James944a48e2012-03-07 12:19:03 -0800547def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800548 """Helper function that wraps RunBuildStages()."""
549 def IsDistributedBuilder():
550 """Determines whether the build_config should be a DistributedBuilder."""
551 if not options.buildbot:
552 return False
553 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
554 chrome_rev = build_config['chrome_rev']
555 if options.chrome_rev: chrome_rev = options.chrome_rev
556 # We don't do distributed logic to TOT Chrome PFQ's, nor local
557 # chrome roots (e.g. chrome try bots)
558 if chrome_rev not in [constants.CHROME_REV_TOT,
559 constants.CHROME_REV_LOCAL,
560 constants.CHROME_REV_SPEC]:
561 return True
562
563 return False
564
Brian Harringd166aaf2012-05-14 18:31:53 -0700565 cros_lib.Info("cbuildbot executed with args %s"
566 % ' '.join(map(repr, sys.argv)))
567 if IsDistributedBuilder():
568 buildbot = DistributedBuilder(options, build_config)
569 else:
570 buildbot = SimpleBuilder(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800571
Brian Harringd166aaf2012-05-14 18:31:53 -0700572 if not buildbot.Run():
573 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800574
575
576# Parser related functions
Ryan Cuicedd8a52012-03-22 02:28:35 -0700577def _CheckLocalPatches(local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800578 """Do an early quick check of the passed-in patches.
579
580 If the branch of a project is not specified we append the current branch the
581 project is on.
582 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700583 verified_patches = []
584 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800585 components = patch.split(':')
586 if len(components) > 2:
587 msg = 'Specify local patches in project[:branch] format.'
588 raise optparse.OptionValueError(msg)
589
590 # validate project
591 project = components[0]
592 if not cros_lib.DoesProjectExist('.', project):
593 raise optparse.OptionValueError('Project %s does not exist.' % project)
594
595 project_dir = cros_lib.GetProjectDir('.', project)
596
597 # If no branch was specified, we use the project's current branch.
598 if len(components) == 1:
599 branch = cros_lib.GetCurrentBranch(project_dir)
600 if not branch:
601 raise optparse.OptionValueError('project %s is not on a branch!'
602 % project)
603 # Append branch information to patch
604 patch = '%s:%s' % (project, branch)
605 else:
606 branch = components[1]
607 if not cros_lib.DoesLocalBranchExist(project_dir, branch):
608 raise optparse.OptionValueError('Project %s does not have branch %s'
609 % (project, branch))
610
Ryan Cuicedd8a52012-03-22 02:28:35 -0700611 verified_patches.append(patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800612
Ryan Cuicedd8a52012-03-22 02:28:35 -0700613 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800614
615
616def _CheckBuildRootOption(_option, _opt_str, value, parser):
617 """Validate and convert buildroot to full-path form."""
618 value = value.strip()
619 if not value or value == '/':
620 raise optparse.OptionValueError('Invalid buildroot specified')
621
622 parser.values.buildroot = os.path.realpath(os.path.expanduser(value))
623
624
625def _CheckLogDirOption(_option, _opt_str, value, parser):
626 """Validate and convert buildroot to full-path form."""
627 parser.values.log_dir = os.path.abspath(os.path.expanduser(value))
628
629
630def _CheckChromeVersionOption(_option, _opt_str, value, parser):
631 """Upgrade other options based on chrome_version being passed."""
632 value = value.strip()
633
634 if parser.values.chrome_rev is None and value:
635 parser.values.chrome_rev = constants.CHROME_REV_SPEC
636
637 parser.values.chrome_version = value
638
639
640def _CheckChromeRootOption(_option, _opt_str, value, parser):
641 """Validate and convert chrome_root to full-path form."""
642 value = value.strip()
643 if not value or value == '/':
644 raise optparse.OptionValueError('Invalid chrome_root specified')
645
646 if parser.values.chrome_rev is None:
647 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
648
649 parser.values.chrome_root = os.path.realpath(os.path.expanduser(value))
650
651
652def _CheckChromeRevOption(_option, _opt_str, value, parser):
653 """Validate the chrome_rev option."""
654 value = value.strip()
655 if value not in constants.VALID_CHROME_REVISIONS:
656 raise optparse.OptionValueError('Invalid chrome rev specified')
657
658 parser.values.chrome_rev = value
659
660
661def _CreateParser():
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700662 class CustomParser(optparse.OptionParser):
663 def add_remote_option(self, *args, **kwargs):
664 """For arguments that are passed-through to remote trybot."""
665 return optparse.OptionParser.add_option(self, *args,
666 remote_pass_through=True,
667 **kwargs)
668
669 class CustomGroup(optparse.OptionGroup):
670 def add_remote_option(self, *args, **kwargs):
671 """For arguments that are passed-through to remote trybot."""
672 return optparse.OptionGroup.add_option(self, *args,
673 remote_pass_through=True,
674 **kwargs)
675
676 class CustomOption(optparse.Option):
677 """Subclass Option class to implement pass-through."""
678 def __init__(self, *args, **kwargs):
679 # The remote_pass_through argument specifies whether we should directly
680 # pass the argument (with its value) onto the remote trybot.
681 self.pass_through = kwargs.pop('remote_pass_through', False)
682 optparse.Option.__init__(self, *args, **kwargs)
683
684 def take_action(self, action, dest, opt, value, values, parser):
685 optparse.Option.take_action(self, action, dest, opt, value, values,
686 parser)
687 if self.pass_through:
688 parser.values.pass_through_args.append(opt)
689 if self.nargs and self.nargs > 1:
690 # value is a tuple if nargs > 1
691 string_list = [str(val) for val in list(value)]
692 parser.values.pass_through_args.extend(string_list)
693 elif value:
694 parser.values.pass_through_args.append(str(value))
695
Brian Harring3fec5a82012-03-01 05:57:03 -0800696 """Generate and return the parser with all the options."""
697 # Parse options
698 usage = "usage: %prog [options] buildbot_config"
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700699 parser = CustomParser(usage=usage, option_class=CustomOption)
Brian Harring3fec5a82012-03-01 05:57:03 -0800700
701 # Main options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700702 # The remote_pass_through parameter to add_option is implemented by the
703 # CustomOption class. See CustomOption for more information.
Brian Harring3fec5a82012-03-01 05:57:03 -0800704 parser.add_option('-a', '--all', action='store_true', dest='print_all',
705 default=False,
706 help=('List all of the buildbot configs available. Use '
707 'with the --list option'))
708 parser.add_option('-r', '--buildroot', action='callback', dest='buildroot',
709 type='string', callback=_CheckBuildRootOption,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700710 help='Root directory where source is checked out to, and '
711 'where the build occurs. For external build configs, '
712 "defaults to 'trybot' directory at top level of your "
713 'repo-managed checkout.')
714 parser.add_remote_option('--chrome_rev', default=None, type='string',
715 action='callback', dest='chrome_rev',
716 callback=_CheckChromeRevOption,
717 help=('Revision of Chrome to use, of type [%s]'
718 % '|'.join(constants.VALID_CHROME_REVISIONS)))
719 parser.add_remote_option('-g', '--gerrit-patches', action='append',
720 default=[], type='string',
721 metavar="'Id1 *int_Id2...IdN'",
722 help=("Space-separated list of short-form Gerrit "
723 "Change-Id's or change numbers to patch. "
724 "Please prepend '*' to internal Change-Id's"))
Brian Harring3fec5a82012-03-01 05:57:03 -0800725 parser.add_option('-l', '--list', action='store_true', dest='list',
726 default=False,
727 help=('List the suggested trybot configs to use. Use '
728 '--all to list all of the available configs.'))
Ryan Cui54da0702012-04-19 18:38:08 -0700729 parser.add_option('--local', default=False, action='store_true',
730 help=('Specifies that this tryjob should be run locally.'))
Ryan Cuicedd8a52012-03-22 02:28:35 -0700731 parser.add_option('-p', '--local-patches', action='append', default=[],
Brian Harring3fec5a82012-03-01 05:57:03 -0800732 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
733 help=('Space-separated list of project branches with '
734 'patches to apply. Projects are specified by name. '
735 'If no branch is specified the current branch of the '
736 'project will be used.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700737 parser.add_remote_option('--profile', default=None, type='string',
738 action='store', dest='profile',
739 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800740 parser.add_option('--remote', default=False, action='store_true',
Brian Harring3fec5a82012-03-01 05:57:03 -0800741 help=('Specifies that this tryjob should be run remotely.'))
742
743 # Advanced options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700744 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800745 parser,
746 'Advanced Options',
747 'Caution: use these options at your own risk.')
748
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700749 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
750 default=False, help='This is running on a buildbot')
751 group.add_remote_option('--buildnumber', help='build number', type='int',
752 default=0)
Brian Harring3fec5a82012-03-01 05:57:03 -0800753 group.add_option('--chrome_root', default=None, type='string',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700754 action='callback', dest='chrome_root',
755 callback=_CheckChromeRootOption,
756 help='Local checkout of Chrome to use.')
757 group.add_remote_option('--chrome_version', default=None, type='string',
758 action='callback', dest='chrome_version',
759 callback=_CheckChromeVersionOption,
760 help='Used with SPEC logic to force a particular SVN '
761 'revision of chrome rather than the latest.')
762 group.add_remote_option('--clobber', action='store_true', dest='clobber',
763 default=False,
764 help='Clears an old checkout before syncing')
765 group.add_remote_option('--lkgm', action='store_true', dest='lkgm',
766 default=False,
767 help='Sync to last known good manifest blessed by '
768 'PFQ')
Brian Harring3fec5a82012-03-01 05:57:03 -0800769 parser.add_option('--log_dir', action='callback', dest='log_dir',
770 type='string', callback=_CheckLogDirOption,
771 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700772 group.add_remote_option('--maxarchives', dest='max_archive_builds',
773 default=3, type='int',
774 help="Change the local saved build count limit.")
775 group.add_remote_option('--noarchive', action='store_false', dest='archive',
776 default=True, help="Don't run archive stage.")
777 group.add_remote_option('--nobuild', action='store_false', dest='build',
778 default=True,
779 help="Don't actually build (for cbuildbot dev)")
780 group.add_remote_option('--noclean', action='store_false', dest='clean',
781 default=True, help="Don't clean the buildroot")
782 group.add_remote_option('--noprebuilts', action='store_false',
783 dest='prebuilts', default=True,
784 help="Don't upload prebuilts.")
785 group.add_remote_option('--nosync', action='store_false', dest='sync',
786 default=True, help="Don't sync before building.")
787 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
788 default=True,
789 help='Disable cbuildbots usage of cgroups.')
790 group.add_remote_option('--notests', action='store_false', dest='tests',
791 default=True,
792 help='Override values from buildconfig and run no '
793 'tests.')
794 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
795 default=True,
796 help='Override values from buildconfig and never '
797 'uprev.')
798 group.add_option('--pass-through', dest='pass_through_args', action='append',
799 type='string', default=[], help=optparse.SUPPRESS_HELP)
Brian Harring3fec5a82012-03-01 05:57:03 -0800800 group.add_option('--reference-repo', action='store', default=None,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700801 dest='reference_repo',
802 help='Reuse git data stored in an existing repo '
803 'checkout. This can drastically reduce the network '
804 'time spent setting up the trybot checkout. By '
805 "default, if this option isn't given but cbuildbot "
806 'is invoked from a repo checkout, cbuildbot will '
807 'use the repo root.')
808 # Indicates this is running on a remote trybot machine.
Ryan Cuiba41ad32012-03-08 17:15:29 -0800809 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700810 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700811 # Patches uploaded by trybot client when run using the -p option.
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700812 group.add_remote_option('--remote-patches', action='append', default=[],
813 help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700814 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700815 help='Skip stages already successfully completed.')
816 group.add_remote_option('--timeout', action='store', type='int', default=0,
817 help='Specify the maximum amount of time this job '
818 'can run for, at which point the build will be '
819 'aborted. If set to zero, then there is no '
820 'timeout.')
Ryan Cui39bdbbf2012-02-29 16:15:39 -0800821 group.add_option('--test-tryjob', action='store_true',
822 default=False,
823 help='Submit a tryjob to the test repository. Will not '
824 'show up on the production trybot waterfall.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700825 group.add_remote_option('--validation_pool', default=None,
826 help='Path to a pickled validation pool. Intended '
827 'for use only with the commit queue.')
828 group.add_remote_option('--version', dest='force_version', default=None,
829 help='Used with manifest logic. Forces use of this '
830 'version rather than create or get latest.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800831
832 parser.add_option_group(group)
833
834 # Debug options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700835 group = CustomGroup(parser, "Debug Options")
Brian Harring3fec5a82012-03-01 05:57:03 -0800836
Ryan Cui85867972012-02-23 18:21:49 -0800837 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800838 help='Override some options to run as a developer.')
839 group.add_option('--dump_config', action='store_true', dest='dump_config',
840 default=False,
841 help='Dump out build config options, and exit.')
842 group.add_option('--notee', action='store_false', dest='tee', default=True,
843 help="Disable logging and internal tee process. Primarily "
844 "used for debugging cbuildbot itself.")
845 parser.add_option_group(group)
846 return parser
847
848
Ryan Cui85867972012-02-23 18:21:49 -0800849def _FinishParsing(options, args):
850 """Perform some parsing tasks that need to take place after optparse.
851
852 This function needs to be easily testable! Keep it free of
853 environment-dependent code. Put more detailed usage validation in
854 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800855
856 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800857 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800858 """
Brian Harring07039b52012-05-13 17:56:47 -0700859 # Setup logging levels first so any parsing triggered log messages
860 # are appropriately filtered.
861 logging.getLogger().setLevel(
862 logging.DEBUG if options.debug else logging.INFO)
863
Brian Harring3fec5a82012-03-01 05:57:03 -0800864 if options.chrome_root:
865 if options.chrome_rev != constants.CHROME_REV_LOCAL:
866 cros_lib.Die('Chrome rev must be %s if chrome_root is set.' %
867 constants.CHROME_REV_LOCAL)
868 else:
869 if options.chrome_rev == constants.CHROME_REV_LOCAL:
870 cros_lib.Die('Chrome root must be set if chrome_rev is %s.' %
871 constants.CHROME_REV_LOCAL)
872
873 if options.chrome_version:
874 if options.chrome_rev != constants.CHROME_REV_SPEC:
875 cros_lib.Die('Chrome rev must be %s if chrome_version is set.' %
876 constants.CHROME_REV_SPEC)
877 else:
878 if options.chrome_rev == constants.CHROME_REV_SPEC:
879 cros_lib.Die('Chrome rev must not be %s if chrome_version is not set.' %
880 constants.CHROME_REV_SPEC)
881
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700882 patches = bool(options.gerrit_patches or options.local_patches)
883 if options.remote:
884 if options.local:
885 cros_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -0700886
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700887 if not options.buildbot and not patches:
888 cros_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800889
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700890 # --debug needs to be explicitly passed through for remote invocations.
891 release_mode_with_patches = (options.buildbot and patches and
892 '--debug' not in options.pass_through_args)
893 else:
894 if len(args) > 1:
895 cros_lib.Die('Multiple configs not supported if not running with '
896 '--remote.')
897
898 release_mode_with_patches = (options.buildbot and patches and
899 not options.debug)
900
901 # When running in release mode, make sure we are running with checked-in code.
902 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
903 # a release image with checked-in code for CrOS packages.
904 if release_mode_with_patches:
905 cros_lib.Die('Cannot provide patches when running with --buildbot!')
Brian Harring3fec5a82012-03-01 05:57:03 -0800906
Ryan Cuiba41ad32012-03-08 17:15:29 -0800907 if options.buildbot and options.remote_trybot:
908 cros_lib.Die('--buildbot and --remote-trybot cannot be used together.')
909
Ryan Cui85867972012-02-23 18:21:49 -0800910 # Record whether --debug was set explicitly vs. it was inferred.
911 options.debug_forced = False
912 if options.debug:
913 options.debug_forced = True
914 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800915 # We don't set debug by default for
916 # 1. --buildbot invocations.
917 # 2. --remote invocations, because it needs to push changes to the tryjob
918 # repo.
919 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -0800920
Brian Harring3fec5a82012-03-01 05:57:03 -0800921
Ryan Cuicedd8a52012-03-22 02:28:35 -0700922def _SplitAndFlatten(appended_items):
923 """Given a list of space-separated items, split into flattened list.
924
925 Given ['abc def', 'hij'] return ['abc', 'def', 'hij'].
926 Arguments:
927 appended_items: List of delimiter-separated items.
928
929 Returns: Flattened list.
930 """
931 new_list = []
932 for item in appended_items:
Mike Frysinger4bd23892012-03-26 15:08:52 -0400933 new_list.extend(item.split())
Ryan Cuicedd8a52012-03-22 02:28:35 -0700934 return new_list
935
936
Brian Harring1d7ba942012-04-24 06:37:18 -0700937# pylint: disable=W0613
Ryan Cui85867972012-02-23 18:21:49 -0800938def _PostParseCheck(options, args):
939 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800940
Ryan Cui85867972012-02-23 18:21:49 -0800941 Args:
942 options/args: The options/args object returned by optparse
943 """
Brian Harring1d7ba942012-04-24 06:37:18 -0700944 if options.resume:
945 return
946
947 options.gerrit_patches = _SplitAndFlatten(options.gerrit_patches)
948 options.remote_patches = _SplitAndFlatten(options.remote_patches)
949 try:
950 # TODO(rcui): Split this into two stages, one that parses, another that
951 # validates. Parsing step will be called by _FinishParsing().
952 options.local_patches = _CheckLocalPatches(
953 _SplitAndFlatten(options.local_patches))
954 except optparse.OptionValueError as e:
955 cros_lib.Die(str(e))
956
957 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
958 if (default and not any([options.local, options.buildbot,
959 options.remote, options.remote_trybot])):
960 cros_lib.Info("CBUILDBOT_DEFAULT_MODE=%s env var detected, using it."
961 % default)
962 default = default.lower()
963 if default == 'local':
964 options.local = True
965 elif default == 'remote':
966 options.remote = True
967 elif default == 'buildbot':
968 options.buildbot = True
969 else:
970 cros_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
971 % default)
Ryan Cui85867972012-02-23 18:21:49 -0800972
973
974def _ParseCommandLine(parser, argv):
975 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800976 (options, args) = parser.parse_args(argv)
Ryan Cui54da0702012-04-19 18:38:08 -0700977 if options.list:
978 _PrintValidConfigs(options.print_all)
979 sys.exit(0)
980
Ryan Cui8be16062012-04-24 12:05:26 -0700981 # Strip out null arguments.
982 # TODO(rcui): Remove when buildbot is fixed
983 args = [arg for arg in args if arg]
984 if not args:
985 parser.error('Invalid usage. Use -h to see usage. Use -l to list '
986 'supported configs.')
987
Ryan Cui85867972012-02-23 18:21:49 -0800988 _FinishParsing(options, args)
989 return options, args
990
991
992def main(argv):
993 # Set umask to 022 so files created by buildbot are readable.
994 os.umask(022)
995
996 if cros_lib.IsInsideChroot():
997 cros_lib.Die('Please run cbuildbot from outside the chroot.')
998
999 parser = _CreateParser()
1000 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -08001001
Brian Harring3fec5a82012-03-01 05:57:03 -08001002 _PostParseCheck(options, args)
1003
1004 if options.remote:
Chris Sosa4f6ffaf2012-05-01 17:05:44 -07001005 cros_lib.logger.setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001006
Brian Harring3fec5a82012-03-01 05:57:03 -08001007 # Verify configs are valid.
1008 for bot in args:
1009 _GetConfig(bot)
1010
1011 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -08001012 print 'Verifying patches...'
Ryan Cuicedd8a52012-03-22 02:28:35 -07001013 _, local_patches = _PreProcessPatches(options.gerrit_patches,
1014 options.local_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001015 # --debug need to be explicitly passed through for remote invocations.
1016 if options.buildbot and '--debug' not in options.pass_through_args:
1017 _ConfirmRemoteBuildbotRun()
1018
Ryan Cui16ca5812012-03-08 20:34:27 -08001019 print 'Submitting tryjob...'
Ryan Cuicedd8a52012-03-22 02:28:35 -07001020 tryjob = remote_try.RemoteTryJob(options, args, local_patches)
Ryan Cui39bdbbf2012-02-29 16:15:39 -08001021 tryjob.Submit(testjob=options.test_tryjob, dryrun=options.debug)
Ryan Cui16ca5812012-03-08 20:34:27 -08001022 print 'Tryjob submitted!'
1023 print ('Go to %s to view the status of your job.'
Ryan Cui4906e1c2012-04-03 20:09:34 -07001024 % tryjob.GetTrybotWaterfallLink())
Brian Harring3fec5a82012-03-01 05:57:03 -08001025 sys.exit(0)
Ryan Cui54da0702012-04-19 18:38:08 -07001026 elif (not options.buildbot and not options.remote_trybot
1027 and not options.resume and not options.local):
1028 cros_lib.Warning('Running in LOCAL TRYBOT mode! Use --remote to submit '
1029 'REMOTE tryjobs. Use --local to suppress this message.')
1030 cros_lib.Warning('Starting April 30th, --local will be required to run the '
1031 'local trybot.')
1032 time.sleep(5)
Brian Harring3fec5a82012-03-01 05:57:03 -08001033
Ryan Cui8be16062012-04-24 12:05:26 -07001034 # Only expecting one config
1035 bot_id = args[-1]
1036 build_config = _GetConfig(bot_id)
Brian Harring3fec5a82012-03-01 05:57:03 -08001037
1038 if options.reference_repo is None:
1039 repo_path = os.path.join(constants.SOURCE_ROOT, '.repo')
1040 # If we're being run from a repo checkout, reuse the repo's git pool to
1041 # cut down on sync time.
1042 if os.path.exists(repo_path):
1043 options.reference_repo = constants.SOURCE_ROOT
1044 elif options.reference_repo:
1045 if not os.path.exists(options.reference_repo):
1046 parser.error('Reference path %s does not exist'
1047 % (options.reference_repo,))
1048 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1049 parser.error('Reference path %s does not look to be the base of a '
1050 'repo checkout; no .repo exists in the root.'
1051 % (options.reference_repo,))
Ryan Cuid4a24212012-04-04 18:08:12 -07001052
Brian Harringf11bf682012-05-14 15:53:43 -07001053 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001054 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001055 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1056 'be used together. Cgroup support is required for '
1057 'buildbot/remote-trybot mode.')
Brian Harring470f6112012-03-02 11:47:10 -08001058 if not cgroups.Cgroup.CgroupsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001059 parser.error('Option --buildbot/--remote-trybot was given, but this '
1060 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001061
Brian Harring351ce442012-03-09 16:38:14 -08001062 missing = []
1063 for program in _BUILDBOT_REQUIRED_BINARIES:
1064 ret = cros_lib.RunCommand('which %s' % program, shell=True,
1065 redirect_stderr=True, redirect_stdout=True,
1066 error_code_ok=True, print_cmd=False)
1067 if ret.returncode != 0:
1068 missing.append(program)
1069
1070 if missing:
Ryan Cuid4a24212012-04-04 18:08:12 -07001071 parser.error("Option --buildbot/--remote-trybot requires the following "
1072 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001073 % (', '.join(missing)))
1074
Brian Harring3fec5a82012-03-01 05:57:03 -08001075 if options.reference_repo:
1076 options.reference_repo = os.path.abspath(options.reference_repo)
1077
1078 if options.dump_config:
1079 # This works, but option ordering is bad...
1080 print 'Configuration %s:' % bot_id
1081 pretty_printer = pprint.PrettyPrinter(indent=2)
1082 pretty_printer.pprint(build_config)
1083 sys.exit(0)
1084
1085 if not options.buildroot:
1086 if options.buildbot:
1087 parser.error('Please specify a buildroot with the --buildroot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001088
Brian Harring470f6112012-03-02 11:47:10 -08001089 options.buildroot = _DetermineDefaultBuildRoot(build_config['internal'])
1090 # We use a marker file in the buildroot to indicate the user has
1091 # consented to using this directory.
1092 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1093 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001094
1095 # Sanity check of buildroot- specifically that it's not pointing into the
1096 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001097 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -08001098 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001099 parser.error('Configured buildroot %s points into a repository checkout, '
1100 'rather than the root of it. This is not supported.'
1101 % options.buildroot)
1102
Brian Harringd166aaf2012-05-14 18:31:53 -07001103 log_file = None
1104 if options.tee:
1105 default_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1106 dirname = options.log_dir or default_dir
1107 log_file = os.path.join(dirname, _BUILDBOT_LOG_FILE)
1108
1109 osutils.SafeMakedirs(dirname)
1110 _BackupPreviousLog(log_file)
1111
Brian Harringc2d09d92012-05-13 22:03:15 -07001112 with cros_lib.ContextManagerStack() as stack:
1113 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1114 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001115
Brian Harringc2d09d92012-05-13 22:03:15 -07001116 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001117 # If we're in resume mode, use our parents tempdir rather than
1118 # nesting another layer.
Brian Harringc2d09d92012-05-13 22:03:15 -07001119 stack.Add(osutils.TempDirContextManager, 'cbuildbot-tmp')
1120 logging.debug("Cbuildbot tempdir is %r.", os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001121
1122 if log_file is not None:
1123 stack.Add(tee.Tee, log_file)
1124 options.preserve_paths = set([_DEFAULT_LOG_DIR])
1125
Brian Harringc2d09d92012-05-13 22:03:15 -07001126 if options.cgroups:
1127 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001128
Brian Harringc2d09d92012-05-13 22:03:15 -07001129 # Mark everything between EnforcedCleanupSection and here as having to
1130 # be rolled back via the contextmanager cleanup handlers. This
1131 # ensures that sudo bits cannot outlive cbuildbot, that anything
1132 # cgroups would kill gets killed, etc.
1133 critical_section.ForkWatchdog()
Brian Harringd166aaf2012-05-14 18:31:53 -07001134
Brian Harringc2d09d92012-05-13 22:03:15 -07001135 if options.timeout > 0:
1136 stack.Add(cros_lib.Timeout, options.timeout)
Brian Harringa184efa2012-03-04 11:51:25 -08001137
Brian Harringc2d09d92012-05-13 22:03:15 -07001138 if not options.buildbot:
1139 build_config = cbuildbot_config.OverrideConfigForTrybot(
1140 build_config,
1141 options.remote_trybot)
1142
1143 _RunBuildStagesWrapper(options, build_config)