blob: 8d52d8aafd79c179d052087b850cac5eede88462 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Don Garrettc4114cc2016-11-01 20:04:06 -07002# Copyright 2016 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Bootstrap for cbuildbot.
7
8This script is intended to checkout chromite on the branch specified by -b or
9--branch (as normally accepted by cbuildbot), and then invoke cbuildbot. Most
10arguments are not parsed, only passed along. If a branch is not specified, this
11script will use 'master'.
12
13Among other things, this allows us to invoke build configs that exist on a given
14branch, but not on TOT.
15"""
16
17from __future__ import print_function
18
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060019import base64
Don Garrett125d4dc2017-04-25 16:26:03 -070020import functools
Don Garrettc4114cc2016-11-01 20:04:06 -070021import os
Mike Frysinger3c831a72020-02-19 02:47:04 -050022import sys
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -070023import time
Don Garrettc4114cc2016-11-01 20:04:06 -070024
25from chromite.cbuildbot import repository
Don Garrett597ddff2017-02-17 18:29:37 -080026from chromite.cbuildbot.stages import sync_stages
Lann Martinebae73d2018-05-21 17:12:00 -060027from chromite.lib import boto_compat
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060028from chromite.lib import build_summary
Don Garrett86881cb2017-02-15 15:41:55 -080029from chromite.lib import config_lib
Don Garretta50bf492017-09-28 18:33:02 -070030from chromite.lib import constants
Don Garrettc4114cc2016-11-01 20:04:06 -070031from chromite.lib import cros_build_lib
32from chromite.lib import cros_logging as logging
Benjamin Gordon74645232018-05-04 17:40:42 -060033from chromite.lib import cros_sdk_lib
Don Garrettacbb2392017-05-11 18:27:41 -070034from chromite.lib import metrics
Don Garrettc4114cc2016-11-01 20:04:06 -070035from chromite.lib import osutils
Mike Frysingerf0146252019-09-02 13:31:05 -040036from chromite.lib import timeout_util
Don Garrettacbb2392017-05-11 18:27:41 -070037from chromite.lib import ts_mon_config
Don Garrett86881cb2017-02-15 15:41:55 -080038from chromite.scripts import cbuildbot
Don Garrettc4114cc2016-11-01 20:04:06 -070039
Mike Frysinger3c831a72020-02-19 02:47:04 -050040
41assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
42
43
Don Garrett60967922017-04-12 18:51:44 -070044# This number should be incremented when we change the layout of the buildroot
45# in a non-backwards compatible way. This wipes all buildroots.
Don Garrettbf90cdf2017-05-19 15:54:02 -070046BUILDROOT_BUILDROOT_LAYOUT = 2
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -070047_DISTFILES_CACHE_EXPIRY_HOURS = 8 * 24
Don Garrett60967922017-04-12 18:51:44 -070048
Don Garrettacbb2392017-05-11 18:27:41 -070049# Metrics reported to Monarch.
Mike Nicholscb29fbd2018-07-24 11:09:33 -060050METRIC_PREFIX = 'chromeos/chromite/cbuildbot_launch/'
51METRIC_ACTIVE = METRIC_PREFIX + 'active'
52METRIC_INVOKED = METRIC_PREFIX + 'invoked'
53METRIC_COMPLETED = METRIC_PREFIX + 'completed'
54METRIC_PREP = METRIC_PREFIX + 'prep_completed'
55METRIC_CLEAN = METRIC_PREFIX + 'clean_buildroot_durations'
56METRIC_INITIAL = METRIC_PREFIX + 'initial_checkout_durations'
57METRIC_CBUILDBOT = METRIC_PREFIX + 'cbuildbot_durations'
58METRIC_CBUILDBOT_INSTANCE = METRIC_PREFIX + 'cbuildbot_instance_durations'
59METRIC_CLOBBER = METRIC_PREFIX + 'clobber'
60METRIC_BRANCH_CLEANUP = METRIC_PREFIX + 'branch_cleanup'
61METRIC_DISTFILES_CLEANUP = METRIC_PREFIX + 'distfiles_cleanup'
62METRIC_CHROOT_CLEANUP = METRIC_PREFIX + 'chroot_cleanup'
Don Garrettacbb2392017-05-11 18:27:41 -070063
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060064# Builder state
65BUILDER_STATE_FILENAME = '.cbuildbot_build_state.json'
66
Don Garrett60967922017-04-12 18:51:44 -070067
Don Garrett125d4dc2017-04-25 16:26:03 -070068def StageDecorator(functor):
69 """A Decorator that adds buildbot stage tags around a method.
70
Don Garrettacbb2392017-05-11 18:27:41 -070071 It uses the method name as the stage name, and assumes failure on a true
72 return value, or an exception.
Don Garrett125d4dc2017-04-25 16:26:03 -070073 """
74 @functools.wraps(functor)
75 def wrapped_functor(*args, **kwargs):
76 try:
77 logging.PrintBuildbotStepName(functor.__name__)
Don Garrettacbb2392017-05-11 18:27:41 -070078 result = functor(*args, **kwargs)
Don Garrett125d4dc2017-04-25 16:26:03 -070079 except Exception:
80 logging.PrintBuildbotStepFailure()
81 raise
82
Don Garrettacbb2392017-05-11 18:27:41 -070083 if result:
84 logging.PrintBuildbotStepFailure()
85 return result
86
Don Garrett125d4dc2017-04-25 16:26:03 -070087 return wrapped_functor
88
89
Don Garrettb5fc08b2017-11-20 21:51:16 +000090def field(fields, **kwargs):
Don Garrettacbb2392017-05-11 18:27:41 -070091 """Helper for inserting more fields into a metrics fields dictionary.
92
93 Args:
94 fields: Dictionary of metrics fields.
95 kwargs: Each argument is a key/value pair to insert into dict.
96
97 Returns:
98 Copy of original dictionary with kwargs set as fields.
99 """
100 f = fields.copy()
101 f.update(kwargs)
102 return f
103
Don Garretta50bf492017-09-28 18:33:02 -0700104
105def PrependPath(prepend):
106 """Generate path with new directory at the beginning.
107
108 Args:
109 prepend: Directory to add at the beginning of the path.
110
111 Returns:
112 Extended path as a string.
113 """
114 return os.pathsep.join([prepend, os.environ.get('PATH', os.defpath)])
115
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000116
Don Garrett86881cb2017-02-15 15:41:55 -0800117def PreParseArguments(argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700118 """Extract the branch name from cbuildbot command line arguments.
119
Don Garrettc4114cc2016-11-01 20:04:06 -0700120 Args:
121 argv: The command line arguments to parse.
122
123 Returns:
124 Branch as a string ('master' if nothing is specified).
125 """
Don Garrett86881cb2017-02-15 15:41:55 -0800126 parser = cbuildbot.CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400127 options = cbuildbot.ParseCommandLine(parser, argv)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800128
129 if not options.cache_dir:
130 options.cache_dir = os.path.join(options.buildroot,
131 'repository', '.cache')
132
Don Garrettd1d90dd2017-06-13 17:35:52 -0700133 options.Freeze()
Don Garrett86881cb2017-02-15 15:41:55 -0800134
135 # This option isn't required for cbuildbot, but is for us.
136 if not options.buildroot:
137 cros_build_lib.Die('--buildroot is a required option.')
138
139 return options
Don Garrettc4114cc2016-11-01 20:04:06 -0700140
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000141
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600142def GetCurrentBuildState(options, branch):
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600143 """Extract information about the current build state from command-line args.
144
145 Args:
146 options: A parsed options object from a cbuildbot parser.
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600147 branch: The name of the branch this builder was called with.
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600148
149 Returns:
150 A BuildSummary object describing the current build.
151 """
152 build_state = build_summary.BuildSummary(
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600153 status=constants.BUILDER_STATUS_INFLIGHT,
154 buildroot_layout=BUILDROOT_BUILDROOT_LAYOUT,
155 branch=branch)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600156 if options.buildnumber:
157 build_state.build_number = options.buildnumber
158 if options.buildbucket_id:
159 build_state.buildbucket_id = options.buildbucket_id
160 if options.master_build_id:
161 build_state.master_build_id = options.master_build_id
162 return build_state
163
164
165def GetLastBuildState(root):
166 """Fetch the state of the last build run from |root|.
167
168 If the saved state file can't be read or doesn't contain valid JSON, a default
169 state will be returned.
170
171 Args:
172 root: Root of the working directory tree as a string.
173
174 Returns:
175 A BuildSummary object representing the previous build.
176 """
177 state_file = os.path.join(root, BUILDER_STATE_FILENAME)
178
179 state = build_summary.BuildSummary()
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600180
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600181 try:
182 state_raw = osutils.ReadFile(state_file)
183 state.from_json(state_raw)
184 except IOError as e:
185 logging.warning('Unable to read %s: %s', state_file, e)
186 return state
187 except ValueError as e:
188 logging.warning('Saved state file %s is not valid JSON: %s', state_file, e)
189 return state
190
191 if not state.is_valid():
192 logging.warning('Previous build state is not valid. Ignoring.')
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600193 state = build_summary.BuildSummary()
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600194
195 return state
196
197
198def SetLastBuildState(root, new_state):
199 """Save the state of the last build under |root|.
200
201 Args:
202 root: Root of the working directory tree as a string.
203 new_state: BuildSummary object containing the state to be saved.
204 """
205 state_file = os.path.join(root, BUILDER_STATE_FILENAME)
206 osutils.WriteFile(state_file, new_state.to_json())
207
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600208 # Remove old state file. Its contents have been migrated into the new file.
209 old_state_file = os.path.join(root, '.cbuildbot_launch_state')
210 osutils.SafeUnlink(old_state_file)
211
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600212
Don Garrett61ce1ee2019-02-26 16:20:25 -0800213def _MaybeCleanDistfiles(cache_dir, distfiles_ts):
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700214 """Cleans the distfiles directory if too old.
215
216 Args:
Don Garrett61ce1ee2019-02-26 16:20:25 -0800217 cache_dir: Directory of the cache, as a string.
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700218 distfiles_ts: A timestamp str for the last time distfiles was cleaned. May
219 be None.
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700220
221 Returns:
222 The new distfiles_ts to persist in state.
223 """
Don Garrette3f1a472018-06-19 13:03:21 -0700224 # distfiles_ts can be None for a fresh environment, which means clean.
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700225 if distfiles_ts is None:
Don Garrette3f1a472018-06-19 13:03:21 -0700226 return time.time()
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700227
228 distfiles_age = (time.time() - distfiles_ts) / 3600.0
229 if distfiles_age < _DISTFILES_CACHE_EXPIRY_HOURS:
230 return distfiles_ts
231
232 logging.info('Remove old distfiles cache (cache expiry %d hours)',
233 _DISTFILES_CACHE_EXPIRY_HOURS)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800234 osutils.RmDir(os.path.join(cache_dir, 'distfiles'),
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700235 ignore_missing=True, sudo=True)
236 metrics.Counter(METRIC_DISTFILES_CLEANUP).increment(
Dhanya Ganesh0d909202019-02-20 12:56:46 -0700237 fields=field({}, reason='cache_expired'))
Don Garrette3f1a472018-06-19 13:03:21 -0700238
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700239 # Cleaned cache, so reset distfiles_ts
Don Garrette3f1a472018-06-19 13:03:21 -0700240 return time.time()
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -0700241
242
Don Garrett61ce1ee2019-02-26 16:20:25 -0800243def SanitizeCacheDir(cache_dir):
244 """Make certain the .cache directory is valid.
245
246 Args:
247 cache_dir: Directory of the cache, as a string.
248 """
249 logging.info('Cleaning up cache dir at %s', cache_dir)
250 # Verify that .cache is writable by the current user.
251 try:
252 osutils.Touch(os.path.join(cache_dir, '.cbuildbot_launch'), makedirs=True)
253 except IOError:
254 logging.info('Bad Permissions for cache dir, wiping: %s', cache_dir)
255 osutils.RmDir(cache_dir, sudo=True)
256 osutils.Touch(os.path.join(cache_dir, '.cbuildbot_launch'), makedirs=True)
257
Don Garrett14a41b32019-02-28 12:54:14 -0800258 osutils.RmDir(os.path.join(cache_dir, 'paygen_cache'),
259 ignore_missing=True, sudo=True)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800260 logging.info('Finished cleaning cache_dir.')
261
262
Don Garrett125d4dc2017-04-25 16:26:03 -0700263@StageDecorator
Don Garrett61ce1ee2019-02-26 16:20:25 -0800264def CleanBuildRoot(root, repo, cache_dir, build_state):
Don Garrett7ade05a2017-02-17 13:31:47 -0800265 """Some kinds of branch transitions break builds.
266
Don Garrettbf90cdf2017-05-19 15:54:02 -0700267 This method ensures that cbuildbot's buildroot is a clean checkout on the
268 given branch when it starts. If necessary (a branch transition) it will wipe
269 assorted state that cannot be safely reused from the previous build.
Don Garrett7ade05a2017-02-17 13:31:47 -0800270
Don Garrett7ade05a2017-02-17 13:31:47 -0800271 Args:
Don Garrettbf90cdf2017-05-19 15:54:02 -0700272 root: Root directory owned by cbuildbot_launch.
Don Garrettf324bc32017-05-23 14:00:53 -0700273 repo: repository.RepoRepository instance.
Don Garrett61ce1ee2019-02-26 16:20:25 -0800274 cache_dir: Cache directory.
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600275 build_state: BuildSummary object containing the current build state that
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600276 will be saved into the cleaned root. The distfiles_ts property will
277 be updated if the distfiles cache is cleaned.
Don Garrett7ade05a2017-02-17 13:31:47 -0800278 """
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600279 previous_state = GetLastBuildState(root)
Don Garrett4166d182018-12-17 12:52:02 -0800280 SetLastBuildState(root, build_state)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800281 SanitizeCacheDir(cache_dir)
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600282 build_state.distfiles_ts = _MaybeCleanDistfiles(
Don Garrett61ce1ee2019-02-26 16:20:25 -0800283 cache_dir, previous_state.distfiles_ts)
Don Garrette17e1d92017-04-12 15:28:19 -0700284
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600285 if previous_state.buildroot_layout != BUILDROOT_BUILDROOT_LAYOUT:
Don Garrett125d4dc2017-04-25 16:26:03 -0700286 logging.PrintBuildbotStepText('Unknown layout: Wiping buildroot.')
Don Garrettb5fc08b2017-11-20 21:51:16 +0000287 metrics.Counter(METRIC_CLOBBER).increment(
Dhanya Ganesh0d909202019-02-20 12:56:46 -0700288 fields=field({}, reason='layout_change'))
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700289 chroot_dir = os.path.join(root, constants.DEFAULT_CHROOT_DIR)
Don Garrettb5fc08b2017-11-20 21:51:16 +0000290 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
Don Garrett36650112018-06-28 15:54:34 -0700291 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=True)
Don Garrettb5fc08b2017-11-20 21:51:16 +0000292 osutils.RmDir(root, ignore_missing=True, sudo=True)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800293 osutils.RmDir(cache_dir, ignore_missing=True, sudo=True)
Don Garrettf324bc32017-05-23 14:00:53 -0700294 else:
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600295 if previous_state.branch != repo.branch:
Don Garrettf324bc32017-05-23 14:00:53 -0700296 logging.PrintBuildbotStepText('Branch change: Cleaning buildroot.')
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600297 logging.info('Unmatched branch: %s -> %s', previous_state.branch,
298 repo.branch)
Don Garrettacbb2392017-05-11 18:27:41 -0700299 metrics.Counter(METRIC_BRANCH_CLEANUP).increment(
Dhanya Ganesh0d909202019-02-20 12:56:46 -0700300 fields=field({}, old_branch=previous_state.branch))
Don Garrett39963602017-02-27 14:41:58 -0800301
Don Garrettf324bc32017-05-23 14:00:53 -0700302 logging.info('Remove Chroot.')
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700303 chroot_dir = os.path.join(repo.directory, constants.DEFAULT_CHROOT_DIR)
Benjamin Gordon59ba2f82017-08-28 15:31:06 -0600304 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
Don Garrett36650112018-06-28 15:54:34 -0700305 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=True)
Don Garrett7ade05a2017-02-17 13:31:47 -0800306
Don Garrettf324bc32017-05-23 14:00:53 -0700307 logging.info('Remove Chrome checkout.')
Don Garrettbf90cdf2017-05-19 15:54:02 -0700308 osutils.RmDir(os.path.join(repo.directory, '.cache', 'distfiles'),
Don Garrettf324bc32017-05-23 14:00:53 -0700309 ignore_missing=True, sudo=True)
310
Don Garrett1241c4e2018-08-06 17:33:41 -0700311 try:
312 # If there is any failure doing the cleanup, wipe everything.
313 # The previous run might have been killed in the middle leaving stale git
314 # locks. Clean those up, first.
315 repo.PreLoad()
Don Garrett4166d182018-12-17 12:52:02 -0800316
317 # If the previous build didn't exit normally, run an expensive step to
318 # cleanup abandoned git locks.
319 if previous_state.status not in (constants.BUILDER_STATUS_FAILED,
320 constants.BUILDER_STATUS_PASSED):
321 repo.CleanStaleLocks()
322
Don Garrett1241c4e2018-08-06 17:33:41 -0700323 repo.BuildRootGitCleanup(prune_all=True)
324 except Exception:
325 logging.info('Checkout cleanup failed, wiping buildroot:', exc_info=True)
326 metrics.Counter(METRIC_CLOBBER).increment(
Dhanya Ganesh0d909202019-02-20 12:56:46 -0700327 fields=field({}, reason='repo_cleanup_failure'))
Don Garrett1241c4e2018-08-06 17:33:41 -0700328 repository.ClearBuildRoot(repo.directory)
Don Garrett39963602017-02-27 14:41:58 -0800329
Don Garrettbf90cdf2017-05-19 15:54:02 -0700330 # Ensure buildroot exists. Save the state we are prepped for.
331 osutils.SafeMakedirs(repo.directory)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600332 SetLastBuildState(root, build_state)
Don Garrett7ade05a2017-02-17 13:31:47 -0800333
334
Don Garrett125d4dc2017-04-25 16:26:03 -0700335@StageDecorator
Don Garrettf324bc32017-05-23 14:00:53 -0700336def InitialCheckout(repo):
Don Garrett86881cb2017-02-15 15:41:55 -0800337 """Preliminary ChromeOS checkout.
338
339 Perform a complete checkout of ChromeOS on the specified branch. This does NOT
340 match what the build needs, but ensures the buildroot both has a 'hot'
341 checkout, and is close enough that the branched cbuildbot can successfully get
342 the right checkout.
343
344 This checks out full ChromeOS, even if a ChromiumOS build is going to be
345 performed. This is because we have no knowledge of the build config to be
346 used.
Don Garrettc4114cc2016-11-01 20:04:06 -0700347
348 Args:
Don Garrettf324bc32017-05-23 14:00:53 -0700349 repo: repository.RepoRepository instance.
Don Garrettc4114cc2016-11-01 20:04:06 -0700350 """
Don Garrettf324bc32017-05-23 14:00:53 -0700351 logging.PrintBuildbotStepText('Branch: %s' % repo.branch)
Don Garrett7ade05a2017-02-17 13:31:47 -0800352 logging.info('Bootstrap script starting initial sync on branch: %s',
Don Garrettf324bc32017-05-23 14:00:53 -0700353 repo.branch)
Don Garrett5516acb2018-11-15 16:02:59 -0800354 repo.PreLoad('/preload/chromeos')
Don Garrett76496912017-05-11 16:59:11 -0700355 repo.Sync(detach=True)
Don Garrettc4114cc2016-11-01 20:04:06 -0700356
357
Lann Martin8c4c6802018-05-23 11:09:46 -0600358def ShouldFixBotoCerts(options):
359 """Decide if FixBotoCerts should be applied for this branch."""
360 try:
361 # Only apply to factory and firmware branches.
362 branch = options.branch or ''
363 prefix = branch.split('-')[0]
364 if prefix not in ('factory', 'firmware'):
365 return False
366
367 # Only apply to "old" branches.
368 if branch.endswith('.B'):
369 version = branch[:-2].split('-')[-1]
370 major = int(version.split('.')[0])
371 return major <= 9667 # This is the newest known to be failing.
372
373 return False
Mike Frysinger9f470262018-08-03 15:09:58 -0400374 except Exception as e:
Lann Martin8c4c6802018-05-23 11:09:46 -0600375 logging.warning(' failed: %s', e)
376 # Conservatively continue without the fix.
377 return False
378
379
Don Garrett066e6f52017-09-28 19:14:01 -0700380@StageDecorator
Don Garrett6e5c6b92018-04-06 17:58:49 -0700381def Cbuildbot(buildroot, depot_tools_path, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700382 """Start cbuildbot in specified directory with all arguments.
383
384 Args:
Don Garrettbf90cdf2017-05-19 15:54:02 -0700385 buildroot: Directory to be passed to cbuildbot with --buildroot.
Don Garretta50bf492017-09-28 18:33:02 -0700386 depot_tools_path: Directory for depot_tools to be used by cbuildbot.
Don Garrettd1d90dd2017-06-13 17:35:52 -0700387 argv: Command line options passed to cbuildbot_launch.
Don Garrettc4114cc2016-11-01 20:04:06 -0700388
389 Returns:
390 Return code of cbuildbot as an integer.
391 """
Don Garrettbf90cdf2017-05-19 15:54:02 -0700392 logging.info('Bootstrap cbuildbot in: %s', buildroot)
Don Garrettbf90cdf2017-05-19 15:54:02 -0700393
Don Garrettd1d90dd2017-06-13 17:35:52 -0700394 # Fixup buildroot parameter.
395 argv = argv[:]
Mike Frysinger79cca962019-06-13 15:26:53 -0400396 for i, arg in enumerate(argv):
397 if arg in ('-r', '--buildroot'):
398 argv[i + 1] = buildroot
Don Garrett597ddff2017-02-17 18:29:37 -0800399
Don Garrettd1d90dd2017-06-13 17:35:52 -0700400 # This filters out command line arguments not supported by older versions
401 # of cbuildbot.
402 parser = cbuildbot.CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400403 options = cbuildbot.ParseCommandLine(parser, argv)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700404 cbuildbot_path = os.path.join(buildroot, 'chromite', 'bin', 'cbuildbot')
Don Garrett597ddff2017-02-17 18:29:37 -0800405 cmd = sync_stages.BootstrapStage.FilterArgsForTargetCbuildbot(
Don Garrettbf90cdf2017-05-19 15:54:02 -0700406 buildroot, cbuildbot_path, options)
Don Garrett597ddff2017-02-17 18:29:37 -0800407
Don Garretta50bf492017-09-28 18:33:02 -0700408 # We want cbuildbot to use branched depot_tools scripts from our manifest,
409 # so that depot_tools is branched to match cbuildbot.
410 logging.info('Adding depot_tools into PATH: %s', depot_tools_path)
411 extra_env = {'PATH': PrependPath(depot_tools_path)}
412
Lann Martinebae73d2018-05-21 17:12:00 -0600413 # TODO(crbug.com/845304): Remove once underlying boto issues are resolved.
Lann Martin8c4c6802018-05-23 11:09:46 -0600414 fix_boto = ShouldFixBotoCerts(options)
Lann Martinebae73d2018-05-21 17:12:00 -0600415
416 with boto_compat.FixBotoCerts(activate=fix_boto):
Mike Frysinger45602c72019-09-22 02:15:11 -0400417 result = cros_build_lib.run(
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500418 cmd, extra_env=extra_env, check=False, cwd=buildroot)
Lann Martinebae73d2018-05-21 17:12:00 -0600419
Don Garrettacbb2392017-05-11 18:27:41 -0700420 return result.returncode
Don Garrettc4114cc2016-11-01 20:04:06 -0700421
Don Garrett60967922017-04-12 18:51:44 -0700422
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700423@StageDecorator
424def CleanupChroot(buildroot):
425 """Unmount/clean up an image-based chroot without deleting the backing image.
426
427 Args:
428 buildroot: Directory containing the chroot to be cleaned up.
429 """
430 chroot_dir = os.path.join(buildroot, constants.DEFAULT_CHROOT_DIR)
431 logging.info('Cleaning up chroot at %s', chroot_dir)
432 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
Mike Frysingerf0146252019-09-02 13:31:05 -0400433 try:
434 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=False)
435 except timeout_util.TimeoutError:
436 logging.exception('Cleaning up chroot timed out')
437 # Dump debug info to help https://crbug.com/1000034.
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500438 cros_build_lib.run(['mount'], check=True)
439 cros_build_lib.run(['uname', '-a'], check=True)
440 cros_build_lib.sudo_run(['losetup', '-a'], check=True)
441 cros_build_lib.run(['dmesg'], check=True)
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400442 logging.warning('Assuming the bot is going to reboot, so ignoring this '
443 'failure; see https://crbug.com/1000034')
Mike Frysingerf0146252019-09-02 13:31:05 -0400444
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400445 # NB: We ignore errors at this point because this stage runs last. If the
446 # chroot failed to unmount, we're going to reboot the system once we're done,
447 # and that will implicitly take care of cleaning things up. If the bots stop
448 # rebooting after every run, we'll need to make this fatal all the time.
449 #
450 # TODO(crbug.com/1000034): This should be fatal all the time.
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700451
452
Don Garrettf15d65b2017-04-12 12:39:55 -0700453def ConfigureGlobalEnvironment():
454 """Setup process wide environmental changes."""
Don Garrettf15d65b2017-04-12 12:39:55 -0700455 # Set umask to 022 so files created by buildbot are readable.
456 os.umask(0o22)
457
Don Garrett86fec482017-05-17 18:13:33 -0700458 # These variables can interfere with LANG / locale behavior.
459 unwanted_local_vars = [
460 'LC_ALL', 'LC_CTYPE', 'LC_COLLATE', 'LC_TIME', 'LC_NUMERIC',
461 'LC_MONETARY', 'LC_MESSAGES', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
462 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION',
463 ]
464 for v in unwanted_local_vars:
465 os.environ.pop(v, None)
466
467 # This variable is required for repo sync's to work in all cases.
468 os.environ['LANG'] = 'en_US.UTF-8'
469
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000470
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600471def _main(options, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700472 """main method of script.
473
474 Args:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600475 options: preparsed options object for the build.
Don Garrettc4114cc2016-11-01 20:04:06 -0700476 argv: All command line arguments to pass as list of strings.
477
478 Returns:
479 Return code of cbuildbot as an integer.
480 """
Don Garrettd1d90dd2017-06-13 17:35:52 -0700481 branchname = options.branch or 'master'
482 root = options.buildroot
483 buildroot = os.path.join(root, 'repository')
Don Garrettb497f552018-07-09 16:01:13 -0700484 workspace = os.path.join(root, 'workspace')
Don Garretta50bf492017-09-28 18:33:02 -0700485 depot_tools_path = os.path.join(buildroot, constants.DEPOT_TOOLS_SUBPATH)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700486
Ben Pastenec8e4e792018-05-14 20:20:25 +0000487 # Does the entire build pass or fail.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600488 with metrics.Presence(METRIC_ACTIVE), \
489 metrics.SuccessCounter(METRIC_COMPLETED) as s_fields:
Don Garrettc4114cc2016-11-01 20:04:06 -0700490
Ben Pastenec8e4e792018-05-14 20:20:25 +0000491 # Preliminary set, mostly command line parsing.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600492 with metrics.SuccessCounter(METRIC_INVOKED):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000493 if options.enable_buildbot_tags:
494 logging.EnableBuildbotMarkers()
495 ConfigureGlobalEnvironment()
Don Garrett86881cb2017-02-15 15:41:55 -0800496
Ben Pastenec8e4e792018-05-14 20:20:25 +0000497 # Prepare the buildroot with source for the build.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600498 with metrics.SuccessCounter(METRIC_PREP):
Alex Klein2ab29cc2018-07-19 12:01:00 -0600499 manifest_url = config_lib.GetSiteParams().MANIFEST_INT_URL
Ben Pastenec8e4e792018-05-14 20:20:25 +0000500 repo = repository.RepoRepository(manifest_url, buildroot,
501 branch=branchname,
Don Garrett33872502018-08-03 22:30:40 +0000502 git_cache_dir=options.git_cache_dir)
Ben Pastenec8e4e792018-05-14 20:20:25 +0000503 previous_build_state = GetLastBuildState(root)
Don Garrett86881cb2017-02-15 15:41:55 -0800504
Ben Pastenec8e4e792018-05-14 20:20:25 +0000505 # Clean up the buildroot to a safe state.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600506 with metrics.SecondsTimer(METRIC_CLEAN):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000507 build_state = GetCurrentBuildState(options, branchname)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800508 CleanBuildRoot(root, repo, options.cache_dir, build_state)
Don Garrettacbb2392017-05-11 18:27:41 -0700509
Ben Pastenec8e4e792018-05-14 20:20:25 +0000510 # Get a checkout close enough to the branch that cbuildbot can handle it.
511 if options.sync:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600512 with metrics.SecondsTimer(METRIC_INITIAL):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000513 InitialCheckout(repo)
Don Garrettacbb2392017-05-11 18:27:41 -0700514
Ben Pastenec8e4e792018-05-14 20:20:25 +0000515 # Run cbuildbot inside the full ChromeOS checkout, on the specified branch.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600516 with metrics.SecondsTimer(METRIC_CBUILDBOT), \
517 metrics.SecondsInstanceTimer(METRIC_CBUILDBOT_INSTANCE):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000518 if previous_build_state.is_valid():
519 argv.append('--previous-build-state')
Mike Frysinger1a443332019-11-24 02:48:03 -0500520 argv.append(base64.b64encode(previous_build_state.to_json().encode(
521 'utf-8')).decode('utf-8'))
Don Garrettb497f552018-07-09 16:01:13 -0700522 argv.extend(['--workspace', workspace])
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600523
Don Garrett61ce1ee2019-02-26 16:20:25 -0800524 if not options.cache_dir_specified:
525 argv.extend(['--cache-dir', options.cache_dir])
526
Ben Pastenec8e4e792018-05-14 20:20:25 +0000527 result = Cbuildbot(buildroot, depot_tools_path, argv)
528 s_fields['success'] = (result == 0)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600529
Ben Pastenec8e4e792018-05-14 20:20:25 +0000530 build_state.status = (
531 constants.BUILDER_STATUS_PASSED
532 if result == 0 else constants.BUILDER_STATUS_FAILED)
533 SetLastBuildState(root, build_state)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600534
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600535 with metrics.SecondsTimer(METRIC_CHROOT_CLEANUP):
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400536 CleanupChroot(buildroot)
Don Garrett91a8cfc2018-06-22 15:39:36 -0700537
Ben Pastenec8e4e792018-05-14 20:20:25 +0000538 return result
539
Don Garrettacbb2392017-05-11 18:27:41 -0700540
541def main(argv):
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600542 options = PreParseArguments(argv)
543 metric_fields = {
544 'branch_name': options.branch or 'master',
545 'build_config': options.build_config_name,
546 'tryjob': options.remote_trybot,
547 }
548
Ben Pastenec8e4e792018-05-14 20:20:25 +0000549 # Enable Monarch metrics gathering.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600550 with ts_mon_config.SetupTsMonGlobalState('cbuildbot_launch',
551 common_metric_fields=metric_fields,
552 indirect=True):
553 return _main(options, argv)