blob: 0bf17a0ec2a2232cb605a7f92b11bb3adacc8863 [file] [log] [blame]
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Module containing the various stages that a builder runs."""
import contextlib
import datetime
import functools
import glob
import json
import logging
import math
import multiprocessing
import os
import platform
import Queue
except ImportError:
# Python-3 renamed to "queue". We still use Queue to avoid collisions
# with naming variables as "queue". Maybe we'll transition at some point.
# pylint: disable=F0401
import queue as Queue
import re
import shutil
import sys
import urllib
from xml.etree import ElementTree
from chromite.buildbot import builderstage as bs
from chromite.buildbot import cbuildbot_commands as commands
from chromite.buildbot import cbuildbot_config
from chromite.buildbot import cbuildbot_results as results_lib
from chromite.buildbot import constants
from chromite.buildbot import lab_status
from chromite.buildbot import lkgm_manager
from chromite.buildbot import manifest_version
from chromite.buildbot import portage_utilities
from chromite.buildbot import repository
from chromite.buildbot import trybot_patch_pool
from chromite.buildbot import validation_pool
from chromite.lib import alerts
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import git
from chromite.lib import gs
from chromite.lib import toolchain
from chromite.lib import osutils
from chromite.lib import parallel
from chromite.lib import patch as cros_patch
from chromite.lib import retry_util
from chromite.lib import timeout_util
!!!VMTests failed!!!
Logs are uploaded in the corresponding %(vm_test_results)s. This can be found
by clicking on the artifacts link in the "Report" Stage. Specifically look
for the test_harness/failed for the failing tests. For more
particulars, please refer to which test failed i.e. above see the
individual test that failed -- or if an update failed, check the
corresponding update directory.
PRE_CQ = validation_pool.PRE_CQ
class NonHaltingBuilderStage(bs.BuilderStage):
"""Build stage that fails a build but finishes the other steps."""
def Run(self):
super(NonHaltingBuilderStage, self).Run()
except results_lib.StepFailure:
name = self.__class__.__name__
cros_build_lib.Error('Ignoring StepFailure in %s', name)
class ForgivingBuilderStage(bs.BuilderStage):
"""Build stage that turns a build step red but not a build."""
def _HandleStageException(self, exception):
"""Override and don't set status to FAIL but FORGIVEN instead."""
return self._HandleExceptionAsWarning(exception)
class RetryStage(object):
"""Retry a given stage multiple times to see if it passes."""
def __init__(self, builder_run, max_retry, stage, *args, **kwargs):
"""Create a RetryStage object.
builder_run: See arguments to bs.BuilderStage.__init__()
max_retry: The number of times to try the given stage.
stage: The stage class to create.
*args: A list of arguments to pass to the stage constructor.
**kwargs: A list of keyword arguments to pass to the stage constructor.
self._run = builder_run
self.max_retry = max_retry
self.stage = stage
self.args = (builder_run,) + args
self.kwargs = kwargs
self.names = []
self.attempt = None
def GetStageNames(self):
"""Get a list of the places where this stage has recorded results."""
return self.names[:]
def _PerformStage(self):
"""Run the stage once, incrementing the attempt number as needed."""
suffix = ' (attempt %d)' % (self.attempt,)
stage_obj = self.stage(
*self.args, attempt=self.attempt, max_retry=self.max_retry,
suffix=suffix, **self.kwargs)
self.attempt += 1
def Run(self):
"""Retry the given stage multiple times to see if it passes."""
self.attempt = 1
results_lib.RetriableStepFailure, self.max_retry, self._PerformStage)
class BoardSpecificBuilderStage(bs.BuilderStage):
"""Builder stage that is specific to a board."""
def __init__(self, builder_run, board, **kwargs):
super(BoardSpecificBuilderStage, self).__init__(builder_run, **kwargs)
self._current_board = board
if not isinstance(board, basestring):
raise TypeError('Expected string, got %r' % (board,))
# Add a board name suffix to differentiate between various boards (in case
# more than one board is built on a single builder.)
if len(self._boards) > 1 or self._run.config.grouped: = '%s [%s]' % (, board)
def GetImageDirSymlink(self, pointer='latest-cbuildbot'):
"""Get the location of the current image."""
return os.path.join(self._run.buildroot, 'src', 'build', 'images',
self._current_board, pointer)
class ArchivingStageMixin(object):
"""Stage with utilities for uploading artifacts.
This provides functionality for doing archiving. All it needs is access
to the BuilderRun object at self._run. No __init__ needed.
acl: GS ACL to use for uploads.
archive: Archive object.
archive_path: Local path where archives are kept for this run. Also copy
of self.archive.archive_path.
download_url: The URL where artifacts for this run can be downloaded.
Also copy of self.archive.download_url.
upload_url: The Google Storage location where artifacts for this run should
be uploaded. Also copy of self.archive.upload_url.
version: Copy of self.archive.version.
def archive(self):
"""Retrieve the Archive object to use."""
# pylint: disable=W0201
if not hasattr(self, '_archive'):
self._archive = self._run.GetArchive()
return self._archive
def acl(self):
"""Retrieve GS ACL to use for uploads."""
return self.GetUploadACL(self._run.config)
# TODO(mtennant): Get rid of this property.
def version(self):
"""Retrieve the ChromeOS version for the archiving."""
return self.archive.version
def archive_path(self):
"""Local path where archives are kept for this run."""
return self.archive.archive_path
# TODO(mtennant): Rename base_archive_path.
def bot_archive_root(self):
"""Path of directory one level up from self.archive_path."""
return os.path.dirname(self.archive_path)
def upload_url(self):
"""The GS location where artifacts should be uploaded for this run."""
return self.archive.upload_url
def base_upload_url(self):
"""The GS path one level up from self.upload_url."""
return os.path.dirname(self.upload_url)
def download_url(self):
"""The URL where artifacts for this run can be downloaded."""
return self.archive.download_url
def GetUploadACL(cls, config):
"""Get the ACL we should use to upload artifacts for a given config."""
if config.internal:
# Use the bucket default ACL.
return None
return 'public-read'
def ArtifactUploader(self, queue=None, archive=True, strict=True):
"""Upload each queued input in the background.
This context manager starts a set of workers in the background, who each
wait for input on the specified queue. These workers run
self.UploadArtifact(*args, archive=archive) for each input in the queue.
queue: Queue to use. Add artifacts to this queue, and they will be
uploaded in the background. If None, one will be created on the fly.
archive: Whether to automatically copy files to the archive dir.
strict: Whether to treat upload errors as fatal.
The queue to use. This is only useful if you did not supply a queue.
upload = lambda path: self.UploadArtifact(path, archive, strict)
with parallel.BackgroundTaskRunner(upload, queue=queue,
processes=self.PROCESSES) as bg_queue:
yield bg_queue
def PrintDownloadLink(self, filename, prefix=''):
"""Print a link to an artifact in Google Storage.
filename: The filename of the uploaded file.
prefix: The prefix to put in front of the filename.
url = '%s/%s' % (self.download_url.rstrip('/'), filename)
cros_build_lib.PrintBuildbotLink(prefix + filename, url)
def UploadArtifact(self, path, archive=True, strict=True):
"""Upload generated artifact to Google Storage.
path: Path of local file to upload to Google Storage.
archive: Whether to automatically copy files to the archive dir.
strict: Whether to treat upload errors as fatal.
filename = path
if archive:
filename = commands.ArchiveFile(path, self.archive_path)
self.archive_path, self.upload_url, filename, self._run.debug,
update_list=True, acl=self.acl)
except (cros_build_lib.RunCommandError, timeout_util.TimeoutError) as e:
cros_build_lib.PrintBuildbotStepText('Upload failed')
if strict:
# Treat gsutil flake as a warning if it's the only problem.
def GetMetadata(self, config=None, stage=None, final_status=None,
sync_instance=None, completion_instance=None):
"""Constructs the metadata json object.
config: The build config for this run. Defaults to self._run.config.
stage: The stage name that this metadata file is being uploaded for.
final_status: Whether the build passed or failed. If None, the build
will be treated as still running.
sync_instance: The stage instance that was used for syncing the source
code. This should be a derivative of SyncStage. If None, the list of
commit queue patches will not be included in the metadata.
completion_instance: The stage instance that was used to wait for slave
completion. Used to add slave build information to master builder's
metadata. If None, no such status information will be included. It not
None, this should be a derivative of MasterSlaveSyncCompletionStage.
config = config or self._run.config
start_time = results_lib.Results.start_time
current_time =
start_time_stamp = cros_build_lib.UserDateTimeFormat(timeval=start_time)
current_time_stamp = cros_build_lib.UserDateTimeFormat(timeval=current_time)
duration = '%s' % (current_time - start_time,)
sdk_verinfo = cros_build_lib.LoadKeyValueFile(
os.path.join(self._build_root, constants.SDK_VERSION_FILE),
verinfo = self._run.GetVersionInfo(self._build_root)
platform_tag = getattr(self._run.attrs, 'release_tag')
if not platform_tag:
platform_tag = verinfo.VersionString()
metadata = {
# Version of the metadata format.
'metadata-version': '2',
# Data for this build.
'bot-config': config['name'],
'bot-hostname': cros_build_lib.GetHostName(fully_qualified=True),
'boards': config['boards'],
'build-number': self._run.buildnumber,
'builder-name': os.environ.get('BUILDBOT_BUILDERNAME', ''),
'status': {
'current-time': current_time_stamp,
'status': final_status if final_status else 'running',
'summary': stage or '',
'time': {
'start': start_time_stamp,
'finish': current_time_stamp if final_status else '',
'duration': duration,
'version': {
'chrome': self._run.attrs.chrome_version,
'full': self.archive.version,
'milestone': verinfo.chrome_branch,
'platform': platform_tag,
# Data for the toolchain used.
'sdk-version': sdk_verinfo.get('SDK_LATEST_VERSION', '<unknown>'),
'toolchain-url': sdk_verinfo.get('TC_PATH', '<unknown>'),
if len(config['boards']) == 1:
toolchains = toolchain.GetToolchainsForBoard(config['boards'][0],
metadata['toolchain-tuple'] = (
toolchain.FilterToolchains(toolchains, 'default', True).keys() +
toolchain.FilterToolchains(toolchains, 'default', False).keys())
metadata['results'] = []
for entry in results_lib.Results.Get():
timestr = datetime.timedelta(seconds=math.ceil(entry.time))
if entry.result in results_lib.Results.NON_FAILURE_TYPES:
status = constants.FINAL_STATUS_PASSED
status = constants.FINAL_STATUS_FAILED
'status': status,
# The result might be a custom exception.
'summary': str(entry.result),
'duration': '%s' % timestr,
'description': entry.description,
'log': self.ConstructDashboardURL(,
commit_queue_stages = (CommitQueueSyncStage, PreCQSyncStage)
if (sync_instance and isinstance(sync_instance, commit_queue_stages) and
changes = []
pool = sync_instance.pool
for change in pool.changes:
details = {'gerrit_number': change.gerrit_number,
'patch_number': change.patch_number,
'internal': change.internal}
for latest_patchset_only in (False, True):
prefix = '' if latest_patchset_only else 'total_'
for status in (pool.STATUS_FAILED, pool.STATUS_PASSED):
count = pool.GetCLStatusCount(, change, status,
details['%s%s' % (prefix, status.lower())] = count
metadata['changes'] = changes
# If we were a CQ master, then include a summary of the status of slave cq
# builders in metadata
if config['master']:
if (completion_instance and
isinstance(completion_instance, MasterSlaveSyncCompletionStage)):
statuses = completion_instance.GetSlaveStatuses()
if not statuses:
logging.warning('completion_instance did not have any statuses '
'to report. Will not add slave status to metadata.')
metadata['slave_targets'] = {}
for builder, status in statuses.iteritems():
metadata['slave_targets'][builder] = status.AsFlatDict()
return metadata
def UploadMetadata(self, config=None, stage=None, upload_queue=None,
"""Create and upload JSON of various metadata describing this run.
config: Build config to use. Passed to GetMetadata.
stage: Stage to upload metadata for. If None the metadata is for the
entire run.
upload_queue: If specified then put the artifact file to upload on
this queue. If None then upload it directly now.
kwargs: Pass to self.GetMetadata.
metadata = self.GetMetadata(config=config, stage=stage, **kwargs)
filename = constants.METADATA_JSON
if stage is not None:
filename = constants.METADATA_STAGE_JSON % { 'stage': stage }
metadata_json = os.path.join(self.archive_path, filename)
# Stages may run in parallel, so we have to do atomic updates on this.
osutils.WriteFile(metadata_json, json.dumps(metadata), atomic=True)
if upload_queue is not None:
self.UploadArtifact(filename, archive=False)
# TODO(mtennant): This class continues to exist only for subclasses that still
# need self.archive_stage. Hopefully, we can get rid of that need, eventually.
class ArchivingStage(BoardSpecificBuilderStage, ArchivingStageMixin):
"""Helper for stages that archive files.
See ArchivingStageMixin for functionality.
archive_stage: The ArchiveStage instance for this board.
def __init__(self, builder_run, board, archive_stage, **kwargs):
super(ArchivingStage, self).__init__(builder_run, board, **kwargs)
self.archive_stage = archive_stage
class CleanUpStage(bs.BuilderStage):
"""Stages that cleans up build artifacts from previous runs.
This stage cleans up previous KVM state, temporary git commits,
clobbers, and wipes tmp inside the chroot.
option_name = 'clean'
def _CleanChroot(self):
chroot_tmpdir = os.path.join(self._build_root, constants.DEFAULT_CHROOT_DIR,
if os.path.exists(chroot_tmpdir):
cros_build_lib.SudoRunCommand(['rm', '-rf', chroot_tmpdir],
cros_build_lib.SudoRunCommand(['mkdir', '--mode', '1777', chroot_tmpdir],
def _DeleteChroot(self):
chroot = os.path.join(self._build_root, constants.DEFAULT_CHROOT_DIR)
if os.path.exists(chroot):
# At this stage, it's not safe to run the cros_sdk inside the buildroot
# itself because we haven't sync'd yet, and the version of the chromite
# in there might be broken. Since we've already unmounted everything in
# there, we can just remove it using rm -rf.
osutils.RmDir(chroot, ignore_missing=True, sudo=True)
def _DeleteArchivedTrybotImages(self):
"""For trybots, clear all previus archive images to save space."""
archive_root = self._run.GetArchive().GetLocalArchiveRoot(trybot=True)
osutils.RmDir(archive_root, ignore_missing=True)
def _DeleteArchivedPerfResults(self):
"""Clear any previously stashed perf results from hw testing."""
for result in glob.glob(os.path.join(
def _DeleteChromeBuildOutput(self):
chrome_src = os.path.join(self._run.options.chrome_root, 'src')
for out_dir in glob.glob(os.path.join(chrome_src, 'out_*')):
def PerformStage(self):
if (not (self._run.options.buildbot or self._run.options.remote_trybot)
and self._run.options.clobber):
if not commands.ValidateClobber(self._build_root):
cros_build_lib.Die("--clobber in local mode must be approved.")
# If we can't get a manifest out of it, then it's not usable and must be
# clobbered.
manifest = None
if not self._run.options.clobber:
manifest = git.ManifestCheckout.Cached(self._build_root, search=False)
except (KeyboardInterrupt, MemoryError, SystemExit):
except Exception as e:
# Either there is no repo there, or the manifest isn't usable. If the
# directory exists, log the exception for debugging reasons. Either
# way, the checkout needs to be wiped since it's in an unknown
# state.
if os.path.exists(self._build_root):
cros_build_lib.Warning("ManifestCheckout at %s is unusable: %s",
self._build_root, e)
# Clean mount points first to be safe about deleting.
if manifest is None:
tasks = [functools.partial(commands.BuildRootGitCleanup,
functools.partial(commands.WipeOldOutput, self._build_root),
if self._run.options.chrome_root:
if self._run.config.chroot_replace and
class PatchChangesStage(bs.BuilderStage):
"""Stage that patches a set of Gerrit changes to the buildroot source tree."""
def __init__(self, builder_run, patch_pool, **kwargs):
"""Construct a PatchChangesStage.
builder_run: BuilderRun object.
patch_pool: A TrybotPatchPool object containing the different types of
patches to apply.
super(PatchChangesStage, self).__init__(builder_run, **kwargs)
self.patch_pool = patch_pool
def _CheckForDuplicatePatches(_series, changes):
conflicts = {}
duplicates = []
for change in changes:
if is None:
"Change %s lacks a usable ChangeId; duplicate checking cannot "
"be done for this change. If cherry-picking fails, this is a "
"potential cause.", change)
conflicts.setdefault(, []).append(change)
duplicates = [x for x in conflicts.itervalues() if len(x) > 1]
if not duplicates:
return changes
for conflict in duplicates:
"Changes %s conflict with each other- they have same id %s.",
', '.join(map(str, conflict)), conflict[0].id)
cros_build_lib.Die("Duplicate patches were encountered: %s", duplicates)
def _PatchSeriesFilter(self, series, changes):
return self._CheckForDuplicatePatches(series, changes)
def _ApplyPatchSeries(self, series, patch_pool, **kwargs):
"""Applies a patch pool using a patch series."""
kwargs.setdefault('frozen', False)
# Honor the given ordering, so that if a gerrit/remote patch
# conflicts w/ a local patch, the gerrit/remote patch are
# blamed rather than local (patch ordering is typically
# local, gerrit, then remote).
kwargs.setdefault('honor_ordering', True)
kwargs['changes_filter'] = self._PatchSeriesFilter
_applied, failed_tot, failed_inflight = series.Apply(
list(patch_pool), **kwargs)
failures = failed_tot + failed_inflight
if failures:
cros_build_lib.Die("Failed applying patches: %s",
"\n".join(map(str, failures)))
def PerformStage(self):
class NoisyPatchSeries(validation_pool.PatchSeries):
"""Custom PatchSeries that adds links to buildbot logs for remote trys."""
def ApplyChange(self, change, dryrun=False):
if isinstance(change, cros_patch.GerritPatch):
cros_build_lib.PrintBuildbotLink(str(change), change.url)
elif isinstance(change, cros_patch.UploadedLocalPatch):
return validation_pool.PatchSeries.ApplyChange(self, change,
# If we're an external builder, ignore internal patches.
helper_pool = validation_pool.HelperPool.SimpleCreate(
cros_internal=self._run.config.internal, cros=True)
# Limit our resolution to non-manifest patches.
patch_series = NoisyPatchSeries(
deps_filter_fn=lambda p: not trybot_patch_pool.ManifestFilter(p))
self._ApplyPatchSeries(patch_series, self.patch_pool)
class BootstrapStage(PatchChangesStage):
"""Stage that patches a chromite repo and re-executes inside it.
returncode - the returncode of the cbuildbot re-execution. Valid after
calling stage.Run().
option_name = 'bootstrap'
def __init__(self, builder_run, chromite_patch_pool,
manifest_patch_pool=None, **kwargs):
super(BootstrapStage, self).__init__(
builder_run, trybot_patch_pool.TrybotPatchPool(), **kwargs)
self.chromite_patch_pool = chromite_patch_pool
self.manifest_patch_pool = manifest_patch_pool
self.returncode = None
def _ApplyManifestPatches(self, patch_pool):
"""Apply a pool of manifest patches to a temp manifest checkout.
patch_pool: The pool to apply.
The path to the patched manifest checkout.
Exception, if the new patched manifest cannot be parsed.
checkout_dir = os.path.join(self.tempdir, 'manfest-checkout')
patch_series = validation_pool.PatchSeries.WorkOnSingleRepo(
checkout_dir, deps_filter_fn=trybot_patch_pool.ManifestFilter,
self._ApplyPatchSeries(patch_series, patch_pool)
# Create the branch that 'repo init -b <target_branch> -u <patched_repo>'
# will look for.
cmd = ['branch', '-f', self._run.manifest_branch,
git.RunGit(checkout_dir, cmd)
# Verify that the patched manifest loads properly. Propagate any errors as
# exceptions.
manifest = os.path.join(checkout_dir, self._run.config.manifest)
git.Manifest.Cached(manifest, manifest_include_dir=checkout_dir)
return checkout_dir
def _FilterArgsForApi(parsed_args, api_minor):
"""Remove arguments that are introduced after an api version."""
def filter_fn(passed_arg):
return passed_arg.opt_inst.api_version <= api_minor
accepted, removed = commandline.FilteringParser.FilterArgs(
parsed_args, filter_fn)
if removed:
cros_build_lib.Warning('The following arguments were removed due to api: '
"'%s'" % ' '.join(removed))
return accepted
def FilterArgsForTargetCbuildbot(cls, buildroot, cbuildbot_path, options):
_, minor = cros_build_lib.GetTargetChromiteApiVersion(buildroot)
args = [cbuildbot_path]
args.extend(cls._FilterArgsForApi(options.parsed_args, minor))
# Only pass down --cache-dir if it was specified. By default, we want
# the cache dir to live in the root of each checkout, so this means that
# each instance of cbuildbot needs to calculate the default separately.
if minor >= 2 and options.cache_dir_specified:
args += ['--cache-dir', options.cache_dir]
return args
#pylint: disable=E1101
def PerformStage(self):
# The plan for the builders is to use master branch to bootstrap other
# branches. Now, if we wanted to test patches for both the bootstrap code
# (on master) and the branched chromite (say, R20), we need to filter the
# patches by branch.
filter_branch = self._run.manifest_branch
if self._run.options.test_bootstrap:
filter_branch = 'master'
chromite_dir = os.path.join(self.tempdir, 'chromite')
reference_repo = os.path.join(constants.SOURCE_ROOT, 'chromite', '.git')
repository.CloneGitRepo(chromite_dir, constants.CHROMITE_URL,
git.RunGit(chromite_dir, ['checkout', filter_branch])
def BranchAndChromiteFilter(patch):
return (trybot_patch_pool.BranchFilter(filter_branch, patch) and
patch_series = validation_pool.PatchSeries.WorkOnSingleRepo(
chromite_dir, filter_branch,
filtered_pool = self.chromite_patch_pool.FilterBranch(filter_branch)
if filtered_pool:
self._ApplyPatchSeries(patch_series, filtered_pool)
cbuildbot_path = constants.PATH_TO_CBUILDBOT
if not os.path.exists(os.path.join(self.tempdir, cbuildbot_path)):
cbuildbot_path = 'chromite/buildbot/cbuildbot'
# pylint: disable=W0212
cmd = self.FilterArgsForTargetCbuildbot(self.tempdir, cbuildbot_path,
extra_params = ['--sourceroot=%s' % self._run.options.sourceroot]
if self._run.options.test_bootstrap:
# We don't want re-executed instance to see this.
cmd = [a for a in cmd if a != '--test-bootstrap']
# If we've already done the desired number of bootstraps, disable
# bootstrapping for the next execution. Also pass in the patched manifest
# repository.
if self.manifest_patch_pool:
manifest_dir = self._ApplyManifestPatches(self.manifest_patch_pool)
extra_params.extend(['--manifest-repo-url', manifest_dir])
cmd += extra_params
result_obj = cros_build_lib.RunCommand(
cmd, cwd=self.tempdir, kill_timeout=30, error_code_ok=True)
self.returncode = result_obj.returncode
class SyncStage(bs.BuilderStage):
"""Stage that performs syncing for the builder."""
option_name = 'sync'
output_manifest_sha1 = True
def __init__(self, builder_run, **kwargs):
super(SyncStage, self).__init__(builder_run, **kwargs)
self.repo = None
self.skip_sync = False
# TODO(mtennant): Why keep a duplicate copy of this config value
# at self.internal when it can always be retrieved from config?
self.internal = self._run.config.internal
def _GetManifestVersionsRepoUrl(self, read_only=False):
return cbuildbot_config.GetManifestVersionsRepoUrl(
def Initialize(self):
def _InitializeRepo(self):
"""Set up the RepoRepository object."""
self.repo = self.GetRepoRepository()
def GetNextManifest(self):
"""Returns the manifest to use."""
return self._run.config.manifest
def ManifestCheckout(self, next_manifest):
"""Checks out the repository to the given manifest."""
self._Print('\n'.join(['BUILDROOT: %s' %,
'TRACKING BRANCH: %s' % self.repo.branch,
'NEXT MANIFEST: %s' % next_manifest]))
if not self.skip_sync:
print >> sys.stderr, self.repo.ExportManifest(
def PerformStage(self):
with osutils.TempDir() as tempdir:
# Save off the last manifest.
fresh_sync = True
if os.path.exists( and not self._run.options.clobber:
old_filename = os.path.join(tempdir, 'old.xml')
old_contents = self.repo.ExportManifest()
except cros_build_lib.RunCommandError as e:
osutils.WriteFile(old_filename, old_contents)
fresh_sync = False
# Sync.
# Print the blamelist.
if fresh_sync:
cros_build_lib.PrintBuildbotStepText('(From scratch)')
elif self._run.options.buildbot:
lkgm_manager.GenerateBlameList(self.repo, old_filename)
class LKGMSyncStage(SyncStage):
"""Stage that syncs to the last known good manifest blessed by builders."""
output_manifest_sha1 = False
def GetNextManifest(self):
"""Override: Gets the LKGM."""
# TODO(sosa): Should really use an initialized manager here.
if self.internal:
mv_dir = 'manifest-versions-internal'
mv_dir = 'manifest-versions'
manifest_path = os.path.join(self._build_root, mv_dir)
manifest_repo = self._GetManifestVersionsRepoUrl(read_only=True)
manifest_version.RefreshManifestCheckout(manifest_path, manifest_repo)
return os.path.join(manifest_path, lkgm_manager.LKGMManager.LKGM_PATH)
class ChromeLKGMSyncStage(SyncStage):
"""Stage that syncs to the last known good manifest for Chrome."""
output_manifest_sha1 = False
def GetNextManifest(self):
"""Override: Gets the LKGM from the Chrome tree."""
chrome_lkgm = commands.GetChromeLKGM(self._run.options.chrome_version)
# We need a full buildspecs manager here as we need an initialized manifest
# manager with paths to the spec.
# TODO(mtennant): Consider registering as manifest_manager run param, for
# consistency, but be careful that consumers do not get confused.
# Currently only the "manifest_manager" from ManifestVersionedSync (and
# subclasses) is used later in the flow.
manifest_manager = manifest_version.BuildSpecsManager(
return manifest_manager.GetLocalManifest(chrome_lkgm)
class ManifestVersionedSyncStage(SyncStage):
"""Stage that generates a unique manifest file, and sync's to it."""
# TODO(mtennant): Make this into a builder run value.
output_manifest_sha1 = False
def __init__(self, builder_run, **kwargs):
# Perform the sync at the end of the stage to the given manifest.
super(ManifestVersionedSyncStage, self).__init__(builder_run, **kwargs)
self.repo = None
self.manifest_manager = None
# If a builder pushes changes (even with dryrun mode), we need a writable
# repository. Otherwise, the push will be rejected by the server.
self.manifest_repo = self._GetManifestVersionsRepoUrl(read_only=False)
# 1. If we're uprevving Chrome, Chrome might have changed even if the
# manifest has not, so we should force a build to double check. This
# means that we'll create a new manifest, even if there are no changes.
# 2. If we're running with --debug, we should always run through to
# completion, so as to ensure a complete test.
self._force = self._chrome_rev or self._run.options.debug
def HandleSkip(self):
"""Initializes a manifest manager to the specified version if skipped."""
super(ManifestVersionedSyncStage, self).HandleSkip()
if self._run.options.force_version:
def ForceVersion(self, version):
"""Creates a manifest manager from given version and returns manifest."""
return self.manifest_manager.BootstrapFromVersion(version)
def VersionIncrementType(self):
"""Return which part of the version number should be incremented."""
if self._run.manifest_branch == 'master':
return 'build'
return 'branch'
def RegisterManifestManager(self, manifest_manager):
"""Save the given manifest manager for later use in this run.
manifest_manager: Expected to be a BuildSpecsManager.
self._run.attrs.manifest_manager = self.manifest_manager = manifest_manager
def Initialize(self):
"""Initializes a manager that manages manifests for associated stages."""
dry_run = self._run.options.debug
# If chrome_rev is somehow set, fail.
assert not self._chrome_rev, \
'chrome_rev is unsupported on release builders.'
def GetNextManifest(self):
"""Uses the initialized manifest manager to get the next manifest."""
assert self.manifest_manager, \
'Must run GetStageManager before checkout out build.'
to_return = self.manifest_manager.GetNextBuildSpec()
previous_version = self.manifest_manager.GetLatestPassingSpec()
target_version = self.manifest_manager.current_version
# Print the Blamelist here.
url_prefix = ''
url = url_prefix + 'from=%s&to=%s' % (previous_version, target_version)
cros_build_lib.PrintBuildbotLink('Blamelist', url)
# The testManifestVersionedSyncOnePartBranch interacts badly with this
# function. It doesn't fully initialize self.manifest_manager which
# causes target_version to be None. Since there isn't a clean fix in
# either direction, just throw this through str(). In the normal case,
# it's already a string anyways.
return to_return
def LocalizeManifest(self, manifest, filter_cros=False):
"""Remove restricted checkouts from the manifest if needed.
manifest: The manifest to localize.
filter_cros: If set, then only checkouts with a remote of 'cros' or
'cros-internal' are kept, and the rest are filtered out.
if filter_cros:
with osutils.TempDir() as tempdir:
filtered_manifest = os.path.join(tempdir, 'filtered.xml')
doc = ElementTree.parse(manifest)
root = doc.getroot()
for node in root.findall('project'):
remote = node.attrib.get('remote')
if remote and remote not in constants.GIT_REMOTES:
yield filtered_manifest
yield manifest
def PerformStage(self):
if self._run.options.force_version:
next_manifest = self.ForceVersion(self._run.options.force_version)
next_manifest = self.GetNextManifest()
if not next_manifest:
cros_build_lib.Info('Found no work to do.')
if self._run.attrs.manifest_manager.DidLastBuildFail():
raise results_lib.StepFailure('The previous build failed.')
# Log this early on for the release team to grep out before we finish.
if self.manifest_manager:
self._Print('\nRELEASETAG: %s\n' % (
# To keep local trybots working, remove restricted checkouts from the
# official manifest we get from manifest-versions.
with self.LocalizeManifest(
next_manifest, filter_cros=self._run.options.local) as new_manifest:
class MasterSlaveSyncStage(ManifestVersionedSyncStage):
"""Stage that generates a unique manifest file candidate, and sync's to it."""
# TODO(mtennant): Turn this into self._run.attrs.sub_manager or similar.
# An instance of lkgm_manager.LKGMManager for slave builds.
sub_manager = None
def __init__(self, builder_run, **kwargs):
super(MasterSlaveSyncStage, self).__init__(builder_run, **kwargs)
# lkgm_manager deals with making sure we're synced to whatever manifest
# we get back in GetNextManifest so syncing again is redundant.
self.skip_sync = True
def _GetInitializedManager(self, internal):
"""Returns an initialized lkgm manager.
internal: Boolean. True if this is using an internal manifest.
increment = self.VersionIncrementType()
return lkgm_manager.LKGMManager(
internal, read_only=False),
def Initialize(self):
"""Override: Creates an LKGMManager rather than a ManifestManager."""
if (self._run.config.master and
assert self.internal, 'Unified masters must use an internal checkout.'
MasterSlaveSyncStage.sub_manager = self._GetInitializedManager(False)
def ForceVersion(self, version):
manifest = super(MasterSlaveSyncStage, self).ForceVersion(version)
if MasterSlaveSyncStage.sub_manager:
return manifest
def GetNextManifest(self):
"""Gets the next manifest using LKGM logic."""
assert self.manifest_manager, \
'Must run Initialize before we can get a manifest.'
assert isinstance(self.manifest_manager, lkgm_manager.LKGMManager), \
'Manifest manager instantiated with wrong class.'
if self._run.config.master:
manifest = self.manifest_manager.CreateNewCandidate()
if MasterSlaveSyncStage.sub_manager:
return manifest
return self.manifest_manager.GetLatestCandidate()
class CommitQueueSyncStage(MasterSlaveSyncStage):
"""Commit Queue Sync stage that handles syncing and applying patches.
This stage handles syncing to a manifest, passing around that manifest to
other builders and finding the Gerrit Reviews ready to be committed and
applying them into its own checkout.
def __init__(self, builder_run, **kwargs):
super(CommitQueueSyncStage, self).__init__(builder_run, **kwargs)
# Figure out the builder's name from the buildbot waterfall.
builder_name = self._run.config.paladin_builder_name
self.builder_name = builder_name if builder_name else
# The pool of patches to be picked up by the commit queue.
# - For the master commit queue, it's initialized in GetNextManifest.
# - For slave commit queues, it's initialized in _SetPoolFromManifest.
# In all cases, the pool is saved to disk, and refreshed after bootstrapping
# by HandleSkip.
self.pool = None
def HandleSkip(self):
"""Handles skip and initializes validation pool from manifest."""
super(CommitQueueSyncStage, self).HandleSkip()
filename = self._run.options.validation_pool
if filename:
self.pool = validation_pool.ValidationPool.Load(filename)
def _ChangeFilter(self, pool, changes, non_manifest_changes):
# First, look for changes that were tested by the Pre-CQ.
changes_to_test = []
for change in changes:
status = pool.GetCLStatus(PRE_CQ, change)
if status == manifest_version.BuilderStatus.STATUS_PASSED:
# If we only see changes that weren't verified by Pre-CQ, try all of the
# changes. This ensures that the CQ continues to work even if the Pre-CQ is
# down.
if not changes_to_test:
changes_to_test = changes
return changes_to_test, non_manifest_changes
def _SetPoolFromManifest(self, manifest):
"""Sets validation pool based on manifest path passed in."""
# Note that GetNextManifest() calls GetLatestCandidate() in this case,
# so the repo will already be sync'd appropriately. This means that
# AcquirePoolFromManifest does not need to sync.
self.pool = validation_pool.ValidationPool.AcquirePoolFromManifest(
manifest, self._run.config.overlays, self.repo,
self._run.buildnumber, self.builder_name,
self._run.config.master, self._run.options.debug)
def GetNextManifest(self):
"""Gets the next manifest using LKGM logic."""
assert self.manifest_manager, \
'Must run Initialize before we can get a manifest.'
assert isinstance(self.manifest_manager, lkgm_manager.LKGMManager), \
'Manifest manager instantiated with wrong class.'
if self._run.config.master:
# In order to acquire a pool, we need an initialized buildroot.
if not git.FindRepoDir(
self.pool = pool = validation_pool.ValidationPool.AcquirePool(
self._run.config.overlays, self.repo,
self._run.buildnumber, self.builder_name,
check_tree_open=not self._run.options.debug or
change_filter=self._ChangeFilter, throttled_ok=True)
except validation_pool.TreeIsClosedException as e:
return None
manifest = self.manifest_manager.CreateNewCandidate(validation_pool=pool)
if MasterSlaveSyncStage.sub_manager:
return manifest
manifest = self.manifest_manager.GetLatestCandidate()
if manifest:
if self._run.config.build_before_patching:
pre_build_passed = self._RunPrePatchBuild()
'CommitQueueSync : Apply Patches')
if not pre_build_passed:
cros_build_lib.PrintBuildbotStepText('Pre-patch build failed.')
return manifest
def _RunPrePatchBuild(self):
"""Run through a pre-patch build to prepare for incremental build.
This function runs though the InitSDKStage, SetupBoardStage, and
BuildPackagesStage. It is intended to be called before applying
any patches under test, to prepare the chroot and sysroot in a state
corresponding to ToT prior to an incremental build.
True if all stages were successful, False if any of them failed.
suffix = ' (pre-Patch)'
InitSDKStage(self._run, chroot_replace=True, suffix=suffix).Run()
SetupBoardStage(self._run, boards=self._run.config.boards,
for board in self._run.config.boards:
BuildPackagesStage(self._run, board=board, archive_stage=None,
except results_lib.StepFailure:
return False
return True
def PerformStage(self):
"""Performs normal stage and prints blamelist at end."""
if self._run.options.force_version:
class ManifestVersionedSyncCompletionStage(ForgivingBuilderStage):
"""Stage that records board specific results for a unique manifest file."""
option_name = 'sync'
def __init__(self, builder_run, sync_stage, success, **kwargs):
super(ManifestVersionedSyncCompletionStage, self).__init__(
builder_run, **kwargs)
self.sync_stage = sync_stage
self.success = success
# Message that can be set that well be sent along with the status in
# UpdateStatus.
self.message = None
def PerformStage(self):
success=self.success, message=self.message)
class ImportantBuilderFailedException(results_lib.StepFailure):
"""Exception thrown when an important build fails to build."""
class MasterSlaveSyncCompletionStage(ManifestVersionedSyncCompletionStage):
"""Stage that records whether we passed or failed to build/test manifest."""
def __init__(self, *args, **kwargs):
super(MasterSlaveSyncCompletionStage, self).__init__(*args, **kwargs)
self._slave_statuses = {}
def _FetchSlaveStatuses(self):
"""Fetch and return build status for this build and any of its slaves.
A build-names->status dictionary of build statuses. Builders that never
started may have status None.
# TODO(mtennant): When testing a master in debug mode, it is actually very
# helpful to allow this code to check on slave status IF the run was with
# a specified manifest version (--version argument). In such a case, the
# master fetches the statuses of previously finished slaves (from the real
# runs, presumably completed earlier), nicely executing more of this code.
# I suggest allowing a master with --debug and --version to run this code.
if self._run.options.debug:
# In debug mode, nothing is uploaded to Google Storage, so we bypass
# the extra hop and just look at what we have locally.
status = manifest_version.BuilderStatus.GetCompletedStatus(self.success)
status_obj = manifest_version.BuilderStatus(status, self.message)
return {self._bot_id: status_obj}
elif not self._run.config.master:
# Slaves only need to look at their own status.
return self._run.attrs.manifest_manager.GetBuildersStatus([self._bot_id])
builders = self._GetSlavesForMaster(self._run.config)
manager = self._run.attrs.manifest_manager
sub_manager = MasterSlaveSyncStage.sub_manager
if sub_manager:
# TODO(build): There appears to be no reason the public and private
# statuses cannot be gathered at the same time. This would avoid
# having two separate long timeout periods involved.
public_builders = [b['name'] for b in builders if not b['internal']]
statuses = sub_manager.GetBuildersStatus(public_builders)
private_builders = [b['name'] for b in builders if b['internal']]
statuses = manager.GetBuildersStatus([b['name'] for b in builders])
return statuses
def _AbortCQHWTests(self):
"""Abort any HWTests started by the CQ."""
manifest_manager = self._run.attrs.manifest_manager
if (cbuildbot_config.IsCQType(self._run.config.build_type) and
manifest_manager is not None and
self._run.manifest_branch == 'master'):
release_tag = manifest_manager.current_version
if release_tag and not commands.HaveHWTestsBeenAborted(release_tag):
commands.AbortHWTests(release_tag, self._run.options.debug)
def _HandleStageException(self, exception):
"""Decide whether an exception should be treated as fatal."""
# Besides the master, the completion stages also run on slaves, to report
# their status back to the master. If the build failed, they throw an
# exception here. For slave builders, marking this stage 'red' would be
# redundant, since the build itself would already be red. In this case,
# report a warning instead.
# pylint: disable=W0212
if (isinstance(exception, ImportantBuilderFailedException) and
not self._run.config.master):
return self._HandleExceptionAsWarning(exception)
# In all other cases, exceptions should be treated as fatal. To
# implement this, we bypass ForgivingStage and call
# bs.BuilderStage._HandleStageException explicitly.
return bs.BuilderStage._HandleStageException(self, exception)
def HandleSuccess(self):
"""Handle a successful build.
This function is called whenever the cbuildbot run is successful.
For the master, this will only be called when all slave builders
are also successful. This function may be overridden by subclasses.
# We only promote for the pfq, not chrome pfq.
# TODO(build): Run this logic in debug mode too.
if (not self._run.options.debug and
cbuildbot_config.IsPFQType(self._run.config.build_type) and
self._run.config.master and
self._run.manifest_branch == 'master' and
self._run.config.build_type != constants.CHROME_PFQ_TYPE):
if MasterSlaveSyncStage.sub_manager:
def HandleFailure(self, failing, inflight):
"""Handle a build failure.
This function is called whenever the cbuildbot run fails.
For the master, this will be called when any slave fails or times
out. This function may be overridden by subclasses.
failing: The names of the failing builders.
inflight: The names of the builders that are still running.
if failing:
elif inflight:
def HandleValidationFailure(self, failing):
'The following builders failed with this manifest:',
', '.join(sorted(failing)),
'Please check the logs of the failing builders for details.']))
def HandleValidationTimeout(self, inflight_statuses):
'The following builders took too long to finish:',
', '.join(sorted(inflight_statuses)),
'Please check the logs of these builders for details.']))
def PerformStage(self):
# Upload our pass/fail status to Google Storage.
success=self.success, message=self.message,
statuses = self._FetchSlaveStatuses()
self._slave_statuses = statuses
no_stat = set(builder for builder, status in statuses.iteritems()
if status is None)
failing = set(builder for builder, status in statuses.iteritems()
if status and status.Failed())
inflight = set(builder for builder, status in statuses.iteritems()
if status and status.Inflight())
# If all the failing or inflight builders were sanity checkers
# then ignore the failure.
fatal = self._IsFailureFatal(failing, inflight, no_stat)
if fatal:
self._AnnotateFailingBuilders(failing, inflight, no_stat, statuses)
self.HandleFailure(failing, inflight)
raise ImportantBuilderFailedException()
def _IsFailureFatal(self, failing, inflight, no_stat):
"""Returns a boolean indicating whether the build should fail.
failing: Set of builder names of slave builders that failed.
inflight: Set of builder names of slave builders that are inflight
no_stat: Set of builder names of slave builders that had status None.
True if any of the failing or inflight builders are not sanity check
builders for this master, or if there were any non-sanity-check builders
with status None.
sanity_builders = self._run.config.sanity_check_slaves or []
sanity_builders = set(sanity_builders)
return not sanity_builders.issuperset(failing | inflight | no_stat)
def _AnnotateFailingBuilders(self, failing, inflight, no_stat, statuses):
"""Add annotations that link to either failing or inflight builders.
Adds buildbot links to failing builder dashboards. If no builders are
failing, adds links to inflight builders. Adds step text for builders
with status None.
failing: Set of builder names of slave builders that failed.
inflight: Set of builder names of slave builders that are inflight.
no_stat: Set of builder names of slave builders that had status None.
statuses: A builder-name->status dictionary, which will provide
the dashboard_url values for any links.
builders_to_link = failing or inflight or []
for builder in builders_to_link:
if statuses[builder].dashboard_url:
for builder in no_stat:
cros_build_lib.PrintBuildbotStepText('%s did not start.' % builder)
def GetSlaveStatuses(self):
"""Returns cached slave status results.
Cached results are populated during PerformStage, so this function
should only be called after PerformStage has returned.
A dictionary from build names to manifest_version.BuilderStatus
builder status objects.
return self._slave_statuses
class CommitQueueCompletionStage(MasterSlaveSyncCompletionStage):
"""Commits or reports errors to CL's that failed to be validated."""
def HandleSuccess(self):
if self._run.config.master:
# After submitting the pool, update the commit hashes for uprevved
# ebuilds.
manifest = git.ManifestCheckout.Cached(self._build_root)
self.sync_stage.pool.changes, self._build_root, manifest)
if cbuildbot_config.IsPFQType(self._run.config.build_type):
super(CommitQueueCompletionStage, self).HandleSuccess()
def HandleFailure(self, failing, inflight):
"""Handle a build failure or timeout in the Commit Queue.
This function performs any tasks that need to happen when the Commit Queue
- Abort the HWTests if necessary.
- Push any CLs that indicate that they don't care about this failure.
- Reject the rest of the changes, but only if the sanity check builders
did NOT fail.
See MasterSlaveSyncCompletionStage.HandleFailure.
failing: Names of the builders that failed.
inflight: Names of the builders that timed out.
# Print out the status about what builds failed or not.
MasterSlaveSyncCompletionStage.HandleFailure(self, failing, inflight)
# Abort hardware tests to save time if we have already seen a failure,
# except in the case where the only failure is a hardware test failure.
# When we're debugging hardware test failures, it's useful to see the
# results on all platforms, to see if the failure is platform-specific.
tracebacks = results_lib.Results.GetTracebacks()
if not self.success and self._run.config['important']:
if len(tracebacks) != 1 or tracebacks[0].failed_prefix != 'HWTest':
if self._run.config.master:
# Even if there was a failure, we can submit the changes that indicate
# that they don't care about this failure.
messages = [self._slave_statuses[x].message for x in failing]
if failing and not inflight:
tracebacks = set()
for message in messages:
# If there are no tracebacks, that means that the builder did not
# report its status properly. Don't submit anything.
if not message.tracebacks:
rejected = self.sync_stage.pool.SubmitPartialPool(tracebacks)
self.sync_stage.pool.changes = rejected
sanity = self._WasBuildSane(
self._run.config.sanity_check_slaves, self._slave_statuses)
if not sanity:'Detected that a sanity-check builder failed. Will not '
'reject patches.')
if failing:
self.sync_stage.pool.HandleValidationFailure(messages, sanity=sanity)
elif inflight:
def _WasBuildSane(sanity_check_slaves, slave_statuses):
"""Determines weather any of the sanity check slaves failed."""
sanity_check_slaves = sanity_check_slaves or []
# Ignore any sanity_check_slaves builders for which we do not have a
# status (perhaps because they timed out or never ran).
# Of those that do have a status, if any of them failed,
# call the build not sane.
return not any([slave_statuses.get(x) is not None and
for x in sanity_check_slaves])
def PerformStage(self):
# - If the build failed, and the builder was important, fetch a message
# listing the patches which failed to be validated. This message is sent
# along with the failed status to the master to indicate a failure.
# - This is skipped when sync_stage did not apply a validation pool. For
# instance on builders with do_not_apply_cq_patches=True, sync_stage will
# be a MasterSlaveSyncStage and not have a |pool| attribute.
if (not self.success and self._run.config.important
and hasattr(self.sync_stage, 'pool')):
self.message = self.sync_stage.pool.GetValidationFailedMessage()
super(CommitQueueCompletionStage, self).PerformStage()
success=self.success, message=self.message)
class PreCQSyncStage(SyncStage):
"""Sync and apply patches to test if they compile."""
def __init__(self, builder_run, patches, **kwargs):
super(PreCQSyncStage, self).__init__(builder_run, **kwargs)
# The list of patches to test.
self.patches = patches
# The ValidationPool of patches to test. Initialized in PerformStage, and
# refreshed after bootstrapping by HandleSkip.
self.pool = None
def HandleSkip(self):
"""Handles skip and loads validation pool from disk."""
super(PreCQSyncStage, self).HandleSkip()
filename = self._run.options.validation_pool
if filename:
self.pool = validation_pool.ValidationPool.Load(filename)
def PerformStage(self):
super(PreCQSyncStage, self).PerformStage()
self.pool = validation_pool.ValidationPool.AcquirePreCQPool(
self._run.config.overlays, self._build_root,
dryrun=self._run.options.debug_forced, changes=self.patches)
class PreCQCompletionStage(bs.BuilderStage):
"""Reports the status of a trybot run to Google Storage and Gerrit."""
def __init__(self, builder_run, sync_stage, success, **kwargs):
super(PreCQCompletionStage, self).__init__(builder_run, **kwargs)
self.sync_stage = sync_stage
self.success = success
def PerformStage(self):
# Update Gerrit and Google Storage with the Pre-CQ status.
if self.success:
message = self.sync_stage.pool.GetValidationFailedMessage()
class PreCQLauncherStage(SyncStage):
"""Scans for CLs and automatically launches Pre-CQ jobs to test them."""
STATUS_INFLIGHT = validation_pool.ValidationPool.STATUS_INFLIGHT
STATUS_PASSED = validation_pool.ValidationPool.STATUS_PASSED
STATUS_FAILED = validation_pool.ValidationPool.STATUS_FAILED
STATUS_LAUNCHING = validation_pool.ValidationPool.STATUS_LAUNCHING
STATUS_WAITING = validation_pool.ValidationPool.STATUS_WAITING
# The number of minutes we allow before considering a launch attempt failed.
# If this window isn't hit in a given launcher run, the window will start
# again from scratch in the next run.
# The maximum number of patches we will allow in a given trybot run. This is
# needed because our trybot infrastructure can only handle so many patches at
# once.
def __init__(self, builder_run, **kwargs):
super(PreCQLauncherStage, self).__init__(builder_run, **kwargs)
self.skip_sync = True
self.launching = {}
self.retried = set()
def _HasLaunchTimedOut(self, change):
"""Check whether a given |change| has timed out on its trybot launch.
Assumes that the change is in the middle of being launched.
True if the change has timed out. False otherwise.
diff = datetime.timedelta(minutes=self.LAUNCH_DELAY)
return - self.launching[change] > diff
def GetPreCQStatus(self, pool, changes):
"""Get the Pre-CQ status of a list of changes.
pool: The validation pool.
changes: Changes to examine.
busy: The set of CLs that are currently being tested.
passed: The set of CLs that have been verified.
busy, passed = set(), set()
for change in changes:
status = pool.GetCLStatus(PRE_CQ, change)
if status != self.STATUS_LAUNCHING:
# The trybot has finished launching, so we should remove it from our
# data structures.
self.launching.pop(change, None)
if status == self.STATUS_LAUNCHING:
# The trybot is in the process of launching.
if change not in self.launching:
self.launching[change] =
elif self._HasLaunchTimedOut(change):
if change in self.retried:
msg = ('We were not able to launch a pre-cq trybot for your change.'
'This problem can happen if the trybot waterfall is very '
'busy, or if there is an infrastructure issue. Please '
'notify the sheriff and mark your change as ready again. If '
'this problem occurs multiple times in a row, please file a '
pool.SendNotification(change, '%(details)s', details=msg)
pool.UpdateCLStatus(PRE_CQ, change, self.STATUS_FAILED,
# Try the change again.
pool.UpdateCLStatus(PRE_CQ, change, self.STATUS_WAITING,
elif status == self.STATUS_INFLIGHT:
# Once a Pre-CQ run actually starts, it'll set the status to
elif status == self.STATUS_FAILED:
# The Pre-CQ run failed for this change. It's possible that we got
# unlucky and this change was just marked as 'Not Ready' by a bot. To
# test this, mark the CL as 'waiting' for now. If the CL is still marked
# as 'Ready' next time we check, we'll know the CL is truly still ready.
pool.UpdateCLStatus(PRE_CQ, change, self.STATUS_WAITING,
elif status == self.STATUS_PASSED:
return busy, passed
def LaunchTrybot(self, pool, plan):
"""Launch a Pre-CQ run with the provided list of CLs.
pool: ValidationPool corresponding to |plan|.
plan: The list of patches to test in the Pre-CQ run.
cmd = ['cbuildbot', '--remote', constants.PRE_CQ_BUILDER_NAME]
if self._run.options.debug:
for patch in plan:
number = cros_patch.FormatGerritNumber(
patch.gerrit_number, force_internal=patch.internal)
cmd += ['-g', number]
cros_build_lib.RunCommand(cmd, cwd=self._build_root)
for patch in plan:
if pool.GetCLStatus(PRE_CQ, patch) != self.STATUS_PASSED:
pool.UpdateCLStatus(PRE_CQ, patch, self.STATUS_LAUNCHING,
def GetDisjointTransactionsToTest(self, pool, changes):
"""Get the list of disjoint transactions to test.
A list of disjoint transactions to test. Each transaction should be sent
to a different Pre-CQ trybot.
busy, passed = self.GetPreCQStatus(pool, changes)
# Create a list of disjoint transactions to test.
manifest = git.ManifestCheckout.Cached(self._build_root)
plans = pool.CreateDisjointTransactions(
manifest, max_txn_length=self.MAX_PATCHES_PER_TRYBOT_RUN)
for plan in plans:
# If any of the CLs in the plan are currently "busy" being tested,
# wait until they're done before launching our trybot run. This helps
# avoid race conditions.
# Similarly, if all of the CLs in the plan have already been validated,
# there's no need to launch a trybot run.
plan = set(plan)
if plan.issubset(passed):'CLs already verified: %r', ' '.join(map(str, plan)))
elif plan.intersection(busy):'CLs currently being verified: %r',
' '.join(map(str, plan.intersection(busy))))
if plan.difference(busy):'CLs waiting on verification of dependencies: %r',
' '.join(map(str, plan.difference(busy))))
yield plan
def ProcessChanges(self, pool, changes, _non_manifest_changes):
"""Process a list of changes that were marked as Ready.
From our list of changes that were marked as Ready, we create a
list of disjoint transactions and send each one to a separate Pre-CQ
Non-manifest changes are just submitted here because they don't need to be
verified by either the Pre-CQ or CQ.
# Submit non-manifest changes if we can.
if timeout_util.IsTreeOpen(
# Launch trybots for manifest changes.
for plan in self.GetDisjointTransactionsToTest(pool, changes):
self.LaunchTrybot(pool, plan)
# Tell ValidationPool to keep waiting for more changes until we hit
# its internal timeout.
return [], []
def PerformStage(self):
# Setup and initialize the repo.
super(PreCQLauncherStage, self).PerformStage()
# Loop through all of the changes until we hit a timeout.
self._run.config.overlays, self.repo,
check_tree_open=False, change_filter=self.ProcessChanges)
class BranchError(Exception):
"""Raised by branch creation code on error."""
class BranchUtilStage(bs.BuilderStage):
"""Creates, deletes and renames branches, depending on cbuildbot options.
The two main types of branches are release branches and non-release
branches. Release branches have the form 'release-*' - e.g.,
On a very basic level, a branch is created by parsing the manifest of a
specific version of Chrome OS (e.g., 4319.0.0), and creating the branch
remotely for each checkout in the manifest at the specified hash.
Once a branch is created however, the branch component of the version on the
newly created branch needs to be incremented. Additionally, in some cases
the Chrome major version (i.e, R29) and/or the Chrome OS version (i.e.,
4319.0.0) of the source branch must be incremented
(see _IncrementVersionOnDiskForSourceBranch docstring). Finally, the external
and internal manifests of the new branch need to be fixed up (see
FixUpManifests docstring).
COMMIT_MESSAGE = 'Bump %(target)s after branching %(branch)s'
def __init__(self, builder_run, **kwargs):
super(BranchUtilStage, self).__init__(builder_run, **kwargs)
self.dryrun = self._run.options.debug_forced
self.branch_name = self._run.options.branch_name
self.rename_to = self._run.options.rename_to
def _RunPush(self, checkout, src_ref, dest_ref, force=False):
"""Perform a git push for a checkout.
checkout: A dictionary of checkout manifest attributes.
src_ref: The source local ref to push to the remote.
dest_ref: The local remote ref that correspond to destination ref name.
force: Whether to override non-fastforward checks.
# Convert local tracking ref to refs/heads/* on a remote:
# refs/remotes/<remote name>/<branch> to refs/heads/<branch>.
# If dest_ref is already refs/heads/<branch> it's a noop.
dest_ref = git.NormalizeRef(git.StripRefs(dest_ref))
push_to = git.RemoteRef(checkout['push_remote'], dest_ref)
git.GitPush(checkout['local_path'], src_ref, push_to, dryrun=self.dryrun,
def _FetchAndCheckoutTo(self, checkout_dir, remote_ref):
"""Fetch a remote ref and check out to it.
checkout_dir: Path to git repo to operate on.
remote_ref: A git.RemoteRef object.
git.RunGit(checkout_dir, ['fetch', remote_ref.remote, remote_ref.ref],
git.RunGit(checkout_dir, ['checkout', 'FETCH_HEAD'], print_cmd=True)
def _GetBranchSuffix(self, manifest, checkout):
"""Return the branch suffix for the given checkout.
If a given project is checked out to multiple locations, it is necessary
to append a branch suffix. To be safe, we append branch suffixes for all
repositories that use a non-standard branch name (e.g., if our default
revision is "master", then any repository which does not use "master"
has a non-standard branch name.)
manifest: The associated ManifestCheckout.
checkout: The associated ProjectCheckout.
# Get the default and tracking branch.
suffix = ''
if len(manifest.FindCheckouts(checkout['name'])) > 1:
default_branch = git.StripRefs(manifest.default['revision'])
tracking_branch = git.StripRefs(checkout['tracking_branch'])
suffix = '-%s' % (tracking_branch,)
if default_branch != 'master':
suffix = re.sub('^-%s-' % re.escape(default_branch), '-', suffix)
return suffix
def _GetSHA1(self, checkout, branch):
"""Get the SHA1 for the specified |branch| in the specified |checkout|.
checkout: The ProjectCheckout to look in.
branch: Remote branch to look for.
If the branch exists, returns the SHA1 of the branch. Otherwise, returns
the empty string. If branch is None, return None.
if branch:
cmd = ['show-ref', branch]
result = git.RunGit(checkout['local_path'], cmd, error_code_ok=True)
if result.returncode == 0:
# Output looks like:
# a00733b...30ee40e0c2c1 refs/remotes/cros/test-4980.B
return result.output.strip().split()[0]
return ''
def _CopyBranch(self, src_checkout, src_branch, dst_branch, force=False):
"""Copy the given |src_branch| to |dst_branch|.
src_checkout: The ProjectCheckout to work in.
src_branch: The remote branch ref to copy from.
dst_branch: The remote branch ref to copy to.
force: If True then execute the copy even if dst_branch exists.
cros_build_lib.Info('Creating new branch "%s" for %s.',
dst_branch, src_checkout['name'])
self._RunPush(src_checkout, src_ref=src_branch, dest_ref=dst_branch,
def _DeleteBranch(self, src_checkout, branch):
"""Delete the given |branch| in the given |src_checkout|.
src_checkout: The ProjectCheckout to work in.
branch: The branch ref to delete. Must be a remote branch.
cros_build_lib.Info('Deleting branch "%s" for %s.',
branch, src_checkout['name'])
self._RunPush(src_checkout, src_ref='', dest_ref=branch)
def _ProcessCheckout(self, src_manifest, src_checkout):
"""Performs per-checkout push operations.
src_manifest: The ManifestCheckout object for the current manifest.
src_checkout: The ProjectCheckout object to process.
if not src_checkout.IsBranchableProject():
# We don't have the ability to push branches to this repository. Just
# use TOT instead.
checkout_name = src_checkout['name']
remote = src_checkout['push_remote']
src_ref = src_checkout['revision']
suffix = self._GetBranchSuffix(src_manifest, src_checkout)
# The source/destination branches depend on options.
if self.rename_to:
# Rename flow. Both src and dst branches exist.
src_branch = '%s%s' % (self.branch_name, suffix)
dst_branch = '%s%s' % (self.rename_to, suffix)
elif self._run.options.delete_branch:
# Delete flow. Only dst branch exists.
src_branch = None
dst_branch = '%s%s' % (self.branch_name, suffix)
# Create flow (default). Only dst branch exists. Source
# for the branch will just be src_ref.
src_branch = None
dst_branch = '%s%s' % (self.branch_name, suffix)
# Normalize branch refs to remote. We only process remote branches.
src_branch = git.NormalizeRemoteRef(remote, src_branch)
dst_branch = git.NormalizeRemoteRef(remote, dst_branch)
# Determine whether src/dst branches exist now, by getting their sha1s.
if src_branch:
src_sha1 = self._GetSHA1(src_checkout, src_branch)
elif git.IsSHA1(src_ref):
src_sha1 = src_ref
dst_sha1 = self._GetSHA1(src_checkout, dst_branch)
# Complain if the branch already exists, unless that is expected.
force = self._run.options.force_create or self._run.options.delete_branch
if dst_sha1 and not force:
# We are either creating a branch or renaming a branch, and the
# destination branch unexpectedly exists. Accept this only if the
# destination branch is already at the revision we want.
if src_sha1 != dst_sha1:
raise BranchError('Checkout %s already contains branch %s. Run with '
'--force-create to overwrite.'
% (checkout_name, dst_branch))
cros_build_lib.Info('Checkout %s already contains branch %s and it '
'already points to revision %s', checkout_name,
dst_branch, dst_sha1)
elif self._run.options.delete_branch:
# Delete the dst_branch, if it exists.
if dst_sha1:
self._DeleteBranch(src_checkout, dst_branch)
raise BranchError('Checkout %s does not contain branch %s to delete.'
% (checkout_name, dst_branch))
elif self.rename_to:
# Copy src_branch to dst_branch, if it exists, then delete src_branch.
if src_sha1:
self._CopyBranch(src_checkout, src_branch, dst_branch)
self._DeleteBranch(src_checkout, src_branch)
raise BranchError('Checkout %s does not contain branch %s to rename.'
% (checkout_name, src_branch))
# Copy src_ref to dst_branch.
self._CopyBranch(src_checkout, src_ref, dst_branch,
def _UpdateManifest(self, manifest_path):
"""Rewrite |manifest_path| to point at the right branch.
manifest_path: The path to the manifest file.
src_manifest = git.ManifestCheckout.Cached(self._build_root,
doc = ElementTree.parse(manifest_path)
root = doc.getroot()
# Use the local branch ref.
new_branch_name = self.rename_to if self.rename_to else self.branch_name
new_branch_name = git.NormalizeRef(new_branch_name)
for node in root.findall('project'):
path = node.attrib['path']
checkout = src_manifest.FindCheckoutFromPath(path)
if checkout.IsBranchableProject():
# Point at the new branch.
node.attrib.pop('revision', None)
node.attrib.pop('upstream', None)
suffix = self._GetBranchSuffix(src_manifest, checkout)
if suffix:
node.attrib['revision'] = '%s%s' % (new_branch_name, suffix)
# We can't branch this repository. Just use TOT of the repository.
node.attrib['revision'] = checkout['revision']
# Can not use the default version of get() here since
# 'upstream' can be a valid key with a None value.
upstream = checkout.get('upstream')
if upstream is not None:
node.attrib['upstream'] = upstream
for node in root.findall('default'):
node.attrib['revision'] = new_branch_name
def _FixUpManifests(self, repo_manifest):
"""Points the checkouts at the new branch in the manifests.
Within the branch, make sure all manifests with projects that are
"branchable" are checked out to "refs/heads/<new_branch>". Do this
by updating all manifests in the known manifest projects.
assert not self._run.options.delete_branch, 'Cannot fix a deleted branch.'
# Use local branch ref.
branch_ref = git.NormalizeRef(self.branch_name)
cros_build_lib.Debug('Fixing manifest projects for new branch.')
for project in constants.MANIFEST_PROJECTS:
manifest_checkout = repo_manifest.FindCheckout(project)
manifest_dir = manifest_checkout['local_path']
push_remote = manifest_checkout['push_remote']
# Checkout revision can be either a sha1 or a branch ref.
src_ref = manifest_checkout['revision']
if not git.IsSHA1(src_ref):
src_ref = git.NormalizeRemoteRef(push_remote, src_ref)
manifest_dir, manifest_version.PUSH_BRANCH, src_ref)
# Look for all manifest files in manifest_dir.
for manifest_path in glob.glob(os.path.join(manifest_dir, '*.xml')):
# Accept only non-symlink xml files directly in manifest_dir.
if not os.path.islink(manifest_path):
cros_build_lib.Debug('Fixing manifest at %s.', manifest_path)
git.RunGit(manifest_dir, ['add', '-A'], print_cmd=True)
message = 'Fix up manifest after branching %s.' % branch_ref
git.RunGit(manifest_dir, ['commit', '-m', message], print_cmd=True)
push_to = git.RemoteRef(push_remote, branch_ref)
git.GitPush(manifest_dir, manifest_version.PUSH_BRANCH, push_to,
dryrun=self.dryrun, force=self.dryrun)
def _IncrementVersionOnDisk(self, incr_type, push_to, message):
"""Bumps the version found in on a branch.
incr_type: See docstring for manifest_version.VersionInfo.
push_to: A git.RemoteRef object.
message: The message to give the git commit that bumps the version.
version_info = manifest_version.VersionInfo.from_repo(
self._build_root, incr_type=incr_type)
version_info.UpdateVersionFile(message, dry_run=self.dryrun,
def DetermineBranchIncrParams(version_info):
"""Determines the version component to bump for the new branch."""
# We increment the left-most component that is zero.
if version_info.branch_build_number != '0':
if version_info.patch_number != '0':
raise BranchError('Version %s cannot be branched.' %
return 'patch', 'patch number'
return 'branch', 'branch number'
def DetermineSourceIncrParams(source_name, dest_name):
"""Determines the version component to bump for the original branch."""
if dest_name.startswith('refs/heads/release-'):
return 'chrome_branch', 'Chrome version'
elif source_name == 'refs/heads/master':
return 'build', 'build number'
return 'branch', 'branch build number'
def _IncrementVersionOnDiskForNewBranch(self, push_remote):
"""Bumps the version found in on the new branch
When a new branch is created, the branch component of the new branch's
version needs to bumped.
For example, say 'stabilize-link' is created from a the 4230.0.0 manifest.
The new branch's version needs to be bumped to 4230.1.0.
push_remote: a git remote name where the new branch lives.
# This needs to happen before the source branch version bumping above
# because we rely on the fact that since our current overlay checkout
# is what we just pushed to the new branch, we don't need to do another
# sync. This also makes it easier to implement dryrun functionality (the
# new branch doesn't actually get created in dryrun mode).
# Use local branch ref.
branch_ref = git.NormalizeRef(self.branch_name)
push_to = git.RemoteRef(push_remote, branch_ref)
version_info = manifest_version.VersionInfo(
incr_type, incr_target = self.DetermineBranchIncrParams(version_info)
message = self.COMMIT_MESSAGE % {
'target': incr_target,
'branch': branch_ref,
self._IncrementVersionOnDisk(incr_type, push_to, message)
def _IncrementVersionOnDiskForSourceBranch(self, overlay_dir, push_remote,
"""Bumps the version found in on the source branch
The source branch refers to the branch that the manifest used for creating
the new branch came from. For release branches, we generally branch from a
'master' branch manifest.
To work around, for both non-release and release branches,
we need to bump the Chrome OS version on the source branch if the manifest
used for branch creation is the latest generated manifest for the source
When we are creating a release branch, the Chrome major version of the
'master' (source) branch needs to be bumped. For example, if we branch
'release-R29-4230.B' from the 4230.0.0 manifest (which is from the 'master'
branch), the 'master' branch's Chrome major version in
(which is 29) needs to be bumped to 30.
overlay_dir: Absolute path to the chromiumos overlay repo.
push_remote: The remote to push to.
source_branch: The branch that the manifest we are using comes from.
push_to = git.RemoteRef(push_remote, source_branch)
self._FetchAndCheckoutTo(overlay_dir, push_to)
# Use local branch ref.
branch_ref = git.NormalizeRef(self.branch_name)
tot_version_info = manifest_version.VersionInfo.from_repo(self._build_root)
if (branch_ref.startswith('refs/heads/release-') or
tot_version_info.VersionString() == self._run.options.force_version):
incr_type, incr_target = self.DetermineSourceIncrParams(
source_branch, branch_ref)
message = self.COMMIT_MESSAGE % {
'target': incr_target,
'branch': branch_ref,
self._IncrementVersionOnDisk(incr_type, push_to, message)
except cros_build_lib.RunCommandError:
# There's a chance we are racing against the buildbots for this
# increment. We shouldn't quit the script because of this. Instead, we
# print a warning.
self._FetchAndCheckoutTo(overlay_dir, push_to)
new_version = manifest_version.VersionInfo.from_repo(self._build_root)
if new_version.VersionString() != tot_version_info.VersionString():
logging.warning('Version number for branch %s was bumped by another '
'bot.', push_to.ref)
def PerformStage(self):
"""Run the branch operation."""
# Setup and initialize the repo.
super(BranchUtilStage, self).PerformStage()
repo_manifest = git.ManifestCheckout.Cached(self._build_root)
checkouts = repo_manifest.ListCheckouts()
'Processing %d checkouts from manifest in parallel.', len(checkouts))
args = [[repo_manifest, x] for x in checkouts]
parallel.RunTasksInProcessPool(self._ProcessCheckout, args, processes=16)
if not self._run.options.delete_branch:
# Increment versions for a new branch.
if not (self._run.options.delete_branch or self.rename_to):
overlay_name = 'chromiumos/overlays/chromiumos-overlay'
overlay_checkout = repo_manifest.FindCheckout(overlay_name)
overlay_dir = overlay_checkout['local_path']
push_remote = overlay_checkout['push_remote']
source_branch = repo_manifest.default['revision']
self._IncrementVersionOnDiskForSourceBranch(overlay_dir, push_remote,
class RefreshPackageStatusStage(bs.BuilderStage):
"""Stage for refreshing Portage package status in online spreadsheet."""
def PerformStage(self):
class InitSDKStage(bs.BuilderStage):
"""Stage that is responsible for initializing the SDK."""
option_name = 'build'
def __init__(self, builder_run, chroot_replace=False, **kwargs):
"""InitSDK constructor.
builder_run: Builder run instance for this run.
chroot_replace: If True, force the chroot to be replaced.
super(InitSDKStage, self).__init__(builder_run, **kwargs)
self._env = {}
self.force_chroot_replace = chroot_replace
if self._run.options.clobber:
self._latest_toolchain = (self._run.config.latest_toolchain or
if self._latest_toolchain and self._run.config.gcc_githash:
self._env['USE'] = 'git_gcc'
self._env['GCC_GITHASH'] = self._run.config.gcc_githash
def PerformStage(self):
chroot_path = os.path.join(self._build_root, constants.DEFAULT_CHROOT_DIR)
replace = self._run.config.chroot_replace or self.force_chroot_replace
pre_ver = post_ver = None
if os.path.isdir(self._build_root) and not replace:
pre_ver = cros_build_lib.GetChrootVersion(chroot=chroot_path)
except results_lib.BuildScriptFailure:
cros_build_lib.PrintBuildbotStepText('Replacing broken chroot')
replace = True
if not os.path.isdir(chroot_path) or replace:
use_sdk = (self._run.config.use_sdk and not self._run.options.nosdk)
pre_ver = None
post_ver = cros_build_lib.GetChrootVersion(chroot=chroot_path)
if pre_ver is not None and pre_ver != post_ver:
cros_build_lib.PrintBuildbotStepText('%s->%s' % (pre_ver, post_ver))
class SetupBoardStage(InitSDKStage):
"""Stage that is responsible for building host pkgs and setting up a board."""
option_name = 'build'
def __init__(self, builder_run, boards=None, **kwargs):
super(SetupBoardStage, self).__init__(builder_run, **kwargs)
if boards is not None:
self._boards = boards
def PerformStage(self):
# Calculate whether we should use binary packages.
usepkg = (self._run.config.usepkg_setup_board and
not self._latest_toolchain)
# We need to run chroot updates on most builders because they uprev after
# the InitSDK stage. For the SDK builder, we can skip updates because uprev
# is run prior to InitSDK. This is not just an optimization: It helps
# workaround
chroot_upgrade = (
self._run.config.build_type != constants.CHROOT_BUILDER_TYPE)
# Iterate through boards to setup.
chroot_path = os.path.join(self._build_root, constants.DEFAULT_CHROOT_DIR)
for board_to_build in self._boards:
# Only update the board if we need to do so.
board_path = os.path.join(chroot_path, 'build', board_to_build)
if os.path.isdir(board_path) and not chroot_upgrade:
self._build_root, board=board_to_build, usepkg=usepkg,
extra_env=self._env, chroot_upgrade=chroot_upgrade,
profile=self._run.options.profile or self._run.config.profile)
chroot_upgrade = False
class UprevStage(bs.BuilderStage):
"""Stage that uprevs Chromium OS packages that the builder intends to
option_name = 'uprev'
def __init__(self, builder_run, boards=None, enter_chroot=True, **kwargs):
super(UprevStage, self).__init__(builder_run, **kwargs)
self._enter_chroot = enter_chroot
if boards is not None:
self._boards = boards
def PerformStage(self):
# Perform other uprevs.
if self._run.config.uprev:
overlays, _ = self._ExtractOverlays()
class SyncChromeStage(bs.BuilderStage):
"""Stage that syncs Chrome sources if needed."""
option_name = 'managed_chrome'
def __init__(self, builder_run, **kwargs):
super(SyncChromeStage, self).__init__(builder_run, **kwargs)
# PerformStage() will fill this out for us.
# TODO(mtennant): Replace with a run param.
self.chrome_version = None
def PerformStage(self):
# Perform chrome uprev.
chrome_atom_to_build = None
if self._chrome_rev:
chrome_atom_to_build = commands.MarkChromeAsStable(
self._build_root, self._run.manifest_branch,
self._chrome_rev, self._boards,
kwargs = {}
if self._chrome_rev == constants.CHROME_REV_SPEC:
kwargs['revision'] = self._run.options.chrome_version
cpv = None
cros_build_lib.PrintBuildbotStepText('revision %s' % kwargs['revision'])
self.chrome_version = self._run.options.chrome_version
cpv = portage_utilities.BestVisible(constants.CHROME_CP,
kwargs['tag'] = cpv.version_no_rev.partition('_')[0]
cros_build_lib.PrintBuildbotStepText('tag %s' % kwargs['tag'])
self.chrome_version = kwargs['tag']
useflags = self._run.config.useflags
commands.SyncChrome(self._build_root, self._run.options.chrome_root,
useflags, **kwargs)
if (self._chrome_rev and not chrome_atom_to_build and
self._run.options.buildbot and
self._run.config.build_type == constants.CHROME_PFQ_TYPE):
cros_build_lib.Info('Chrome already uprevved')
def _Finish(self):
"""Provide chrome_version to the rest of the run."""
# Even if the stage failed, a None value for chrome_version still
# means something. In other words, this stage tried to run.
self._run.attrs.chrome_version = self.chrome_version
super(SyncChromeStage, self)._Finish()
class PatchChromeStage(bs.BuilderStage):
"""Stage that applies Chrome patches if needed."""
option_name = 'rietveld_patches'
def PerformStage(self):
for patch in ' '.join(self._run.options.rietveld_patches).split():
patch, colon, subdir = patch.partition(':')
if not colon:
subdir = 'src'
commands.PatchChrome(self._run.options.chrome_root, patch, subdir)
class BuildPackagesStage(ArchivingStage):
"""Build Chromium OS packages."""
option_name = 'build'
def __init__(self, builder_run, board, archive_stage,
pgo_generate=False, pgo_use=False, **kwargs):
super(BuildPackagesStage, self).__init__(builder_run, board,
archive_stage, **kwargs)
self._pgo_generate, self._pgo_use = pgo_generate, pgo_use
assert not pgo_generate or not pgo_use
useflags = self._run.config.useflags[:]
if pgo_generate: += ' [%s]' % constants.USE_PGO_GENERATE
elif pgo_use: += ' [%s]' % constants.USE_PGO_USE
self._env = {}
if useflags:
self._env['USE'] = ' '.join(useflags)
if self._run.options.chrome_root:
if self._run.options.clobber:
self._build_autotest = (self._run.config.build_tests and
def _GetArchitectures(self):
"""Get the list of architectures built by this builder."""
return set(self._GetPortageEnvVar('ARCH', b) for b in self._boards)
def PerformStage(self):
# Wait for PGO data to be ready if needed.
if self._pgo_use:
cpv = portage_utilities.BestVisible(constants.CHROME_CP,
commands.WaitForPGOData(self._GetArchitectures(), cpv)
# If we have rietveld patches, always compile Chrome from source.
noworkon = not self._run.options.rietveld_patches
class ChromeSDKStage(ArchivingStage):
"""Run through the simple chrome workflow."""
def __init__(self, *args, **kwargs):
super(ChromeSDKStage, self).__init__(*args, **kwargs)
self._upload_queue = multiprocessing.Queue()
self._pkg_dir = os.path.join(
self._build_root, constants.DEFAULT_CHROOT_DIR,
'build', self._current_board, 'var', 'db', 'pkg')
self.chrome_src = os.path.join(self._run.options.chrome_root, 'src')
self.out_board_dir = os.path.join(
self.chrome_src, 'out_%s' % self._current_board)
def _BuildAndArchiveChromeSysroot(self):
"""Generate and upload sysroot for building Chrome."""
assert self.archive_path.startswith(self._build_root)
extra_env = {}
if self._run.config.useflags:
extra_env['USE'] = ' '.join(self._run.config.useflags)
in_chroot_path = git.ReinterpretPathForChroot(self.archive_path)
cmd = ['cros_generate_sysroot', '--out-dir', in_chroot_path, '--board',
self._current_board, '--package', constants.CHROME_CP]
cros_build_lib.RunCommand(cmd, cwd=self._build_root, enter_chroot=True,
def _ArchiveChromeEbuildEnv(self):
"""Generate and upload Chrome ebuild environment."""
chrome_dir = self.archive_stage.SingleMatchGlob(
os.path.join(self._pkg_dir, constants.CHROME_CP) + '-*')
env_bzip = os.path.join(chrome_dir, 'environment.bz2')
with osutils.TempDir(prefix='chrome-sdk-stage') as tempdir:
# Convert from bzip2 to tar format.
bzip2 = cros_build_lib.FindCompressor(cros_build_lib.COMP_BZIP2)
[bzip2, '-d', env_bzip, '-c'],
log_stdout_to_file=os.path.join(tempdir, constants.CHROME_ENV_FILE))
env_tar = os.path.join(self.archive_path, constants.CHROME_ENV_TAR)
cros_build_lib.CreateTarball(env_tar, tempdir)
def _VerifyChromeDeployed(self, tempdir):
"""Check to make sure deploy_chrome ran correctly."""
if not os.path.exists(os.path.join(tempdir, 'chrome')):
raise AssertionError('deploy_chrome did not run successfully!')
def _VerifySDKEnvironment(self):
"""Make sure the SDK environment is set up properly."""
# If the environment wasn't set up, then the output directory wouldn't be
# created after 'gclient runhooks'.
# TODO: Make this check actually look at the environment.
if not os.path.exists(self.out_board_dir):
raise AssertionError('%s not created!' % self.out_board_dir)
def _BuildChrome(self, sdk_cmd):
"""Use the generated SDK to build Chrome."""
# Validate fetching of the SDK and setting everything up.
# Actually build chromium.
sdk_cmd.Run(['gclient', 'runhooks'])
def _TestDeploy(self, sdk_cmd):
"""Test SDK deployment."""
with osutils.TempDir(prefix='chrome-sdk-stage') as tempdir:
# Use the TOT deploy_chrome.
script_path = os.path.join(
self._build_root, constants.CHROMITE_BIN_SUBDIR, 'deploy_chrome')
sdk_cmd.Run([script_path, '--build-dir',
os.path.join(self.out_board_dir, 'Release'),
'--staging-only', '--staging-dir', tempdir])
def PerformStage(self):
if platform.dist()[-1] == 'lucid':
# Chrome no longer builds on Lucid. See
print 'Ubuntu lucid is no longer supported.'
print 'Please upgrade to Ubuntu Precise.'
upload_metadata = functools.partial(
self.UploadMetadata, upload_queue=self._upload_queue)
steps = [self._BuildAndArchiveChromeSysroot, self._ArchiveChromeEbuildEnv,
with self.ArtifactUploader(self._upload_queue, archive=False):
with osutils.TempDir(prefix='chrome-sdk-cache') as tempdir:
cache_dir = os.path.join(tempdir, 'cache')
extra_args = ['--cwd', self.chrome_src, '--sdk-path', self.archive_path]
sdk_cmd = commands.ChromeSDK(
self._build_root, self._current_board, chrome_src=self.chrome_src,
extra_args=extra_args, cache_dir=cache_dir)
class BuildImageStage(BuildPackagesStage):
"""Build standard Chromium OS images."""
option_name = 'build'
def _BuildImages(self):
# We only build base, dev, and test images from this stage.
if self._pgo_generate:
images_can_build = set(['test'])
images_can_build = set(['base', 'dev', 'test'])
images_to_build = set(self._run.config.images).intersection(
version = self.archive_stage.release_tag
disk_layout = self._run.config.disk_layout
if self._pgo_generate:
disk_layout = constants.PGO_GENERATE_DISK_LAYOUT
if version:
version = '%s-pgo-generate' % version
rootfs_verification = self._run.config.rootfs_verification
# Update link to latest image.
latest_image = os.readlink(self.GetImageDirSymlink('latest'))
cbuildbot_image_link = self.GetImageDirSymlink()
if os.path.lexists(cbuildbot_image_link):
os.symlink(latest_image, cbuildbot_image_link)
[self._BuildVMImage, self.ArchivePayloads,
lambda: self._GenerateAuZip(cbuildbot_image_link)])
def _BuildVMImage(self):
if self._run.config.vm_tests and not self._pgo_generate:
def ArchivePayloads(self):
"""Archives update payloads when they are ready."""
with osutils.TempDir(prefix='cbuildbot-payloads') as tempdir:
with self.ArtifactUploader() as queue:
if self._run.config.upload_hw_test_artifacts:
if 'test' in self._run.config.images:
image_name = 'chromiumos_test_image.bin'
elif 'dev' in self._run.config.images:
image_name = 'chromiumos_dev_image.bin'
image_name = 'chromiumos_base_image.bin''Generating payloads to upload for %s', image_name)
image_path = os.path.join(self.GetImageDirSymlink(), image_name)
# For non release builds, we are only interested in generating
# payloads for the purpose of imaging machines. This means we
# shouldn't generate delta payloads for n-1->n testing.
# TODO: Add a config flag for generating delta payloads instead.
if (self._run.config.build_type == constants.CANARY_TYPE and
not self._pgo_generate):
self._build_root, self.bot_archive_root, image_path, tempdir)
commands.GenerateFullPayload(self._build_root, image_path, tempdir)
for payload in os.listdir(tempdir):
queue.put([os.path.join(tempdir, payload)])