blob: aed8a1df83d1b97cd68cd0be3833b76e9ad05254 [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
Ryan Cui16d9e1f2012-05-11 10:50:18 -070034from chromite.buildbot import trybot_patch_pool
Brian Harring3fec5a82012-03-01 05:57:03 -080035
Brian Harringc92a7012012-02-29 10:11:34 -080036from chromite.lib import cgroups
Brian Harringa184efa2012-03-04 11:51:25 -080037from chromite.lib import cleanup
Brian Harring3fec5a82012-03-01 05:57:03 -080038from chromite.lib import cros_build_lib as cros_lib
Brian Harringaf019fb2012-05-10 15:06:13 -070039from chromite.lib import osutils
Brian Harring3fec5a82012-03-01 05:57:03 -080040from chromite.lib import sudo
41
Ryan Cuiadd49122012-03-21 22:19:58 -070042
Brian Harring3fec5a82012-03-01 05:57:03 -080043cros_lib.STRICT_SUDO = True
44
45_DEFAULT_LOG_DIR = 'cbuildbot_logs'
46_BUILDBOT_LOG_FILE = 'cbuildbot.log'
47_DEFAULT_EXT_BUILDROOT = 'trybot'
48_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Matt Tennantf1e30972012-03-02 16:30:07 -080049_PATH_TO_CBUILDBOT = os.path.join(constants.CHROMITE_BIN_SUBDIR, 'cbuildbot')
Brian Harring3fec5a82012-03-01 05:57:03 -080050_DISTRIBUTED_TYPES = [constants.COMMIT_QUEUE_TYPE, constants.PFQ_TYPE,
51 constants.CANARY_TYPE, constants.CHROME_PFQ_TYPE,
52 constants.PALADIN_TYPE]
Brian Harring351ce442012-03-09 16:38:14 -080053_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Brian Harring3fec5a82012-03-01 05:57:03 -080054
55
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070056def _PrintValidConfigs(display_all=False):
Brian Harring3fec5a82012-03-01 05:57:03 -080057 """Print a list of valid buildbot configs.
58
59 Arguments:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070060 display_all: Print all configs. Otherwise, prints only configs with
61 trybot_list=True.
Brian Harring3fec5a82012-03-01 05:57:03 -080062 """
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070063 def _GetSortKey(config_name):
64 config_dict = cbuildbot_config.config[config_name]
65 return (not config_dict['trybot_list'], config_dict['description'],
66 config_name)
67
Brian Harring3fec5a82012-03-01 05:57:03 -080068 COLUMN_WIDTH = 45
69 print 'config'.ljust(COLUMN_WIDTH), 'description'
70 print '------'.ljust(COLUMN_WIDTH), '-----------'
71 config_names = cbuildbot_config.config.keys()
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070072 config_names.sort(key=_GetSortKey)
Brian Harring3fec5a82012-03-01 05:57:03 -080073 for name in config_names:
Ryan Cui4f6cf7e2012-04-18 16:12:27 -070074 if display_all or cbuildbot_config.config[name]['trybot_list']:
75 desc = cbuildbot_config.config[name].get('description')
76 desc = desc if desc else ''
Brian Harring3fec5a82012-03-01 05:57:03 -080077 print name.ljust(COLUMN_WIDTH), desc
78
79
80def _GetConfig(config_name):
81 """Gets the configuration for the build"""
82 if not cbuildbot_config.config.has_key(config_name):
83 print 'Non-existent configuration %s specified.' % config_name
84 print 'Please specify one of:'
85 _PrintValidConfigs()
86 sys.exit(1)
87
88 result = cbuildbot_config.config[config_name]
89
90 return result
91
92
93def _GetChromiteTrackingBranch():
David James66009462012-03-25 10:08:38 -070094 """Returns the remote branch associated with chromite."""
Brian Harring3fec5a82012-03-01 05:57:03 -080095 cwd = os.path.dirname(os.path.realpath(__file__))
David James66009462012-03-25 10:08:38 -070096 branch = cros_lib.GetCurrentBranch(cwd)
97 if branch:
98 tracking_branch = cros_lib.GetTrackingBranch(branch, cwd)[1]
99 if tracking_branch.startswith('refs/heads/'):
100 return tracking_branch.replace('refs/heads/', '')
101 # If we are not on a branch, or if the tracking branch is a revision,
David James8b3c1bf2012-03-28 09:10:16 -0700102 # use the push branch. For repo repositories, this will be the manifest
103 # branch configured for this project. For other repositories, we'll just
104 # guess 'master', since there's no easy way to find out what branch
105 # we're on.
106 return cros_lib.GetPushBranch(cwd)[1]
Brian Harring3fec5a82012-03-01 05:57:03 -0800107
108
109def _CheckBuildRootBranch(buildroot, tracking_branch):
110 """Make sure buildroot branch is the same as Chromite branch."""
111 manifest_branch = cros_lib.GetManifestDefaultBranch(buildroot)
112 if manifest_branch != tracking_branch:
113 cros_lib.Die('Chromite is not on same branch as buildroot checkout\n' +
114 'Chromite is on branch %s.\n' % tracking_branch +
115 'Buildroot checked out to %s\n' % manifest_branch)
116
117
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700118def AcquirePoolFromOptions(options, target_manifest_branch):
119 """Generate patch objects from passed in options.
Brian Harring3fec5a82012-03-01 05:57:03 -0800120
121 Args:
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700122 options: The options object generated by optparse.
Brian Harring3fec5a82012-03-01 05:57:03 -0800123
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700124 Raises:
125 gerrit_helper.GerritException, cros_patch.PatchException
Brian Harring3fec5a82012-03-01 05:57:03 -0800126 """
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700127 gerrit_patches = []
128 local_patches = []
129 remote_patches = []
Brian Harring3fec5a82012-03-01 05:57:03 -0800130
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700131 if options.gerrit_patches:
132 gerrit_patches = gerrit_helper.GetGerritPatchInfo(
133 options.gerrit_patches)
134 for patch in gerrit_patches:
135 if patch.IsAlreadyMerged():
136 cros_lib.Warning('Patch %s has already been merged.' % str(patch))
Brian Harring3fec5a82012-03-01 05:57:03 -0800137
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700138 if options.local_patches:
139 local_patches = cros_patch.PrepareLocalPatches(
140 options.local_patches,
141 target_manifest_branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800142
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700143 if options.remote_patches:
144 remote_patches = cros_patch.PrepareRemotePatches(
145 options.remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800146
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700147 return trybot_patch_pool.TrybotPatchPool(gerrit_patches, local_patches,
148 remote_patches)
Brian Harring3fec5a82012-03-01 05:57:03 -0800149
150
151def _IsIncrementalBuild(buildroot, clobber):
152 """Returns True if we are reusing an existing buildroot."""
153 repo_dir = os.path.join(buildroot, '.repo')
154 return not clobber and os.path.isdir(repo_dir)
155
156
157class Builder(object):
158 """Parent class for all builder types.
159
160 This class functions as a parent class for various build types. It's intended
161 use is builder_instance.Run().
162
163 Vars:
Brian Harring3fec5a82012-03-01 05:57:03 -0800164 build_config: The configuration dictionary from cbuildbot_config.
165 options: The options provided from optparse in main().
166 completed_stages_file: Where we store resume state.
167 archive_url: Where our artifacts for this builder will be archived.
168 tracking_branch: The tracking branch for this build.
169 release_tag: The associated "chrome os version" of this build.
170 gerrit_patches: Gerrit patches to be included in build.
171 local_patches: Local patches to be included in build.
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700172 remote_patches: Uploaded local patches to be included in build.
Brian Harring3fec5a82012-03-01 05:57:03 -0800173 """
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()
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700190 self.patch_pool = trybot_patch_pool.GetEmptyPool()
Brian Harring3fec5a82012-03-01 05:57:03 -0800191
192 def Initialize(self):
193 """Runs through the initialization steps of an actual build."""
194 if self.options.resume and os.path.exists(self.completed_stages_file):
195 with open(self.completed_stages_file, 'r') as load_file:
196 results_lib.Results.RestoreCompletedStages(load_file)
197
198 # We only want to do this if we need to patch changes.
199 if not results_lib.Results.GetPrevious().get(
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700200 stages.PatchChangesStage.StageNamePrefix()):
201 self.patch_pool = AcquirePoolFromOptions(self.options,
202 self.target_manifest_branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800203
Brian Harringeb237932012-05-07 02:08:06 -0700204 bs.BuilderStage.SetManifestBranch(self.target_manifest_branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800205
206 # Check branch matching early.
207 if _IsIncrementalBuild(self.options.buildroot, self.options.clobber):
Brian Harringeb237932012-05-07 02:08:06 -0700208 _CheckBuildRootBranch(self.options.buildroot, self.target_manifest_branch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800209
210 self._RunStage(stages.CleanUpStage)
211
212 def _GetStageInstance(self, stage, *args, **kwargs):
213 """Helper function to get an instance given the args.
214
David James944a48e2012-03-07 12:19:03 -0800215 Useful as almost all stages just take in options and build_config.
Brian Harring3fec5a82012-03-01 05:57:03 -0800216 """
David James944a48e2012-03-07 12:19:03 -0800217 config = kwargs.pop('config', self.build_config)
218 return stage(self.options, config, *args, **kwargs)
Brian Harring3fec5a82012-03-01 05:57:03 -0800219
220 def _SetReleaseTag(self):
221 """Sets the release tag from the manifest_manager.
222
223 Must be run after sync stage as syncing enables us to have a release tag.
224 """
225 # Extract version we have decided to build into self.release_tag.
226 manifest_manager = stages.ManifestVersionedSyncStage.manifest_manager
227 if manifest_manager:
228 self.release_tag = manifest_manager.current_version
229
230 def _RunStage(self, stage, *args, **kwargs):
231 """Wrapper to run a stage."""
232 stage_instance = self._GetStageInstance(stage, *args, **kwargs)
233 return stage_instance.Run()
234
235 def GetSyncInstance(self):
236 """Returns an instance of a SyncStage that should be run.
237
238 Subclasses must override this method.
239 """
240 raise NotImplementedError()
241
242 def RunStages(self):
243 """Subclasses must override this method. Runs the appropriate code."""
244 raise NotImplementedError()
245
246 def _WriteCheckpoint(self):
247 """Drops a completed stages file with current state."""
248 with open(self.completed_stages_file, 'w+') as save_file:
249 results_lib.Results.SaveCompletedStages(save_file)
250
251 def _ShouldReExecuteInBuildRoot(self):
252 """Returns True if this build should be re-executed in the buildroot."""
253 abs_buildroot = os.path.abspath(self.options.buildroot)
254 return not os.path.abspath(__file__).startswith(abs_buildroot)
255
256 def _ReExecuteInBuildroot(self, sync_instance):
257 """Reexecutes self in buildroot and returns True if build succeeds.
258
259 This allows the buildbot code to test itself when changes are patched for
260 buildbot-related code. This is a no-op if the buildroot == buildroot
261 of the running chromite checkout.
262
263 Args:
264 sync_instance: Instance of the sync stage that was run to sync.
265
266 Returns:
267 True if the Build succeeded.
268 """
269 # If we are resuming, use last checkpoint.
270 if not self.options.resume:
271 self._WriteCheckpoint()
272
273 # Re-write paths to use absolute paths.
274 # Suppress any timeout options given from the commandline in the
275 # invoked cbuildbot; our timeout will enforce it instead.
Brian Harringf11bf682012-05-14 15:53:43 -0700276 args_to_append = ['--resume', '--timeout', '0', '--notee', '--nocgroups',
277 '--buildroot', os.path.abspath(self.options.buildroot)]
Brian Harring3fec5a82012-03-01 05:57:03 -0800278
279 if self.options.chrome_root:
280 args_to_append += ['--chrome_root',
281 os.path.abspath(self.options.chrome_root)]
282
283 if stages.ManifestVersionedSyncStage.manifest_manager:
284 ver = stages.ManifestVersionedSyncStage.manifest_manager.current_version
285 args_to_append += ['--version', ver]
286
287 if isinstance(sync_instance, stages.CommitQueueSyncStage):
288 vp_file = sync_instance.SaveValidationPool()
289 args_to_append += ['--validation_pool', vp_file]
290
291 # Re-run the command in the buildroot.
292 # Finally, be generous and give the invoked cbuildbot 30s to shutdown
293 # when something occurs. It should exit quicker, but the sigterm may
294 # hit while the system is particularly busy.
295 return_obj = cros_lib.RunCommand(
296 [_PATH_TO_CBUILDBOT] + sys.argv[1:] + args_to_append,
297 cwd=self.options.buildroot, error_code_ok=True, kill_timeout=30)
298 return return_obj.returncode == 0
299
300 def Run(self):
301 """Main runner for this builder class. Runs build and prints summary."""
302 print_report = True
David James3d4d3502012-04-09 15:12:06 -0700303 exception_thrown = False
Brian Harring3fec5a82012-03-01 05:57:03 -0800304 success = True
305 try:
306 self.Initialize()
307 sync_instance = self.GetSyncInstance()
308 sync_instance.Run()
309 self._SetReleaseTag()
310
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700311 if self.patch_pool:
312 self._RunStage(stages.PatchChangesStage, self.patch_pool)
Brian Harring3fec5a82012-03-01 05:57:03 -0800313
314 if self._ShouldReExecuteInBuildRoot():
315 print_report = False
316 success = self._ReExecuteInBuildroot(sync_instance)
317 else:
318 self.RunStages()
David James3d4d3502012-04-09 15:12:06 -0700319 except Exception:
320 exception_thrown = True
321 raise
Brian Harring3fec5a82012-03-01 05:57:03 -0800322 finally:
323 if print_report:
324 self._WriteCheckpoint()
325 print '\n\n\n@@@BUILD_STEP Report@@@\n'
326 results_lib.Results.Report(sys.stdout, self.archive_urls,
327 self.release_tag)
328 success = results_lib.Results.BuildSucceededSoFar()
David James3d4d3502012-04-09 15:12:06 -0700329 if exception_thrown and success:
330 success = False
331 print >> sys.stderr, """
332@@@STEP_FAILURE@@@
333Exception thrown, but all stages marked successful. This is an internal error,
334because the stage that threw the exception should be marked as failing."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800335
336 return success
337
338
339class SimpleBuilder(Builder):
340 """Builder that performs basic vetting operations."""
341
342 def GetSyncInstance(self):
343 """Sync to lkgm or TOT as necessary.
344
345 Returns: the instance of the sync stage that was run.
346 """
347 if self.options.lkgm or self.build_config['use_lkgm']:
348 sync_stage = self._GetStageInstance(stages.LKGMSyncStage)
349 else:
350 sync_stage = self._GetStageInstance(stages.SyncStage)
351
352 return sync_stage
353
David James58e0c092012-03-04 20:31:12 -0800354 def _RunBackgroundStagesForBoard(self, board):
355 """Run background board-specific stages for the specified board."""
David James58e0c092012-03-04 20:31:12 -0800356 archive_stage = self.archive_stages[board]
David James944a48e2012-03-07 12:19:03 -0800357 configs = self.build_config['board_specific_configs']
358 config = configs.get(board, self.build_config)
359 stage_list = [[stages.VMTestStage, board, archive_stage],
360 [stages.ChromeTestStage, board, archive_stage],
361 [stages.UnitTestStage, board],
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700362 [stages.UploadPrebuiltsStage, board, archive_stage]]
Brian Harring3fec5a82012-03-01 05:57:03 -0800363
David James58e0c092012-03-04 20:31:12 -0800364 # We can not run hw tests without archiving the payloads.
365 if self.options.archive:
David James944a48e2012-03-07 12:19:03 -0800366 for suite in config['hw_tests']:
367 stage_list.append([stages.HWTestStage, board, archive_stage, suite])
Chris Sosab50dc932012-03-01 14:00:58 -0800368
David James944a48e2012-03-07 12:19:03 -0800369 steps = [self._GetStageInstance(*x, config=config).Run for x in stage_list]
370 background.RunParallelSteps(steps + [archive_stage.Run])
Brian Harring3fec5a82012-03-01 05:57:03 -0800371
372 def RunStages(self):
373 """Runs through build process."""
374 self._RunStage(stages.BuildBoardStage)
375
376 # TODO(sosa): Split these out into classes.
Brian Harring3fec5a82012-03-01 05:57:03 -0800377 if self.build_config['build_type'] == constants.CHROOT_BUILDER_TYPE:
378 self._RunStage(stages.SDKTestStage)
379 self._RunStage(stages.UploadPrebuiltsStage,
Chris Sosa6a5dceb2012-05-14 13:48:56 -0700380 constants.CHROOT_BUILDER_BOARD, None)
Brian Harring3fec5a82012-03-01 05:57:03 -0800381 elif self.build_config['build_type'] == constants.REFRESH_PACKAGES_TYPE:
382 self._RunStage(stages.RefreshPackageStatusStage)
383 else:
384 self._RunStage(stages.UprevStage)
Brian Harring3fec5a82012-03-01 05:57:03 -0800385
David James944a48e2012-03-07 12:19:03 -0800386 configs = self.build_config['board_specific_configs']
David James58e0c092012-03-04 20:31:12 -0800387 for board in self.build_config['boards']:
David James944a48e2012-03-07 12:19:03 -0800388 config = configs.get(board, self.build_config)
389 archive_stage = self._GetStageInstance(stages.ArchiveStage, board,
390 config=config)
David James58e0c092012-03-04 20:31:12 -0800391 self.archive_stages[board] = archive_stage
392
David James944a48e2012-03-07 12:19:03 -0800393 # Set up a process pool to run test/archive stages in the background.
394 # This process runs task(board) for each board added to the queue.
David James58e0c092012-03-04 20:31:12 -0800395 queue = multiprocessing.Queue()
396 task = self._RunBackgroundStagesForBoard
397 with background.BackgroundTaskRunner(queue, task):
David James944a48e2012-03-07 12:19:03 -0800398 for board in self.build_config['boards']:
David James58e0c092012-03-04 20:31:12 -0800399 # Run BuildTarget in the foreground.
David James944a48e2012-03-07 12:19:03 -0800400 archive_stage = self.archive_stages[board]
401 config = configs.get(board, self.build_config)
402 self._RunStage(stages.BuildTargetStage, board, archive_stage,
Chris Sosa1a87b3e2012-04-12 13:20:42 -0700403 self.release_tag, config=config)
David James58e0c092012-03-04 20:31:12 -0800404 self.archive_urls[board] = archive_stage.GetDownloadUrl()
405
David James944a48e2012-03-07 12:19:03 -0800406 # Kick off task(board) in the background.
David James58e0c092012-03-04 20:31:12 -0800407 queue.put([board])
408
Brian Harring3fec5a82012-03-01 05:57:03 -0800409
410class DistributedBuilder(SimpleBuilder):
411 """Build class that has special logic to handle distributed builds.
412
413 These builds sync using git/manifest logic in manifest_versions. In general
414 they use a non-distributed builder code for the bulk of the work.
415 """
David James944a48e2012-03-07 12:19:03 -0800416 def __init__(self, options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800417 """Initializes a buildbot builder.
418
419 Extra variables:
420 completion_stage_class: Stage used to complete a build. Set in the Sync
421 stage.
422 """
David James944a48e2012-03-07 12:19:03 -0800423 super(DistributedBuilder, self).__init__(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800424 self.completion_stage_class = None
425
426 def GetSyncInstance(self):
427 """Syncs the tree using one of the distributed sync logic paths.
428
429 Returns: the instance of the sync stage that was run.
430 """
431 # Determine sync class to use. CQ overrides PFQ bits so should check it
432 # first.
433 if cbuildbot_config.IsCQType(self.build_config['build_type']):
434 sync_stage = self._GetStageInstance(stages.CommitQueueSyncStage)
435 self.completion_stage_class = stages.CommitQueueCompletionStage
436 elif cbuildbot_config.IsPFQType(self.build_config['build_type']):
437 sync_stage = self._GetStageInstance(stages.LKGMCandidateSyncStage)
438 self.completion_stage_class = stages.LKGMCandidateSyncCompletionStage
439 else:
440 sync_stage = self._GetStageInstance(stages.ManifestVersionedSyncStage)
441 self.completion_stage_class = stages.ManifestVersionedSyncCompletionStage
442
443 return sync_stage
444
445 def Publish(self, was_build_successful):
446 """Completes build by publishing any required information."""
447 completion_stage = self._GetStageInstance(self.completion_stage_class,
448 was_build_successful)
449 completion_stage.Run()
450 name = completion_stage.name
451 if not results_lib.Results.WasStageSuccessful(name):
452 should_publish_changes = False
453 else:
454 should_publish_changes = (self.build_config['master'] and
455 was_build_successful)
456
457 if should_publish_changes:
458 self._RunStage(stages.PublishUprevChangesStage)
459
460 def RunStages(self):
461 """Runs simple builder logic and publishes information to overlays."""
462 was_build_successful = False
463 try:
David Jamesf55709e2012-03-13 09:10:15 -0700464 super(DistributedBuilder, self).RunStages()
465 was_build_successful = results_lib.Results.BuildSucceededSoFar()
Brian Harring3fec5a82012-03-01 05:57:03 -0800466 except SystemExit as ex:
467 # If a stage calls sys.exit(0), it's exiting with success, so that means
468 # we should mark ourselves as successful.
469 if ex.code == 0:
470 was_build_successful = True
471 raise
472 finally:
473 self.Publish(was_build_successful)
474
Brian Harring3fec5a82012-03-01 05:57:03 -0800475
476def _ConfirmBuildRoot(buildroot):
477 """Confirm with user the inferred buildroot, and mark it as confirmed."""
478 warning = 'Using default directory %s as buildroot' % buildroot
479 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
480 full=True)
481 if response == cros_lib.NO:
482 print('Please specify a buildroot with the --buildroot option.')
483 sys.exit(0)
484
485 if not os.path.exists(buildroot):
486 os.mkdir(buildroot)
487
488 repository.CreateTrybotMarker(buildroot)
489
490
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700491def _ConfirmRemoteBuildbotRun():
492 """Confirm user wants to run with --buildbot --remote."""
493 warning = ('You are about to launch a PRODUCTION job! This is *NOT* a '
494 'trybot run! Are you sure?')
495 response = cros_lib.YesNoPrompt(default=cros_lib.NO, warning=warning,
496 full=True)
497
498 if response == cros_lib.NO:
499 print('Please specify --pass-through="--debug".')
500 sys.exit(0)
501
502
Brian Harring3fec5a82012-03-01 05:57:03 -0800503def _DetermineDefaultBuildRoot(internal_build):
504 """Default buildroot to be under the directory that contains current checkout.
505
506 Arguments:
507 internal_build: Whether the build is an internal build
508 """
509 repo_dir = cros_lib.FindRepoDir()
510 if not repo_dir:
511 cros_lib.Die('Could not find root of local checkout. Please specify'
512 'using --buildroot option.')
513
514 # Place trybot buildroot under the directory containing current checkout.
515 top_level = os.path.dirname(os.path.realpath(os.path.dirname(repo_dir)))
516 if internal_build:
517 buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
518 else:
519 buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
520
521 return buildroot
522
523
524def _BackupPreviousLog(log_file, backup_limit=25):
525 """Rename previous log.
526
527 Args:
528 log_file: The absolute path to the previous log.
529 """
530 if os.path.exists(log_file):
531 old_logs = sorted(glob.glob(log_file + '.*'),
532 key=distutils.version.LooseVersion)
533
534 if len(old_logs) >= backup_limit:
535 os.remove(old_logs[0])
536
537 last = 0
538 if old_logs:
539 last = int(old_logs.pop().rpartition('.')[2])
540
541 os.rename(log_file, log_file + '.' + str(last + 1))
542
543
David James944a48e2012-03-07 12:19:03 -0800544def _RunBuildStagesWrapper(options, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800545 """Helper function that wraps RunBuildStages()."""
546 def IsDistributedBuilder():
547 """Determines whether the build_config should be a DistributedBuilder."""
548 if not options.buildbot:
549 return False
550 elif build_config['build_type'] in _DISTRIBUTED_TYPES:
551 chrome_rev = build_config['chrome_rev']
552 if options.chrome_rev: chrome_rev = options.chrome_rev
553 # We don't do distributed logic to TOT Chrome PFQ's, nor local
554 # chrome roots (e.g. chrome try bots)
555 if chrome_rev not in [constants.CHROME_REV_TOT,
556 constants.CHROME_REV_LOCAL,
557 constants.CHROME_REV_SPEC]:
558 return True
559
560 return False
561
Brian Harringd166aaf2012-05-14 18:31:53 -0700562 cros_lib.Info("cbuildbot executed with args %s"
563 % ' '.join(map(repr, sys.argv)))
564 if IsDistributedBuilder():
565 buildbot = DistributedBuilder(options, build_config)
566 else:
567 buildbot = SimpleBuilder(options, build_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800568
Brian Harringd166aaf2012-05-14 18:31:53 -0700569 if not buildbot.Run():
570 sys.exit(1)
Brian Harring3fec5a82012-03-01 05:57:03 -0800571
572
573# Parser related functions
Ryan Cuicedd8a52012-03-22 02:28:35 -0700574def _CheckLocalPatches(local_patches):
Brian Harring3fec5a82012-03-01 05:57:03 -0800575 """Do an early quick check of the passed-in patches.
576
577 If the branch of a project is not specified we append the current branch the
578 project is on.
579 """
Ryan Cuicedd8a52012-03-22 02:28:35 -0700580 verified_patches = []
581 for patch in local_patches:
Brian Harring3fec5a82012-03-01 05:57:03 -0800582 components = patch.split(':')
583 if len(components) > 2:
584 msg = 'Specify local patches in project[:branch] format.'
585 raise optparse.OptionValueError(msg)
586
587 # validate project
588 project = components[0]
589 if not cros_lib.DoesProjectExist('.', project):
590 raise optparse.OptionValueError('Project %s does not exist.' % project)
591
592 project_dir = cros_lib.GetProjectDir('.', project)
593
594 # If no branch was specified, we use the project's current branch.
595 if len(components) == 1:
596 branch = cros_lib.GetCurrentBranch(project_dir)
597 if not branch:
598 raise optparse.OptionValueError('project %s is not on a branch!'
599 % project)
600 # Append branch information to patch
601 patch = '%s:%s' % (project, branch)
602 else:
603 branch = components[1]
604 if not cros_lib.DoesLocalBranchExist(project_dir, branch):
605 raise optparse.OptionValueError('Project %s does not have branch %s'
606 % (project, branch))
607
Ryan Cuicedd8a52012-03-22 02:28:35 -0700608 verified_patches.append(patch)
Brian Harring3fec5a82012-03-01 05:57:03 -0800609
Ryan Cuicedd8a52012-03-22 02:28:35 -0700610 return verified_patches
Brian Harring3fec5a82012-03-01 05:57:03 -0800611
612
613def _CheckBuildRootOption(_option, _opt_str, value, parser):
614 """Validate and convert buildroot to full-path form."""
615 value = value.strip()
616 if not value or value == '/':
617 raise optparse.OptionValueError('Invalid buildroot specified')
618
619 parser.values.buildroot = os.path.realpath(os.path.expanduser(value))
620
621
622def _CheckLogDirOption(_option, _opt_str, value, parser):
623 """Validate and convert buildroot to full-path form."""
624 parser.values.log_dir = os.path.abspath(os.path.expanduser(value))
625
626
627def _CheckChromeVersionOption(_option, _opt_str, value, parser):
628 """Upgrade other options based on chrome_version being passed."""
629 value = value.strip()
630
631 if parser.values.chrome_rev is None and value:
632 parser.values.chrome_rev = constants.CHROME_REV_SPEC
633
634 parser.values.chrome_version = value
635
636
637def _CheckChromeRootOption(_option, _opt_str, value, parser):
638 """Validate and convert chrome_root to full-path form."""
639 value = value.strip()
640 if not value or value == '/':
641 raise optparse.OptionValueError('Invalid chrome_root specified')
642
643 if parser.values.chrome_rev is None:
644 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
645
646 parser.values.chrome_root = os.path.realpath(os.path.expanduser(value))
647
648
649def _CheckChromeRevOption(_option, _opt_str, value, parser):
650 """Validate the chrome_rev option."""
651 value = value.strip()
652 if value not in constants.VALID_CHROME_REVISIONS:
653 raise optparse.OptionValueError('Invalid chrome rev specified')
654
655 parser.values.chrome_rev = value
656
657
658def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700659 """Generate and return the parser with all the options."""
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700660 class CustomParser(optparse.OptionParser):
661 def add_remote_option(self, *args, **kwargs):
662 """For arguments that are passed-through to remote trybot."""
663 return optparse.OptionParser.add_option(self, *args,
664 remote_pass_through=True,
665 **kwargs)
666
667 class CustomGroup(optparse.OptionGroup):
668 def add_remote_option(self, *args, **kwargs):
669 """For arguments that are passed-through to remote trybot."""
670 return optparse.OptionGroup.add_option(self, *args,
671 remote_pass_through=True,
672 **kwargs)
673
674 class CustomOption(optparse.Option):
675 """Subclass Option class to implement pass-through."""
676 def __init__(self, *args, **kwargs):
677 # The remote_pass_through argument specifies whether we should directly
678 # pass the argument (with its value) onto the remote trybot.
679 self.pass_through = kwargs.pop('remote_pass_through', False)
680 optparse.Option.__init__(self, *args, **kwargs)
681
682 def take_action(self, action, dest, opt, value, values, parser):
683 optparse.Option.take_action(self, action, dest, opt, value, values,
684 parser)
685 if self.pass_through:
686 parser.values.pass_through_args.append(opt)
687 if self.nargs and self.nargs > 1:
688 # value is a tuple if nargs > 1
689 string_list = [str(val) for val in list(value)]
690 parser.values.pass_through_args.extend(string_list)
691 elif value:
692 parser.values.pass_through_args.append(str(value))
693
Brian Harring3fec5a82012-03-01 05:57:03 -0800694 # Parse options
695 usage = "usage: %prog [options] buildbot_config"
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700696 parser = CustomParser(usage=usage, option_class=CustomOption)
Brian Harring3fec5a82012-03-01 05:57:03 -0800697
698 # Main options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700699 # The remote_pass_through parameter to add_option is implemented by the
700 # CustomOption class. See CustomOption for more information.
Brian Harring3fec5a82012-03-01 05:57:03 -0800701 parser.add_option('-a', '--all', action='store_true', dest='print_all',
702 default=False,
703 help=('List all of the buildbot configs available. Use '
704 'with the --list option'))
705 parser.add_option('-r', '--buildroot', action='callback', dest='buildroot',
706 type='string', callback=_CheckBuildRootOption,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700707 help='Root directory where source is checked out to, and '
708 'where the build occurs. For external build configs, '
709 "defaults to 'trybot' directory at top level of your "
710 'repo-managed checkout.')
711 parser.add_remote_option('--chrome_rev', default=None, type='string',
712 action='callback', dest='chrome_rev',
713 callback=_CheckChromeRevOption,
714 help=('Revision of Chrome to use, of type [%s]'
715 % '|'.join(constants.VALID_CHROME_REVISIONS)))
716 parser.add_remote_option('-g', '--gerrit-patches', action='append',
717 default=[], type='string',
718 metavar="'Id1 *int_Id2...IdN'",
719 help=("Space-separated list of short-form Gerrit "
720 "Change-Id's or change numbers to patch. "
721 "Please prepend '*' to internal Change-Id's"))
Brian Harring3fec5a82012-03-01 05:57:03 -0800722 parser.add_option('-l', '--list', action='store_true', dest='list',
723 default=False,
724 help=('List the suggested trybot configs to use. Use '
725 '--all to list all of the available configs.'))
Ryan Cui54da0702012-04-19 18:38:08 -0700726 parser.add_option('--local', default=False, action='store_true',
727 help=('Specifies that this tryjob should be run locally.'))
Ryan Cuicedd8a52012-03-22 02:28:35 -0700728 parser.add_option('-p', '--local-patches', action='append', default=[],
Brian Harring3fec5a82012-03-01 05:57:03 -0800729 metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
730 help=('Space-separated list of project branches with '
731 'patches to apply. Projects are specified by name. '
732 'If no branch is specified the current branch of the '
733 'project will be used.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700734 parser.add_remote_option('--profile', default=None, type='string',
735 action='store', dest='profile',
736 help='Name of profile to sub-specify board variant.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800737 parser.add_option('--remote', default=False, action='store_true',
Brian Harring3fec5a82012-03-01 05:57:03 -0800738 help=('Specifies that this tryjob should be run remotely.'))
739
740 # Advanced options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700741 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800742 parser,
743 'Advanced Options',
744 'Caution: use these options at your own risk.')
745
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700746 group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
747 default=False, help='This is running on a buildbot')
748 group.add_remote_option('--buildnumber', help='build number', type='int',
749 default=0)
Brian Harring3fec5a82012-03-01 05:57:03 -0800750 group.add_option('--chrome_root', default=None, type='string',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700751 action='callback', dest='chrome_root',
752 callback=_CheckChromeRootOption,
753 help='Local checkout of Chrome to use.')
754 group.add_remote_option('--chrome_version', default=None, type='string',
755 action='callback', dest='chrome_version',
756 callback=_CheckChromeVersionOption,
757 help='Used with SPEC logic to force a particular SVN '
758 'revision of chrome rather than the latest.')
759 group.add_remote_option('--clobber', action='store_true', dest='clobber',
760 default=False,
761 help='Clears an old checkout before syncing')
762 group.add_remote_option('--lkgm', action='store_true', dest='lkgm',
763 default=False,
764 help='Sync to last known good manifest blessed by '
765 'PFQ')
Brian Harring3fec5a82012-03-01 05:57:03 -0800766 parser.add_option('--log_dir', action='callback', dest='log_dir',
767 type='string', callback=_CheckLogDirOption,
768 help=('Directory where logs are stored.'))
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700769 group.add_remote_option('--maxarchives', dest='max_archive_builds',
770 default=3, type='int',
771 help="Change the local saved build count limit.")
772 group.add_remote_option('--noarchive', action='store_false', dest='archive',
773 default=True, help="Don't run archive stage.")
774 group.add_remote_option('--nobuild', action='store_false', dest='build',
775 default=True,
776 help="Don't actually build (for cbuildbot dev)")
777 group.add_remote_option('--noclean', action='store_false', dest='clean',
778 default=True, help="Don't clean the buildroot")
779 group.add_remote_option('--noprebuilts', action='store_false',
780 dest='prebuilts', default=True,
781 help="Don't upload prebuilts.")
782 group.add_remote_option('--nosync', action='store_false', dest='sync',
783 default=True, help="Don't sync before building.")
784 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
785 default=True,
786 help='Disable cbuildbots usage of cgroups.')
787 group.add_remote_option('--notests', action='store_false', dest='tests',
788 default=True,
789 help='Override values from buildconfig and run no '
790 'tests.')
791 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
792 default=True,
793 help='Override values from buildconfig and never '
794 'uprev.')
795 group.add_option('--pass-through', dest='pass_through_args', action='append',
796 type='string', default=[], help=optparse.SUPPRESS_HELP)
Brian Harring3fec5a82012-03-01 05:57:03 -0800797 group.add_option('--reference-repo', action='store', default=None,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700798 dest='reference_repo',
799 help='Reuse git data stored in an existing repo '
800 'checkout. This can drastically reduce the network '
801 'time spent setting up the trybot checkout. By '
802 "default, if this option isn't given but cbuildbot "
803 'is invoked from a repo checkout, cbuildbot will '
804 'use the repo root.')
805 # Indicates this is running on a remote trybot machine.
Ryan Cuiba41ad32012-03-08 17:15:29 -0800806 group.add_option('--remote-trybot', dest='remote_trybot', action='store_true',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700807 default=False, help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700808 # Patches uploaded by trybot client when run using the -p option.
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700809 group.add_remote_option('--remote-patches', action='append', default=[],
810 help=optparse.SUPPRESS_HELP)
Ryan Cuicedd8a52012-03-22 02:28:35 -0700811 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700812 help='Skip stages already successfully completed.')
813 group.add_remote_option('--timeout', action='store', type='int', default=0,
814 help='Specify the maximum amount of time this job '
815 'can run for, at which point the build will be '
816 'aborted. If set to zero, then there is no '
817 'timeout.')
Ryan Cui39bdbbf2012-02-29 16:15:39 -0800818 group.add_option('--test-tryjob', action='store_true',
819 default=False,
820 help='Submit a tryjob to the test repository. Will not '
821 'show up on the production trybot waterfall.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700822 group.add_remote_option('--validation_pool', default=None,
823 help='Path to a pickled validation pool. Intended '
824 'for use only with the commit queue.')
825 group.add_remote_option('--version', dest='force_version', default=None,
826 help='Used with manifest logic. Forces use of this '
827 'version rather than create or get latest.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800828
829 parser.add_option_group(group)
830
831 # Debug options
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700832 group = CustomGroup(parser, "Debug Options")
Brian Harring3fec5a82012-03-01 05:57:03 -0800833
Ryan Cui85867972012-02-23 18:21:49 -0800834 group.add_option('--debug', action='store_true', default=None,
Brian Harring3fec5a82012-03-01 05:57:03 -0800835 help='Override some options to run as a developer.')
836 group.add_option('--dump_config', action='store_true', dest='dump_config',
837 default=False,
838 help='Dump out build config options, and exit.')
839 group.add_option('--notee', action='store_false', dest='tee', default=True,
840 help="Disable logging and internal tee process. Primarily "
841 "used for debugging cbuildbot itself.")
842 parser.add_option_group(group)
843 return parser
844
845
Ryan Cui85867972012-02-23 18:21:49 -0800846def _FinishParsing(options, args):
847 """Perform some parsing tasks that need to take place after optparse.
848
849 This function needs to be easily testable! Keep it free of
850 environment-dependent code. Put more detailed usage validation in
851 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800852
853 Args:
Ryan Cui85867972012-02-23 18:21:49 -0800854 options, args: The options/args object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800855 """
Brian Harring07039b52012-05-13 17:56:47 -0700856 # Setup logging levels first so any parsing triggered log messages
857 # are appropriately filtered.
858 logging.getLogger().setLevel(
859 logging.DEBUG if options.debug else logging.INFO)
860
Brian Harring3fec5a82012-03-01 05:57:03 -0800861 if options.chrome_root:
862 if options.chrome_rev != constants.CHROME_REV_LOCAL:
863 cros_lib.Die('Chrome rev must be %s if chrome_root is set.' %
864 constants.CHROME_REV_LOCAL)
865 else:
866 if options.chrome_rev == constants.CHROME_REV_LOCAL:
867 cros_lib.Die('Chrome root must be set if chrome_rev is %s.' %
868 constants.CHROME_REV_LOCAL)
869
870 if options.chrome_version:
871 if options.chrome_rev != constants.CHROME_REV_SPEC:
872 cros_lib.Die('Chrome rev must be %s if chrome_version is set.' %
873 constants.CHROME_REV_SPEC)
874 else:
875 if options.chrome_rev == constants.CHROME_REV_SPEC:
876 cros_lib.Die('Chrome rev must not be %s if chrome_version is not set.' %
877 constants.CHROME_REV_SPEC)
878
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700879 patches = bool(options.gerrit_patches or options.local_patches)
880 if options.remote:
881 if options.local:
882 cros_lib.Die('Cannot specify both --remote and --local')
Ryan Cui54da0702012-04-19 18:38:08 -0700883
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700884 if not options.buildbot and not patches:
885 cros_lib.Die('Must provide patches when running with --remote.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800886
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700887 # --debug needs to be explicitly passed through for remote invocations.
888 release_mode_with_patches = (options.buildbot and patches and
889 '--debug' not in options.pass_through_args)
890 else:
891 if len(args) > 1:
892 cros_lib.Die('Multiple configs not supported if not running with '
893 '--remote.')
894
895 release_mode_with_patches = (options.buildbot and patches and
896 not options.debug)
897
898 # When running in release mode, make sure we are running with checked-in code.
899 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
900 # a release image with checked-in code for CrOS packages.
901 if release_mode_with_patches:
902 cros_lib.Die('Cannot provide patches when running with --buildbot!')
Brian Harring3fec5a82012-03-01 05:57:03 -0800903
Ryan Cuiba41ad32012-03-08 17:15:29 -0800904 if options.buildbot and options.remote_trybot:
905 cros_lib.Die('--buildbot and --remote-trybot cannot be used together.')
906
Ryan Cui85867972012-02-23 18:21:49 -0800907 # Record whether --debug was set explicitly vs. it was inferred.
908 options.debug_forced = False
909 if options.debug:
910 options.debug_forced = True
911 else:
Ryan Cui16ca5812012-03-08 20:34:27 -0800912 # We don't set debug by default for
913 # 1. --buildbot invocations.
914 # 2. --remote invocations, because it needs to push changes to the tryjob
915 # repo.
916 options.debug = not options.buildbot and not options.remote
Brian Harring3fec5a82012-03-01 05:57:03 -0800917
Brian Harring3fec5a82012-03-01 05:57:03 -0800918
Ryan Cuicedd8a52012-03-22 02:28:35 -0700919def _SplitAndFlatten(appended_items):
920 """Given a list of space-separated items, split into flattened list.
921
922 Given ['abc def', 'hij'] return ['abc', 'def', 'hij'].
923 Arguments:
924 appended_items: List of delimiter-separated items.
925
926 Returns: Flattened list.
927 """
928 new_list = []
929 for item in appended_items:
Mike Frysinger4bd23892012-03-26 15:08:52 -0400930 new_list.extend(item.split())
Ryan Cuicedd8a52012-03-22 02:28:35 -0700931 return new_list
932
933
Brian Harring1d7ba942012-04-24 06:37:18 -0700934# pylint: disable=W0613
Ryan Cui85867972012-02-23 18:21:49 -0800935def _PostParseCheck(options, args):
936 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800937
Ryan Cui85867972012-02-23 18:21:49 -0800938 Args:
939 options/args: The options/args object returned by optparse
940 """
Brian Harring1d7ba942012-04-24 06:37:18 -0700941 if options.resume:
942 return
943
944 options.gerrit_patches = _SplitAndFlatten(options.gerrit_patches)
945 options.remote_patches = _SplitAndFlatten(options.remote_patches)
946 try:
947 # TODO(rcui): Split this into two stages, one that parses, another that
948 # validates. Parsing step will be called by _FinishParsing().
949 options.local_patches = _CheckLocalPatches(
950 _SplitAndFlatten(options.local_patches))
951 except optparse.OptionValueError as e:
952 cros_lib.Die(str(e))
953
954 default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
955 if (default and not any([options.local, options.buildbot,
956 options.remote, options.remote_trybot])):
957 cros_lib.Info("CBUILDBOT_DEFAULT_MODE=%s env var detected, using it."
958 % default)
959 default = default.lower()
960 if default == 'local':
961 options.local = True
962 elif default == 'remote':
963 options.remote = True
964 elif default == 'buildbot':
965 options.buildbot = True
966 else:
967 cros_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
968 % default)
Ryan Cui85867972012-02-23 18:21:49 -0800969
970
971def _ParseCommandLine(parser, argv):
972 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800973 (options, args) = parser.parse_args(argv)
Ryan Cui54da0702012-04-19 18:38:08 -0700974 if options.list:
975 _PrintValidConfigs(options.print_all)
976 sys.exit(0)
977
Ryan Cui8be16062012-04-24 12:05:26 -0700978 # Strip out null arguments.
979 # TODO(rcui): Remove when buildbot is fixed
980 args = [arg for arg in args if arg]
981 if not args:
982 parser.error('Invalid usage. Use -h to see usage. Use -l to list '
983 'supported configs.')
984
Ryan Cui85867972012-02-23 18:21:49 -0800985 _FinishParsing(options, args)
986 return options, args
987
988
989def main(argv):
990 # Set umask to 022 so files created by buildbot are readable.
991 os.umask(022)
992
993 if cros_lib.IsInsideChroot():
994 cros_lib.Die('Please run cbuildbot from outside the chroot.')
995
996 parser = _CreateParser()
997 (options, args) = _ParseCommandLine(parser, argv)
Brian Harring3fec5a82012-03-01 05:57:03 -0800998
Brian Harring3fec5a82012-03-01 05:57:03 -0800999 _PostParseCheck(options, args)
1000
1001 if options.remote:
Chris Sosa4f6ffaf2012-05-01 17:05:44 -07001002 cros_lib.logger.setLevel(logging.WARNING)
Ryan Cui16ca5812012-03-08 20:34:27 -08001003
Brian Harring3fec5a82012-03-01 05:57:03 -08001004 # Verify configs are valid.
1005 for bot in args:
1006 _GetConfig(bot)
1007
1008 # Verify gerrit patches are valid.
Ryan Cui16ca5812012-03-08 20:34:27 -08001009 print 'Verifying patches...'
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001010 patch_pool = AcquirePoolFromOptions(options, _GetChromiteTrackingBranch())
1011
Ryan Cuieaa9efd2012-04-25 17:56:45 -07001012 # --debug need to be explicitly passed through for remote invocations.
1013 if options.buildbot and '--debug' not in options.pass_through_args:
1014 _ConfirmRemoteBuildbotRun()
1015
Ryan Cui16ca5812012-03-08 20:34:27 -08001016 print 'Submitting tryjob...'
Ryan Cui16d9e1f2012-05-11 10:50:18 -07001017 tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
Ryan Cui39bdbbf2012-02-29 16:15:39 -08001018 tryjob.Submit(testjob=options.test_tryjob, dryrun=options.debug)
Ryan Cui16ca5812012-03-08 20:34:27 -08001019 print 'Tryjob submitted!'
1020 print ('Go to %s to view the status of your job.'
Ryan Cui4906e1c2012-04-03 20:09:34 -07001021 % tryjob.GetTrybotWaterfallLink())
Brian Harring3fec5a82012-03-01 05:57:03 -08001022 sys.exit(0)
Ryan Cui54da0702012-04-19 18:38:08 -07001023 elif (not options.buildbot and not options.remote_trybot
1024 and not options.resume and not options.local):
1025 cros_lib.Warning('Running in LOCAL TRYBOT mode! Use --remote to submit '
1026 'REMOTE tryjobs. Use --local to suppress this message.')
1027 cros_lib.Warning('Starting April 30th, --local will be required to run the '
1028 'local trybot.')
1029 time.sleep(5)
Brian Harring3fec5a82012-03-01 05:57:03 -08001030
Ryan Cui8be16062012-04-24 12:05:26 -07001031 # Only expecting one config
1032 bot_id = args[-1]
1033 build_config = _GetConfig(bot_id)
Brian Harring3fec5a82012-03-01 05:57:03 -08001034
1035 if options.reference_repo is None:
1036 repo_path = os.path.join(constants.SOURCE_ROOT, '.repo')
1037 # If we're being run from a repo checkout, reuse the repo's git pool to
1038 # cut down on sync time.
1039 if os.path.exists(repo_path):
1040 options.reference_repo = constants.SOURCE_ROOT
1041 elif options.reference_repo:
1042 if not os.path.exists(options.reference_repo):
1043 parser.error('Reference path %s does not exist'
1044 % (options.reference_repo,))
1045 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
1046 parser.error('Reference path %s does not look to be the base of a '
1047 'repo checkout; no .repo exists in the root.'
1048 % (options.reference_repo,))
Ryan Cuid4a24212012-04-04 18:08:12 -07001049
Brian Harringf11bf682012-05-14 15:53:43 -07001050 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -08001051 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -07001052 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
1053 'be used together. Cgroup support is required for '
1054 'buildbot/remote-trybot mode.')
Brian Harring470f6112012-03-02 11:47:10 -08001055 if not cgroups.Cgroup.CgroupsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -07001056 parser.error('Option --buildbot/--remote-trybot was given, but this '
1057 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -08001058
Brian Harring351ce442012-03-09 16:38:14 -08001059 missing = []
1060 for program in _BUILDBOT_REQUIRED_BINARIES:
1061 ret = cros_lib.RunCommand('which %s' % program, shell=True,
1062 redirect_stderr=True, redirect_stdout=True,
1063 error_code_ok=True, print_cmd=False)
1064 if ret.returncode != 0:
1065 missing.append(program)
1066
1067 if missing:
Ryan Cuid4a24212012-04-04 18:08:12 -07001068 parser.error("Option --buildbot/--remote-trybot requires the following "
1069 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -08001070 % (', '.join(missing)))
1071
Brian Harring3fec5a82012-03-01 05:57:03 -08001072 if options.reference_repo:
1073 options.reference_repo = os.path.abspath(options.reference_repo)
1074
1075 if options.dump_config:
1076 # This works, but option ordering is bad...
1077 print 'Configuration %s:' % bot_id
1078 pretty_printer = pprint.PrettyPrinter(indent=2)
1079 pretty_printer.pprint(build_config)
1080 sys.exit(0)
1081
1082 if not options.buildroot:
1083 if options.buildbot:
1084 parser.error('Please specify a buildroot with the --buildroot option.')
Matt Tennantd55b1f42012-04-13 14:15:01 -07001085
Brian Harring470f6112012-03-02 11:47:10 -08001086 options.buildroot = _DetermineDefaultBuildRoot(build_config['internal'])
1087 # We use a marker file in the buildroot to indicate the user has
1088 # consented to using this directory.
1089 if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
1090 _ConfirmBuildRoot(options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -08001091
1092 # Sanity check of buildroot- specifically that it's not pointing into the
1093 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -08001094 if (not repository.IsARepoRoot(options.buildroot) and
David James6b80dc62012-02-29 15:34:40 -08001095 repository.InARepoRepository(options.buildroot)):
Brian Harring3fec5a82012-03-01 05:57:03 -08001096 parser.error('Configured buildroot %s points into a repository checkout, '
1097 'rather than the root of it. This is not supported.'
1098 % options.buildroot)
1099
Brian Harringd166aaf2012-05-14 18:31:53 -07001100 log_file = None
1101 if options.tee:
1102 default_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
1103 dirname = options.log_dir or default_dir
1104 log_file = os.path.join(dirname, _BUILDBOT_LOG_FILE)
1105
1106 osutils.SafeMakedirs(dirname)
1107 _BackupPreviousLog(log_file)
1108
Brian Harringc2d09d92012-05-13 22:03:15 -07001109 with cros_lib.ContextManagerStack() as stack:
1110 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1111 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001112
Brian Harringc2d09d92012-05-13 22:03:15 -07001113 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -07001114 # If we're in resume mode, use our parents tempdir rather than
1115 # nesting another layer.
Brian Harringc2d09d92012-05-13 22:03:15 -07001116 stack.Add(osutils.TempDirContextManager, 'cbuildbot-tmp')
1117 logging.debug("Cbuildbot tempdir is %r.", os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -07001118
1119 if log_file is not None:
1120 stack.Add(tee.Tee, log_file)
1121 options.preserve_paths = set([_DEFAULT_LOG_DIR])
1122
Brian Harringc2d09d92012-05-13 22:03:15 -07001123 if options.cgroups:
1124 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -08001125
Brian Harringc2d09d92012-05-13 22:03:15 -07001126 # Mark everything between EnforcedCleanupSection and here as having to
1127 # be rolled back via the contextmanager cleanup handlers. This
1128 # ensures that sudo bits cannot outlive cbuildbot, that anything
1129 # cgroups would kill gets killed, etc.
1130 critical_section.ForkWatchdog()
Brian Harringd166aaf2012-05-14 18:31:53 -07001131
Brian Harringc2d09d92012-05-13 22:03:15 -07001132 if options.timeout > 0:
1133 stack.Add(cros_lib.Timeout, options.timeout)
Brian Harringa184efa2012-03-04 11:51:25 -08001134
Brian Harringc2d09d92012-05-13 22:03:15 -07001135 if not options.buildbot:
1136 build_config = cbuildbot_config.OverrideConfigForTrybot(
1137 build_config,
1138 options.remote_trybot)
1139
1140 _RunBuildStagesWrapper(options, build_config)