blob: 4f73d0f4ff9ef033d3bb168a1e2364bbdd59716b [file] [log] [blame]
Don Garrettc4114cc2016-11-01 20:04:06 -07001# Copyright 2016 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Bootstrap for cbuildbot.
6
7This script is intended to checkout chromite on the branch specified by -b or
8--branch (as normally accepted by cbuildbot), and then invoke cbuildbot. Most
9arguments are not parsed, only passed along. If a branch is not specified, this
Julio Hurtado9265c7e2021-04-19 23:04:44 +000010script will use 'main'.
Don Garrettc4114cc2016-11-01 20:04:06 -070011
12Among other things, this allows us to invoke build configs that exist on a given
13branch, but not on TOT.
14"""
15
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060016import base64
Don Garrett125d4dc2017-04-25 16:26:03 -070017import functools
Chris McDonaldb55b7032021-06-17 16:41:32 -060018import logging
Don Garrettc4114cc2016-11-01 20:04:06 -070019import os
Mike Nicholsd0acc7f2021-05-21 17:18:24 +000020import time
Don Garrettc4114cc2016-11-01 20:04:06 -070021
Chris McDonaldb55b7032021-06-17 16:41:32 -060022from chromite.cbuildbot import cbuildbot_alerts
Don Garrettc4114cc2016-11-01 20:04:06 -070023from chromite.cbuildbot import repository
Don Garrett597ddff2017-02-17 18:29:37 -080024from chromite.cbuildbot.stages import sync_stages
Lann Martinebae73d2018-05-21 17:12:00 -060025from chromite.lib import boto_compat
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060026from chromite.lib import build_summary
Don Garrett86881cb2017-02-15 15:41:55 -080027from chromite.lib import config_lib
Don Garretta50bf492017-09-28 18:33:02 -070028from chromite.lib import constants
Don Garrettc4114cc2016-11-01 20:04:06 -070029from chromite.lib import cros_build_lib
Benjamin Gordon74645232018-05-04 17:40:42 -060030from chromite.lib import cros_sdk_lib
Don Garrettacbb2392017-05-11 18:27:41 -070031from chromite.lib import metrics
Don Garrettc4114cc2016-11-01 20:04:06 -070032from chromite.lib import osutils
Mike Frysingerf0146252019-09-02 13:31:05 -040033from chromite.lib import timeout_util
Don Garrettacbb2392017-05-11 18:27:41 -070034from chromite.lib import ts_mon_config
Don Garrett86881cb2017-02-15 15:41:55 -080035from chromite.scripts import cbuildbot
Don Garrettc4114cc2016-11-01 20:04:06 -070036
Mike Frysinger3c831a72020-02-19 02:47:04 -050037
Don Garrett60967922017-04-12 18:51:44 -070038# This number should be incremented when we change the layout of the buildroot
39# in a non-backwards compatible way. This wipes all buildroots.
Don Garrettbf90cdf2017-05-19 15:54:02 -070040BUILDROOT_BUILDROOT_LAYOUT = 2
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -070041_DISTFILES_CACHE_EXPIRY_HOURS = 8 * 24
Don Garrett60967922017-04-12 18:51:44 -070042
Don Garrettacbb2392017-05-11 18:27:41 -070043# Metrics reported to Monarch.
Mike Nicholscb29fbd2018-07-24 11:09:33 -060044METRIC_PREFIX = 'chromeos/chromite/cbuildbot_launch/'
45METRIC_ACTIVE = METRIC_PREFIX + 'active'
46METRIC_INVOKED = METRIC_PREFIX + 'invoked'
47METRIC_COMPLETED = METRIC_PREFIX + 'completed'
48METRIC_PREP = METRIC_PREFIX + 'prep_completed'
49METRIC_CLEAN = METRIC_PREFIX + 'clean_buildroot_durations'
50METRIC_INITIAL = METRIC_PREFIX + 'initial_checkout_durations'
51METRIC_CBUILDBOT = METRIC_PREFIX + 'cbuildbot_durations'
52METRIC_CBUILDBOT_INSTANCE = METRIC_PREFIX + 'cbuildbot_instance_durations'
53METRIC_CLOBBER = METRIC_PREFIX + 'clobber'
54METRIC_BRANCH_CLEANUP = METRIC_PREFIX + 'branch_cleanup'
55METRIC_DISTFILES_CLEANUP = METRIC_PREFIX + 'distfiles_cleanup'
56METRIC_CHROOT_CLEANUP = METRIC_PREFIX + 'chroot_cleanup'
Don Garrettacbb2392017-05-11 18:27:41 -070057
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060058# Builder state
59BUILDER_STATE_FILENAME = '.cbuildbot_build_state.json'
60
Don Garrett60967922017-04-12 18:51:44 -070061
Don Garrett125d4dc2017-04-25 16:26:03 -070062def StageDecorator(functor):
63 """A Decorator that adds buildbot stage tags around a method.
64
Don Garrettacbb2392017-05-11 18:27:41 -070065 It uses the method name as the stage name, and assumes failure on a true
66 return value, or an exception.
Don Garrett125d4dc2017-04-25 16:26:03 -070067 """
68 @functools.wraps(functor)
69 def wrapped_functor(*args, **kwargs):
70 try:
Chris McDonaldb55b7032021-06-17 16:41:32 -060071 cbuildbot_alerts.PrintBuildbotStepName(functor.__name__)
Don Garrettacbb2392017-05-11 18:27:41 -070072 result = functor(*args, **kwargs)
Don Garrett125d4dc2017-04-25 16:26:03 -070073 except Exception:
Chris McDonaldb55b7032021-06-17 16:41:32 -060074 cbuildbot_alerts.PrintBuildbotStepFailure()
Don Garrett125d4dc2017-04-25 16:26:03 -070075 raise
76
Don Garrettacbb2392017-05-11 18:27:41 -070077 if result:
Chris McDonaldb55b7032021-06-17 16:41:32 -060078 cbuildbot_alerts.PrintBuildbotStepFailure()
Don Garrettacbb2392017-05-11 18:27:41 -070079 return result
80
Don Garrett125d4dc2017-04-25 16:26:03 -070081 return wrapped_functor
82
83
Don Garrettb5fc08b2017-11-20 21:51:16 +000084def field(fields, **kwargs):
Don Garrettacbb2392017-05-11 18:27:41 -070085 """Helper for inserting more fields into a metrics fields dictionary.
86
87 Args:
88 fields: Dictionary of metrics fields.
89 kwargs: Each argument is a key/value pair to insert into dict.
90
91 Returns:
92 Copy of original dictionary with kwargs set as fields.
93 """
94 f = fields.copy()
95 f.update(kwargs)
96 return f
97
Don Garretta50bf492017-09-28 18:33:02 -070098
99def PrependPath(prepend):
100 """Generate path with new directory at the beginning.
101
102 Args:
103 prepend: Directory to add at the beginning of the path.
104
105 Returns:
106 Extended path as a string.
107 """
108 return os.pathsep.join([prepend, os.environ.get('PATH', os.defpath)])
109
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000110
Don Garrett86881cb2017-02-15 15:41:55 -0800111def PreParseArguments(argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700112 """Extract the branch name from cbuildbot command line arguments.
113
Don Garrettc4114cc2016-11-01 20:04:06 -0700114 Args:
115 argv: The command line arguments to parse.
116
117 Returns:
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000118 Branch as a string ('main' if nothing is specified).
Don Garrettc4114cc2016-11-01 20:04:06 -0700119 """
Don Garrett86881cb2017-02-15 15:41:55 -0800120 parser = cbuildbot.CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400121 options = cbuildbot.ParseCommandLine(parser, argv)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800122
123 if not options.cache_dir:
124 options.cache_dir = os.path.join(options.buildroot,
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000125 'repository', '.cache')
Don Garrett61ce1ee2019-02-26 16:20:25 -0800126
Don Garrettd1d90dd2017-06-13 17:35:52 -0700127 options.Freeze()
Don Garrett86881cb2017-02-15 15:41:55 -0800128
129 # This option isn't required for cbuildbot, but is for us.
130 if not options.buildroot:
131 cros_build_lib.Die('--buildroot is a required option.')
132
133 return options
Don Garrettc4114cc2016-11-01 20:04:06 -0700134
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000135
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600136def GetCurrentBuildState(options, branch):
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600137 """Extract information about the current build state from command-line args.
138
139 Args:
140 options: A parsed options object from a cbuildbot parser.
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600141 branch: The name of the branch this builder was called with.
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600142
143 Returns:
144 A BuildSummary object describing the current build.
145 """
146 build_state = build_summary.BuildSummary(
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600147 status=constants.BUILDER_STATUS_INFLIGHT,
148 buildroot_layout=BUILDROOT_BUILDROOT_LAYOUT,
149 branch=branch)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600150 if options.buildnumber:
151 build_state.build_number = options.buildnumber
152 if options.buildbucket_id:
153 build_state.buildbucket_id = options.buildbucket_id
154 if options.master_build_id:
155 build_state.master_build_id = options.master_build_id
156 return build_state
157
158
159def GetLastBuildState(root):
160 """Fetch the state of the last build run from |root|.
161
162 If the saved state file can't be read or doesn't contain valid JSON, a default
163 state will be returned.
164
165 Args:
166 root: Root of the working directory tree as a string.
167
168 Returns:
169 A BuildSummary object representing the previous build.
170 """
171 state_file = os.path.join(root, BUILDER_STATE_FILENAME)
172
173 state = build_summary.BuildSummary()
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600174
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600175 try:
176 state_raw = osutils.ReadFile(state_file)
177 state.from_json(state_raw)
178 except IOError as e:
179 logging.warning('Unable to read %s: %s', state_file, e)
180 return state
181 except ValueError as e:
182 logging.warning('Saved state file %s is not valid JSON: %s', state_file, e)
183 return state
184
185 if not state.is_valid():
186 logging.warning('Previous build state is not valid. Ignoring.')
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600187 state = build_summary.BuildSummary()
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600188
189 return state
190
191
192def SetLastBuildState(root, new_state):
193 """Save the state of the last build under |root|.
194
195 Args:
196 root: Root of the working directory tree as a string.
197 new_state: BuildSummary object containing the state to be saved.
198 """
199 state_file = os.path.join(root, BUILDER_STATE_FILENAME)
200 osutils.WriteFile(state_file, new_state.to_json())
201
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600202 # Remove old state file. Its contents have been migrated into the new file.
203 old_state_file = os.path.join(root, '.cbuildbot_launch_state')
204 osutils.SafeUnlink(old_state_file)
205
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600206
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000207def _MaybeCleanDistfiles(cache_dir, distfiles_ts):
208 """Cleans the distfiles directory if too old.
209
210 Args:
211 cache_dir: Directory of the cache, as a string.
212 distfiles_ts: A timestamp str for the last time distfiles was cleaned. May
213 be None.
214
215 Returns:
216 The new distfiles_ts to persist in state.
217 """
218 # distfiles_ts can be None for a fresh environment, which means clean.
219 if distfiles_ts is None:
220 return time.time()
221
222 distfiles_age = (time.time() - distfiles_ts) / 3600.0
223 if distfiles_age < _DISTFILES_CACHE_EXPIRY_HOURS:
224 return distfiles_ts
225
226 logging.info('Remove old distfiles cache (cache expiry %d hours)',
227 _DISTFILES_CACHE_EXPIRY_HOURS)
228 osutils.RmDir(os.path.join(cache_dir, 'distfiles'),
229 ignore_missing=True, sudo=True)
230 metrics.Counter(METRIC_DISTFILES_CLEANUP).increment(
231 fields=field({}, reason='cache_expired'))
232
233 # Cleaned cache, so reset distfiles_ts
234 return time.time()
235
236
237def SanitizeCacheDir(cache_dir):
238 """Make certain the .cache directory is valid.
239
240 Args:
241 cache_dir: Directory of the cache, as a string.
242 """
243 logging.info('Cleaning up cache dir at %s', cache_dir)
244 # Verify that .cache is writable by the current user.
245 try:
246 osutils.Touch(os.path.join(cache_dir, '.cbuildbot_launch'), makedirs=True)
247 except IOError:
248 logging.info('Bad Permissions for cache dir, wiping: %s', cache_dir)
249 osutils.RmDir(cache_dir, sudo=True)
250 osutils.Touch(os.path.join(cache_dir, '.cbuildbot_launch'), makedirs=True)
251
252 osutils.RmDir(os.path.join(cache_dir, 'paygen_cache'),
253 ignore_missing=True, sudo=True)
254 logging.info('Finished cleaning cache_dir.')
255
256
257@StageDecorator
258def CleanBuildRoot(root, repo, cache_dir, build_state):
259 """Some kinds of branch transitions break builds.
260
261 This method ensures that cbuildbot's buildroot is a clean checkout on the
262 given branch when it starts. If necessary (a branch transition) it will wipe
263 assorted state that cannot be safely reused from the previous build.
264
265 Args:
266 root: Root directory owned by cbuildbot_launch.
267 repo: repository.RepoRepository instance.
268 cache_dir: Cache directory.
269 build_state: BuildSummary object containing the current build state that
270 will be saved into the cleaned root. The distfiles_ts property will
271 be updated if the distfiles cache is cleaned.
272 """
273 previous_state = GetLastBuildState(root)
274 SetLastBuildState(root, build_state)
275 SanitizeCacheDir(cache_dir)
276 build_state.distfiles_ts = _MaybeCleanDistfiles(
277 cache_dir, previous_state.distfiles_ts)
278
279 if previous_state.buildroot_layout != BUILDROOT_BUILDROOT_LAYOUT:
Chris McDonaldb55b7032021-06-17 16:41:32 -0600280 cbuildbot_alerts.PrintBuildbotStepText('Unknown layout: Wiping buildroot.')
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000281 metrics.Counter(METRIC_CLOBBER).increment(
282 fields=field({}, reason='layout_change'))
283 chroot_dir = os.path.join(root, constants.DEFAULT_CHROOT_DIR)
284 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
285 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=True)
286 osutils.RmDir(root, ignore_missing=True, sudo=True)
287 osutils.RmDir(cache_dir, ignore_missing=True, sudo=True)
288 else:
289 if previous_state.branch != repo.branch:
Chris McDonaldb55b7032021-06-17 16:41:32 -0600290 cbuildbot_alerts.PrintBuildbotStepText(
291 'Branch change: Cleaning buildroot.')
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000292 logging.info('Unmatched branch: %s -> %s', previous_state.branch,
293 repo.branch)
294 metrics.Counter(METRIC_BRANCH_CLEANUP).increment(
295 fields=field({}, old_branch=previous_state.branch))
296
297 logging.info('Remove Chroot.')
298 chroot_dir = os.path.join(repo.directory, constants.DEFAULT_CHROOT_DIR)
299 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
300 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=True)
301
302 logging.info('Remove Chrome checkout.')
303 osutils.RmDir(os.path.join(repo.directory, '.cache', 'distfiles'),
304 ignore_missing=True, sudo=True)
305
306 try:
307 # If there is any failure doing the cleanup, wipe everything.
308 # The previous run might have been killed in the middle leaving stale git
309 # locks. Clean those up, first.
310 repo.PreLoad()
311
312 # If the previous build didn't exit normally, run an expensive step to
313 # cleanup abandoned git locks.
314 if previous_state.status not in (constants.BUILDER_STATUS_FAILED,
315 constants.BUILDER_STATUS_PASSED):
316 repo.CleanStaleLocks()
317
318 repo.BuildRootGitCleanup(prune_all=True)
319 except Exception:
320 logging.info('Checkout cleanup failed, wiping buildroot:', exc_info=True)
321 metrics.Counter(METRIC_CLOBBER).increment(
322 fields=field({}, reason='repo_cleanup_failure'))
323 repository.ClearBuildRoot(repo.directory)
324
325 # Ensure buildroot exists. Save the state we are prepped for.
326 osutils.SafeMakedirs(repo.directory)
327 SetLastBuildState(root, build_state)
328
329
Don Garrett125d4dc2017-04-25 16:26:03 -0700330@StageDecorator
Mike Nichols9fb48832021-01-29 14:47:15 -0700331def InitialCheckout(repo, options):
Don Garrett86881cb2017-02-15 15:41:55 -0800332 """Preliminary ChromeOS checkout.
333
334 Perform a complete checkout of ChromeOS on the specified branch. This does NOT
335 match what the build needs, but ensures the buildroot both has a 'hot'
336 checkout, and is close enough that the branched cbuildbot can successfully get
337 the right checkout.
338
339 This checks out full ChromeOS, even if a ChromiumOS build is going to be
340 performed. This is because we have no knowledge of the build config to be
341 used.
Don Garrettc4114cc2016-11-01 20:04:06 -0700342
343 Args:
Don Garrettf324bc32017-05-23 14:00:53 -0700344 repo: repository.RepoRepository instance.
Mike Nichols9fb48832021-01-29 14:47:15 -0700345 options: A parsed options object from a cbuildbot parser.
Don Garrettc4114cc2016-11-01 20:04:06 -0700346 """
Chris McDonaldb55b7032021-06-17 16:41:32 -0600347 cbuildbot_alerts.PrintBuildbotStepText('Branch: %s' % repo.branch)
Mike Nicholsb49ceb92021-09-01 15:43:37 -0400348 if not options.source_cache:
349 logging.info('Bootstrap script starting initial sync on branch: %s',
350 repo.branch)
351 repo.PreLoad('/preload/chromeos')
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000352 repo.Sync(detach=True,
Mike Nichols9fb48832021-01-29 14:47:15 -0700353 downgrade_repo=_ShouldDowngradeRepo(options))
Don Garrettc4114cc2016-11-01 20:04:06 -0700354
355
Lann Martin8c4c6802018-05-23 11:09:46 -0600356def ShouldFixBotoCerts(options):
357 """Decide if FixBotoCerts should be applied for this branch."""
358 try:
359 # Only apply to factory and firmware branches.
360 branch = options.branch or ''
361 prefix = branch.split('-')[0]
362 if prefix not in ('factory', 'firmware'):
363 return False
364
365 # Only apply to "old" branches.
366 if branch.endswith('.B'):
367 version = branch[:-2].split('-')[-1]
368 major = int(version.split('.')[0])
369 return major <= 9667 # This is the newest known to be failing.
370
371 return False
Mike Frysinger9f470262018-08-03 15:09:58 -0400372 except Exception as e:
Lann Martin8c4c6802018-05-23 11:09:46 -0600373 logging.warning(' failed: %s', e)
374 # Conservatively continue without the fix.
375 return False
376
377
Mike Nichols9fb48832021-01-29 14:47:15 -0700378def _ShouldDowngradeRepo(options):
379 """Determine which repo version to set for the branch.
380
381 Repo version is set at cache creation time, in the nightly builder,
382 which means we are typically at the latest version. Older branches
383 are incompatible with newer version of ToT, therefore we downgrade
384 repo to a known working version.
385
386 Args:
387 options: A parsed options object from a cbuildbot parser.
388
389 Returns:
390 bool of whether to downgrade repo version based on branch.
391 """
392 try:
393 branch = options.branch or ''
394 # Only apply to "old" branches.
395 if branch.endswith('.B'):
396 branch_num = branch[:-2].split('-')[1][1:3]
397 return branch_num <= 79 # This is the newest known to be failing.
398
399 return False
400 except Exception as e:
401 logging.warning(' failed: %s', e)
402 # Conservatively continue without the fix.
403 return False
404
405
Don Garrett066e6f52017-09-28 19:14:01 -0700406@StageDecorator
Don Garrett6e5c6b92018-04-06 17:58:49 -0700407def Cbuildbot(buildroot, depot_tools_path, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700408 """Start cbuildbot in specified directory with all arguments.
409
410 Args:
Don Garrettbf90cdf2017-05-19 15:54:02 -0700411 buildroot: Directory to be passed to cbuildbot with --buildroot.
Don Garretta50bf492017-09-28 18:33:02 -0700412 depot_tools_path: Directory for depot_tools to be used by cbuildbot.
Don Garrettd1d90dd2017-06-13 17:35:52 -0700413 argv: Command line options passed to cbuildbot_launch.
Don Garrettc4114cc2016-11-01 20:04:06 -0700414
415 Returns:
416 Return code of cbuildbot as an integer.
417 """
Don Garrettbf90cdf2017-05-19 15:54:02 -0700418 logging.info('Bootstrap cbuildbot in: %s', buildroot)
Don Garrettbf90cdf2017-05-19 15:54:02 -0700419
Don Garrettd1d90dd2017-06-13 17:35:52 -0700420 # Fixup buildroot parameter.
421 argv = argv[:]
Mike Frysinger79cca962019-06-13 15:26:53 -0400422 for i, arg in enumerate(argv):
423 if arg in ('-r', '--buildroot'):
424 argv[i + 1] = buildroot
Don Garrett597ddff2017-02-17 18:29:37 -0800425
Don Garrettd1d90dd2017-06-13 17:35:52 -0700426 # This filters out command line arguments not supported by older versions
427 # of cbuildbot.
428 parser = cbuildbot.CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400429 options = cbuildbot.ParseCommandLine(parser, argv)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700430 cbuildbot_path = os.path.join(buildroot, 'chromite', 'bin', 'cbuildbot')
Don Garrett597ddff2017-02-17 18:29:37 -0800431 cmd = sync_stages.BootstrapStage.FilterArgsForTargetCbuildbot(
Don Garrettbf90cdf2017-05-19 15:54:02 -0700432 buildroot, cbuildbot_path, options)
Don Garrett597ddff2017-02-17 18:29:37 -0800433
Don Garretta50bf492017-09-28 18:33:02 -0700434 # We want cbuildbot to use branched depot_tools scripts from our manifest,
435 # so that depot_tools is branched to match cbuildbot.
436 logging.info('Adding depot_tools into PATH: %s', depot_tools_path)
437 extra_env = {'PATH': PrependPath(depot_tools_path)}
438
Lann Martinebae73d2018-05-21 17:12:00 -0600439 # TODO(crbug.com/845304): Remove once underlying boto issues are resolved.
Lann Martin8c4c6802018-05-23 11:09:46 -0600440 fix_boto = ShouldFixBotoCerts(options)
Lann Martinebae73d2018-05-21 17:12:00 -0600441
442 with boto_compat.FixBotoCerts(activate=fix_boto):
Mike Frysinger45602c72019-09-22 02:15:11 -0400443 result = cros_build_lib.run(
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500444 cmd, extra_env=extra_env, check=False, cwd=buildroot)
Lann Martinebae73d2018-05-21 17:12:00 -0600445
Don Garrettacbb2392017-05-11 18:27:41 -0700446 return result.returncode
Don Garrettc4114cc2016-11-01 20:04:06 -0700447
Don Garrett60967922017-04-12 18:51:44 -0700448
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700449@StageDecorator
450def CleanupChroot(buildroot):
451 """Unmount/clean up an image-based chroot without deleting the backing image.
452
453 Args:
454 buildroot: Directory containing the chroot to be cleaned up.
455 """
456 chroot_dir = os.path.join(buildroot, constants.DEFAULT_CHROOT_DIR)
457 logging.info('Cleaning up chroot at %s', chroot_dir)
458 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
Mike Frysingerf0146252019-09-02 13:31:05 -0400459 try:
460 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=False)
461 except timeout_util.TimeoutError:
462 logging.exception('Cleaning up chroot timed out')
463 # Dump debug info to help https://crbug.com/1000034.
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500464 cros_build_lib.run(['mount'], check=True)
465 cros_build_lib.run(['uname', '-a'], check=True)
466 cros_build_lib.sudo_run(['losetup', '-a'], check=True)
467 cros_build_lib.run(['dmesg'], check=True)
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400468 logging.warning('Assuming the bot is going to reboot, so ignoring this '
469 'failure; see https://crbug.com/1000034')
Mike Frysingerf0146252019-09-02 13:31:05 -0400470
Chris McDonaldb55b7032021-06-17 16:41:32 -0600471 # NB: We ignore errors at this point because this stage runs last. If the
472 # chroot failed to unmount, we're going to reboot the system once we're done,
473 # and that will implicitly take care of cleaning things up. If the bots stop
474 # rebooting after every run, we'll need to make this fatal all the time.
475 #
476 # TODO(crbug.com/1000034): This should be fatal all the time.
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700477
478
Don Garrettf15d65b2017-04-12 12:39:55 -0700479def ConfigureGlobalEnvironment():
480 """Setup process wide environmental changes."""
Don Garrettf15d65b2017-04-12 12:39:55 -0700481 # Set umask to 022 so files created by buildbot are readable.
482 os.umask(0o22)
483
Don Garrett86fec482017-05-17 18:13:33 -0700484 # These variables can interfere with LANG / locale behavior.
485 unwanted_local_vars = [
486 'LC_ALL', 'LC_CTYPE', 'LC_COLLATE', 'LC_TIME', 'LC_NUMERIC',
487 'LC_MONETARY', 'LC_MESSAGES', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
488 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION',
489 ]
490 for v in unwanted_local_vars:
491 os.environ.pop(v, None)
492
493 # This variable is required for repo sync's to work in all cases.
494 os.environ['LANG'] = 'en_US.UTF-8'
495
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000496
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600497def _main(options, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700498 """main method of script.
499
500 Args:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600501 options: preparsed options object for the build.
Don Garrettc4114cc2016-11-01 20:04:06 -0700502 argv: All command line arguments to pass as list of strings.
503
504 Returns:
505 Return code of cbuildbot as an integer.
506 """
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000507 branchname = options.branch or 'main'
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000508 root = options.buildroot
509 buildroot = os.path.join(root, 'repository')
510 workspace = os.path.join(root, 'workspace')
Don Garretta50bf492017-09-28 18:33:02 -0700511 depot_tools_path = os.path.join(buildroot, constants.DEPOT_TOOLS_SUBPATH)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700512
Ben Pastenec8e4e792018-05-14 20:20:25 +0000513 # Does the entire build pass or fail.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600514 with metrics.Presence(METRIC_ACTIVE), \
515 metrics.SuccessCounter(METRIC_COMPLETED) as s_fields:
Don Garrettc4114cc2016-11-01 20:04:06 -0700516
Ben Pastenec8e4e792018-05-14 20:20:25 +0000517 # Preliminary set, mostly command line parsing.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600518 with metrics.SuccessCounter(METRIC_INVOKED):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000519 if options.enable_buildbot_tags:
Chris McDonaldb55b7032021-06-17 16:41:32 -0600520 cbuildbot_alerts.EnableBuildbotMarkers()
Ben Pastenec8e4e792018-05-14 20:20:25 +0000521 ConfigureGlobalEnvironment()
Don Garrett86881cb2017-02-15 15:41:55 -0800522
Ben Pastenec8e4e792018-05-14 20:20:25 +0000523 # Prepare the buildroot with source for the build.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600524 with metrics.SuccessCounter(METRIC_PREP):
Alex Klein2ab29cc2018-07-19 12:01:00 -0600525 manifest_url = config_lib.GetSiteParams().MANIFEST_INT_URL
Ben Pastenec8e4e792018-05-14 20:20:25 +0000526 repo = repository.RepoRepository(manifest_url, buildroot,
527 branch=branchname,
Don Garrett33872502018-08-03 22:30:40 +0000528 git_cache_dir=options.git_cache_dir)
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000529 previous_build_state = GetLastBuildState(root)
Don Garrett86881cb2017-02-15 15:41:55 -0800530
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000531 # Clean up the buildroot to a safe state.
532 with metrics.SecondsTimer(METRIC_CLEAN):
533 build_state = GetCurrentBuildState(options, branchname)
534 CleanBuildRoot(root, repo, options.cache_dir, build_state)
Don Garrettacbb2392017-05-11 18:27:41 -0700535
Ben Pastenec8e4e792018-05-14 20:20:25 +0000536 # Get a checkout close enough to the branch that cbuildbot can handle it.
537 if options.sync:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600538 with metrics.SecondsTimer(METRIC_INITIAL):
Mike Nichols9fb48832021-01-29 14:47:15 -0700539 InitialCheckout(repo, options)
Don Garrettacbb2392017-05-11 18:27:41 -0700540
Ben Pastenec8e4e792018-05-14 20:20:25 +0000541 # Run cbuildbot inside the full ChromeOS checkout, on the specified branch.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600542 with metrics.SecondsTimer(METRIC_CBUILDBOT), \
543 metrics.SecondsInstanceTimer(METRIC_CBUILDBOT_INSTANCE):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000544 if previous_build_state.is_valid():
545 argv.append('--previous-build-state')
Mike Frysinger1a443332019-11-24 02:48:03 -0500546 argv.append(base64.b64encode(previous_build_state.to_json().encode(
547 'utf-8')).decode('utf-8'))
Don Garrettb497f552018-07-09 16:01:13 -0700548 argv.extend(['--workspace', workspace])
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600549
Don Garrett61ce1ee2019-02-26 16:20:25 -0800550 if not options.cache_dir_specified:
551 argv.extend(['--cache-dir', options.cache_dir])
552
Ben Pastenec8e4e792018-05-14 20:20:25 +0000553 result = Cbuildbot(buildroot, depot_tools_path, argv)
554 s_fields['success'] = (result == 0)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600555
Ben Pastenec8e4e792018-05-14 20:20:25 +0000556 build_state.status = (
557 constants.BUILDER_STATUS_PASSED
558 if result == 0 else constants.BUILDER_STATUS_FAILED)
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000559 SetLastBuildState(root, build_state)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600560
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600561 with metrics.SecondsTimer(METRIC_CHROOT_CLEANUP):
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400562 CleanupChroot(buildroot)
Don Garrett91a8cfc2018-06-22 15:39:36 -0700563
Ben Pastenec8e4e792018-05-14 20:20:25 +0000564 return result
565
Don Garrettacbb2392017-05-11 18:27:41 -0700566
567def main(argv):
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600568 options = PreParseArguments(argv)
569 metric_fields = {
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000570 'branch_name': options.branch or 'main',
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600571 'build_config': options.build_config_name,
572 'tryjob': options.remote_trybot,
573 }
574
Ben Pastenec8e4e792018-05-14 20:20:25 +0000575 # Enable Monarch metrics gathering.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600576 with ts_mon_config.SetupTsMonGlobalState('cbuildbot_launch',
577 common_metric_fields=metric_fields,
578 indirect=True):
579 return _main(options, argv)