blob: 7693e36984f9fa4606f1154059326e2f6227e461 [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)
Don Garrett7ade05a2017-02-17 13:31:47 -0800348 logging.info('Bootstrap script starting initial sync on branch: %s',
Don Garrettf324bc32017-05-23 14:00:53 -0700349 repo.branch)
Mike Nichols53f0ab82021-08-26 02:19:37 +0000350 repo.PreLoad('/preload/chromeos')
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000351 repo.Sync(detach=True,
Mike Nichols9fb48832021-01-29 14:47:15 -0700352 downgrade_repo=_ShouldDowngradeRepo(options))
Don Garrettc4114cc2016-11-01 20:04:06 -0700353
354
Lann Martin8c4c6802018-05-23 11:09:46 -0600355def ShouldFixBotoCerts(options):
356 """Decide if FixBotoCerts should be applied for this branch."""
357 try:
358 # Only apply to factory and firmware branches.
359 branch = options.branch or ''
360 prefix = branch.split('-')[0]
361 if prefix not in ('factory', 'firmware'):
362 return False
363
364 # Only apply to "old" branches.
365 if branch.endswith('.B'):
366 version = branch[:-2].split('-')[-1]
367 major = int(version.split('.')[0])
368 return major <= 9667 # This is the newest known to be failing.
369
370 return False
Mike Frysinger9f470262018-08-03 15:09:58 -0400371 except Exception as e:
Lann Martin8c4c6802018-05-23 11:09:46 -0600372 logging.warning(' failed: %s', e)
373 # Conservatively continue without the fix.
374 return False
375
376
Mike Nichols9fb48832021-01-29 14:47:15 -0700377def _ShouldDowngradeRepo(options):
378 """Determine which repo version to set for the branch.
379
380 Repo version is set at cache creation time, in the nightly builder,
381 which means we are typically at the latest version. Older branches
382 are incompatible with newer version of ToT, therefore we downgrade
383 repo to a known working version.
384
385 Args:
386 options: A parsed options object from a cbuildbot parser.
387
388 Returns:
389 bool of whether to downgrade repo version based on branch.
390 """
391 try:
392 branch = options.branch or ''
393 # Only apply to "old" branches.
394 if branch.endswith('.B'):
395 branch_num = branch[:-2].split('-')[1][1:3]
396 return branch_num <= 79 # This is the newest known to be failing.
397
398 return False
399 except Exception as e:
400 logging.warning(' failed: %s', e)
401 # Conservatively continue without the fix.
402 return False
403
404
Don Garrett066e6f52017-09-28 19:14:01 -0700405@StageDecorator
Don Garrett6e5c6b92018-04-06 17:58:49 -0700406def Cbuildbot(buildroot, depot_tools_path, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700407 """Start cbuildbot in specified directory with all arguments.
408
409 Args:
Don Garrettbf90cdf2017-05-19 15:54:02 -0700410 buildroot: Directory to be passed to cbuildbot with --buildroot.
Don Garretta50bf492017-09-28 18:33:02 -0700411 depot_tools_path: Directory for depot_tools to be used by cbuildbot.
Don Garrettd1d90dd2017-06-13 17:35:52 -0700412 argv: Command line options passed to cbuildbot_launch.
Don Garrettc4114cc2016-11-01 20:04:06 -0700413
414 Returns:
415 Return code of cbuildbot as an integer.
416 """
Don Garrettbf90cdf2017-05-19 15:54:02 -0700417 logging.info('Bootstrap cbuildbot in: %s', buildroot)
Don Garrettbf90cdf2017-05-19 15:54:02 -0700418
Don Garrettd1d90dd2017-06-13 17:35:52 -0700419 # Fixup buildroot parameter.
420 argv = argv[:]
Mike Frysinger79cca962019-06-13 15:26:53 -0400421 for i, arg in enumerate(argv):
422 if arg in ('-r', '--buildroot'):
423 argv[i + 1] = buildroot
Don Garrett597ddff2017-02-17 18:29:37 -0800424
Don Garrettd1d90dd2017-06-13 17:35:52 -0700425 # This filters out command line arguments not supported by older versions
426 # of cbuildbot.
427 parser = cbuildbot.CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400428 options = cbuildbot.ParseCommandLine(parser, argv)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700429 cbuildbot_path = os.path.join(buildroot, 'chromite', 'bin', 'cbuildbot')
Don Garrett597ddff2017-02-17 18:29:37 -0800430 cmd = sync_stages.BootstrapStage.FilterArgsForTargetCbuildbot(
Don Garrettbf90cdf2017-05-19 15:54:02 -0700431 buildroot, cbuildbot_path, options)
Don Garrett597ddff2017-02-17 18:29:37 -0800432
Don Garretta50bf492017-09-28 18:33:02 -0700433 # We want cbuildbot to use branched depot_tools scripts from our manifest,
434 # so that depot_tools is branched to match cbuildbot.
435 logging.info('Adding depot_tools into PATH: %s', depot_tools_path)
436 extra_env = {'PATH': PrependPath(depot_tools_path)}
437
Lann Martinebae73d2018-05-21 17:12:00 -0600438 # TODO(crbug.com/845304): Remove once underlying boto issues are resolved.
Lann Martin8c4c6802018-05-23 11:09:46 -0600439 fix_boto = ShouldFixBotoCerts(options)
Lann Martinebae73d2018-05-21 17:12:00 -0600440
441 with boto_compat.FixBotoCerts(activate=fix_boto):
Mike Frysinger45602c72019-09-22 02:15:11 -0400442 result = cros_build_lib.run(
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500443 cmd, extra_env=extra_env, check=False, cwd=buildroot)
Lann Martinebae73d2018-05-21 17:12:00 -0600444
Don Garrettacbb2392017-05-11 18:27:41 -0700445 return result.returncode
Don Garrettc4114cc2016-11-01 20:04:06 -0700446
Don Garrett60967922017-04-12 18:51:44 -0700447
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700448@StageDecorator
449def CleanupChroot(buildroot):
450 """Unmount/clean up an image-based chroot without deleting the backing image.
451
452 Args:
453 buildroot: Directory containing the chroot to be cleaned up.
454 """
455 chroot_dir = os.path.join(buildroot, constants.DEFAULT_CHROOT_DIR)
456 logging.info('Cleaning up chroot at %s', chroot_dir)
457 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
Mike Frysingerf0146252019-09-02 13:31:05 -0400458 try:
459 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=False)
460 except timeout_util.TimeoutError:
461 logging.exception('Cleaning up chroot timed out')
462 # Dump debug info to help https://crbug.com/1000034.
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500463 cros_build_lib.run(['mount'], check=True)
464 cros_build_lib.run(['uname', '-a'], check=True)
465 cros_build_lib.sudo_run(['losetup', '-a'], check=True)
466 cros_build_lib.run(['dmesg'], check=True)
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400467 logging.warning('Assuming the bot is going to reboot, so ignoring this '
468 'failure; see https://crbug.com/1000034')
Mike Frysingerf0146252019-09-02 13:31:05 -0400469
Chris McDonaldb55b7032021-06-17 16:41:32 -0600470 # NB: We ignore errors at this point because this stage runs last. If the
471 # chroot failed to unmount, we're going to reboot the system once we're done,
472 # and that will implicitly take care of cleaning things up. If the bots stop
473 # rebooting after every run, we'll need to make this fatal all the time.
474 #
475 # TODO(crbug.com/1000034): This should be fatal all the time.
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700476
477
Don Garrettf15d65b2017-04-12 12:39:55 -0700478def ConfigureGlobalEnvironment():
479 """Setup process wide environmental changes."""
Don Garrettf15d65b2017-04-12 12:39:55 -0700480 # Set umask to 022 so files created by buildbot are readable.
481 os.umask(0o22)
482
Don Garrett86fec482017-05-17 18:13:33 -0700483 # These variables can interfere with LANG / locale behavior.
484 unwanted_local_vars = [
485 'LC_ALL', 'LC_CTYPE', 'LC_COLLATE', 'LC_TIME', 'LC_NUMERIC',
486 'LC_MONETARY', 'LC_MESSAGES', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
487 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION',
488 ]
489 for v in unwanted_local_vars:
490 os.environ.pop(v, None)
491
492 # This variable is required for repo sync's to work in all cases.
493 os.environ['LANG'] = 'en_US.UTF-8'
494
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000495
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600496def _main(options, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700497 """main method of script.
498
499 Args:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600500 options: preparsed options object for the build.
Don Garrettc4114cc2016-11-01 20:04:06 -0700501 argv: All command line arguments to pass as list of strings.
502
503 Returns:
504 Return code of cbuildbot as an integer.
505 """
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000506 branchname = options.branch or 'main'
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000507 root = options.buildroot
508 buildroot = os.path.join(root, 'repository')
509 workspace = os.path.join(root, 'workspace')
Don Garretta50bf492017-09-28 18:33:02 -0700510 depot_tools_path = os.path.join(buildroot, constants.DEPOT_TOOLS_SUBPATH)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700511
Ben Pastenec8e4e792018-05-14 20:20:25 +0000512 # Does the entire build pass or fail.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600513 with metrics.Presence(METRIC_ACTIVE), \
514 metrics.SuccessCounter(METRIC_COMPLETED) as s_fields:
Don Garrettc4114cc2016-11-01 20:04:06 -0700515
Ben Pastenec8e4e792018-05-14 20:20:25 +0000516 # Preliminary set, mostly command line parsing.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600517 with metrics.SuccessCounter(METRIC_INVOKED):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000518 if options.enable_buildbot_tags:
Chris McDonaldb55b7032021-06-17 16:41:32 -0600519 cbuildbot_alerts.EnableBuildbotMarkers()
Ben Pastenec8e4e792018-05-14 20:20:25 +0000520 ConfigureGlobalEnvironment()
Don Garrett86881cb2017-02-15 15:41:55 -0800521
Ben Pastenec8e4e792018-05-14 20:20:25 +0000522 # Prepare the buildroot with source for the build.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600523 with metrics.SuccessCounter(METRIC_PREP):
Alex Klein2ab29cc2018-07-19 12:01:00 -0600524 manifest_url = config_lib.GetSiteParams().MANIFEST_INT_URL
Ben Pastenec8e4e792018-05-14 20:20:25 +0000525 repo = repository.RepoRepository(manifest_url, buildroot,
526 branch=branchname,
Don Garrett33872502018-08-03 22:30:40 +0000527 git_cache_dir=options.git_cache_dir)
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000528 previous_build_state = GetLastBuildState(root)
Don Garrett86881cb2017-02-15 15:41:55 -0800529
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000530 # Clean up the buildroot to a safe state.
531 with metrics.SecondsTimer(METRIC_CLEAN):
532 build_state = GetCurrentBuildState(options, branchname)
533 CleanBuildRoot(root, repo, options.cache_dir, build_state)
Don Garrettacbb2392017-05-11 18:27:41 -0700534
Ben Pastenec8e4e792018-05-14 20:20:25 +0000535 # Get a checkout close enough to the branch that cbuildbot can handle it.
536 if options.sync:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600537 with metrics.SecondsTimer(METRIC_INITIAL):
Mike Nichols9fb48832021-01-29 14:47:15 -0700538 InitialCheckout(repo, options)
Don Garrettacbb2392017-05-11 18:27:41 -0700539
Ben Pastenec8e4e792018-05-14 20:20:25 +0000540 # Run cbuildbot inside the full ChromeOS checkout, on the specified branch.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600541 with metrics.SecondsTimer(METRIC_CBUILDBOT), \
542 metrics.SecondsInstanceTimer(METRIC_CBUILDBOT_INSTANCE):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000543 if previous_build_state.is_valid():
544 argv.append('--previous-build-state')
Mike Frysinger1a443332019-11-24 02:48:03 -0500545 argv.append(base64.b64encode(previous_build_state.to_json().encode(
546 'utf-8')).decode('utf-8'))
Don Garrettb497f552018-07-09 16:01:13 -0700547 argv.extend(['--workspace', workspace])
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600548
Don Garrett61ce1ee2019-02-26 16:20:25 -0800549 if not options.cache_dir_specified:
550 argv.extend(['--cache-dir', options.cache_dir])
551
Ben Pastenec8e4e792018-05-14 20:20:25 +0000552 result = Cbuildbot(buildroot, depot_tools_path, argv)
553 s_fields['success'] = (result == 0)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600554
Ben Pastenec8e4e792018-05-14 20:20:25 +0000555 build_state.status = (
556 constants.BUILDER_STATUS_PASSED
557 if result == 0 else constants.BUILDER_STATUS_FAILED)
Mike Nicholsd0acc7f2021-05-21 17:18:24 +0000558 SetLastBuildState(root, build_state)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600559
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600560 with metrics.SecondsTimer(METRIC_CHROOT_CLEANUP):
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400561 CleanupChroot(buildroot)
Don Garrett91a8cfc2018-06-22 15:39:36 -0700562
Ben Pastenec8e4e792018-05-14 20:20:25 +0000563 return result
564
Don Garrettacbb2392017-05-11 18:27:41 -0700565
566def main(argv):
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600567 options = PreParseArguments(argv)
568 metric_fields = {
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000569 'branch_name': options.branch or 'main',
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600570 'build_config': options.build_config_name,
571 'tryjob': options.remote_trybot,
572 }
573
Ben Pastenec8e4e792018-05-14 20:20:25 +0000574 # Enable Monarch metrics gathering.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600575 with ts_mon_config.SetupTsMonGlobalState('cbuildbot_launch',
576 common_metric_fields=metric_fields,
577 indirect=True):
578 return _main(options, argv)