blob: e2f09cefe0d5adfd31eee8367fb4c585d268d98b [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
Julio Hurtado9265c7e2021-04-19 23:04:44 +000011script will use 'main'.
Don Garrettc4114cc2016-11-01 20:04:06 -070012
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
Don Garrettc4114cc2016-11-01 20:04:06 -070023
24from chromite.cbuildbot import repository
Don Garrett597ddff2017-02-17 18:29:37 -080025from chromite.cbuildbot.stages import sync_stages
Lann Martinebae73d2018-05-21 17:12:00 -060026from chromite.lib import boto_compat
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060027from chromite.lib import build_summary
Don Garrett86881cb2017-02-15 15:41:55 -080028from chromite.lib import config_lib
Don Garretta50bf492017-09-28 18:33:02 -070029from chromite.lib import constants
Don Garrettc4114cc2016-11-01 20:04:06 -070030from chromite.lib import cros_build_lib
31from chromite.lib import cros_logging as logging
Benjamin Gordon74645232018-05-04 17:40:42 -060032from chromite.lib import cros_sdk_lib
Don Garrettacbb2392017-05-11 18:27:41 -070033from chromite.lib import metrics
Don Garrettc4114cc2016-11-01 20:04:06 -070034from chromite.lib import osutils
Mike Frysingerf0146252019-09-02 13:31:05 -040035from chromite.lib import timeout_util
Don Garrettacbb2392017-05-11 18:27:41 -070036from chromite.lib import ts_mon_config
Don Garrett86881cb2017-02-15 15:41:55 -080037from chromite.scripts import cbuildbot
Don Garrettc4114cc2016-11-01 20:04:06 -070038
Mike Frysinger3c831a72020-02-19 02:47:04 -050039
40assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'
41
42
Don Garrett60967922017-04-12 18:51:44 -070043# This number should be incremented when we change the layout of the buildroot
44# in a non-backwards compatible way. This wipes all buildroots.
Don Garrettbf90cdf2017-05-19 15:54:02 -070045BUILDROOT_BUILDROOT_LAYOUT = 2
Prathmesh Prabhuc41a0f52018-04-03 13:26:52 -070046_DISTFILES_CACHE_EXPIRY_HOURS = 8 * 24
Don Garrett60967922017-04-12 18:51:44 -070047
Don Garrettacbb2392017-05-11 18:27:41 -070048# Metrics reported to Monarch.
Mike Nicholscb29fbd2018-07-24 11:09:33 -060049METRIC_PREFIX = 'chromeos/chromite/cbuildbot_launch/'
50METRIC_ACTIVE = METRIC_PREFIX + 'active'
51METRIC_INVOKED = METRIC_PREFIX + 'invoked'
52METRIC_COMPLETED = METRIC_PREFIX + 'completed'
53METRIC_PREP = METRIC_PREFIX + 'prep_completed'
54METRIC_CLEAN = METRIC_PREFIX + 'clean_buildroot_durations'
55METRIC_INITIAL = METRIC_PREFIX + 'initial_checkout_durations'
56METRIC_CBUILDBOT = METRIC_PREFIX + 'cbuildbot_durations'
57METRIC_CBUILDBOT_INSTANCE = METRIC_PREFIX + 'cbuildbot_instance_durations'
58METRIC_CLOBBER = METRIC_PREFIX + 'clobber'
59METRIC_BRANCH_CLEANUP = METRIC_PREFIX + 'branch_cleanup'
60METRIC_DISTFILES_CLEANUP = METRIC_PREFIX + 'distfiles_cleanup'
61METRIC_CHROOT_CLEANUP = METRIC_PREFIX + 'chroot_cleanup'
Don Garrettacbb2392017-05-11 18:27:41 -070062
Benjamin Gordon90b2dd92018-04-12 14:04:21 -060063# Builder state
64BUILDER_STATE_FILENAME = '.cbuildbot_build_state.json'
65
Don Garrett60967922017-04-12 18:51:44 -070066
Don Garrett125d4dc2017-04-25 16:26:03 -070067def StageDecorator(functor):
68 """A Decorator that adds buildbot stage tags around a method.
69
Don Garrettacbb2392017-05-11 18:27:41 -070070 It uses the method name as the stage name, and assumes failure on a true
71 return value, or an exception.
Don Garrett125d4dc2017-04-25 16:26:03 -070072 """
73 @functools.wraps(functor)
74 def wrapped_functor(*args, **kwargs):
75 try:
76 logging.PrintBuildbotStepName(functor.__name__)
Don Garrettacbb2392017-05-11 18:27:41 -070077 result = functor(*args, **kwargs)
Don Garrett125d4dc2017-04-25 16:26:03 -070078 except Exception:
79 logging.PrintBuildbotStepFailure()
80 raise
81
Don Garrettacbb2392017-05-11 18:27:41 -070082 if result:
83 logging.PrintBuildbotStepFailure()
84 return result
85
Don Garrett125d4dc2017-04-25 16:26:03 -070086 return wrapped_functor
87
88
Don Garrettb5fc08b2017-11-20 21:51:16 +000089def field(fields, **kwargs):
Don Garrettacbb2392017-05-11 18:27:41 -070090 """Helper for inserting more fields into a metrics fields dictionary.
91
92 Args:
93 fields: Dictionary of metrics fields.
94 kwargs: Each argument is a key/value pair to insert into dict.
95
96 Returns:
97 Copy of original dictionary with kwargs set as fields.
98 """
99 f = fields.copy()
100 f.update(kwargs)
101 return f
102
Don Garretta50bf492017-09-28 18:33:02 -0700103
104def PrependPath(prepend):
105 """Generate path with new directory at the beginning.
106
107 Args:
108 prepend: Directory to add at the beginning of the path.
109
110 Returns:
111 Extended path as a string.
112 """
113 return os.pathsep.join([prepend, os.environ.get('PATH', os.defpath)])
114
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000115
Don Garrett86881cb2017-02-15 15:41:55 -0800116def PreParseArguments(argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700117 """Extract the branch name from cbuildbot command line arguments.
118
Don Garrettc4114cc2016-11-01 20:04:06 -0700119 Args:
120 argv: The command line arguments to parse.
121
122 Returns:
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000123 Branch as a string ('main' if nothing is specified).
Don Garrettc4114cc2016-11-01 20:04:06 -0700124 """
Don Garrett86881cb2017-02-15 15:41:55 -0800125 parser = cbuildbot.CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400126 options = cbuildbot.ParseCommandLine(parser, argv)
Don Garrett61ce1ee2019-02-26 16:20:25 -0800127
128 if not options.cache_dir:
129 options.cache_dir = os.path.join(options.buildroot,
Mike Nichols207e2a12021-05-20 14:00:29 -0600130 '.cache')
Don Garrett61ce1ee2019-02-26 16:20:25 -0800131
Don Garrettd1d90dd2017-06-13 17:35:52 -0700132 options.Freeze()
Don Garrett86881cb2017-02-15 15:41:55 -0800133
134 # This option isn't required for cbuildbot, but is for us.
135 if not options.buildroot:
136 cros_build_lib.Die('--buildroot is a required option.')
137
138 return options
Don Garrettc4114cc2016-11-01 20:04:06 -0700139
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000140
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600141def GetCurrentBuildState(options, branch):
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600142 """Extract information about the current build state from command-line args.
143
144 Args:
145 options: A parsed options object from a cbuildbot parser.
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600146 branch: The name of the branch this builder was called with.
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600147
148 Returns:
149 A BuildSummary object describing the current build.
150 """
151 build_state = build_summary.BuildSummary(
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600152 status=constants.BUILDER_STATUS_INFLIGHT,
153 buildroot_layout=BUILDROOT_BUILDROOT_LAYOUT,
154 branch=branch)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600155 if options.buildnumber:
156 build_state.build_number = options.buildnumber
157 if options.buildbucket_id:
158 build_state.buildbucket_id = options.buildbucket_id
159 if options.master_build_id:
160 build_state.master_build_id = options.master_build_id
161 return build_state
162
163
164def GetLastBuildState(root):
165 """Fetch the state of the last build run from |root|.
166
167 If the saved state file can't be read or doesn't contain valid JSON, a default
168 state will be returned.
169
170 Args:
171 root: Root of the working directory tree as a string.
172
173 Returns:
174 A BuildSummary object representing the previous build.
175 """
176 state_file = os.path.join(root, BUILDER_STATE_FILENAME)
177
178 state = build_summary.BuildSummary()
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600179
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600180 try:
181 state_raw = osutils.ReadFile(state_file)
182 state.from_json(state_raw)
183 except IOError as e:
184 logging.warning('Unable to read %s: %s', state_file, e)
185 return state
186 except ValueError as e:
187 logging.warning('Saved state file %s is not valid JSON: %s', state_file, e)
188 return state
189
190 if not state.is_valid():
191 logging.warning('Previous build state is not valid. Ignoring.')
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600192 state = build_summary.BuildSummary()
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600193
194 return state
195
196
197def SetLastBuildState(root, new_state):
198 """Save the state of the last build under |root|.
199
200 Args:
201 root: Root of the working directory tree as a string.
202 new_state: BuildSummary object containing the state to be saved.
203 """
204 state_file = os.path.join(root, BUILDER_STATE_FILENAME)
205 osutils.WriteFile(state_file, new_state.to_json())
206
Benjamin Gordon8b6d4122018-04-26 13:38:39 -0600207 # Remove old state file. Its contents have been migrated into the new file.
208 old_state_file = os.path.join(root, '.cbuildbot_launch_state')
209 osutils.SafeUnlink(old_state_file)
210
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600211
Don Garrett125d4dc2017-04-25 16:26:03 -0700212@StageDecorator
Mike Nichols9fb48832021-01-29 14:47:15 -0700213def InitialCheckout(repo, options):
Don Garrett86881cb2017-02-15 15:41:55 -0800214 """Preliminary ChromeOS checkout.
215
216 Perform a complete checkout of ChromeOS on the specified branch. This does NOT
217 match what the build needs, but ensures the buildroot both has a 'hot'
218 checkout, and is close enough that the branched cbuildbot can successfully get
219 the right checkout.
220
221 This checks out full ChromeOS, even if a ChromiumOS build is going to be
222 performed. This is because we have no knowledge of the build config to be
223 used.
Don Garrettc4114cc2016-11-01 20:04:06 -0700224
225 Args:
Don Garrettf324bc32017-05-23 14:00:53 -0700226 repo: repository.RepoRepository instance.
Mike Nichols9fb48832021-01-29 14:47:15 -0700227 options: A parsed options object from a cbuildbot parser.
Don Garrettc4114cc2016-11-01 20:04:06 -0700228 """
Don Garrettf324bc32017-05-23 14:00:53 -0700229 logging.PrintBuildbotStepText('Branch: %s' % repo.branch)
Don Garrett7ade05a2017-02-17 13:31:47 -0800230 logging.info('Bootstrap script starting initial sync on branch: %s',
Don Garrettf324bc32017-05-23 14:00:53 -0700231 repo.branch)
Mike Nichols207e2a12021-05-20 14:00:29 -0600232 repo.Sync(jobs=20,
233 detach=True,
Mike Nichols9fb48832021-01-29 14:47:15 -0700234 downgrade_repo=_ShouldDowngradeRepo(options))
Don Garrettc4114cc2016-11-01 20:04:06 -0700235
236
Lann Martin8c4c6802018-05-23 11:09:46 -0600237def ShouldFixBotoCerts(options):
238 """Decide if FixBotoCerts should be applied for this branch."""
239 try:
240 # Only apply to factory and firmware branches.
241 branch = options.branch or ''
242 prefix = branch.split('-')[0]
243 if prefix not in ('factory', 'firmware'):
244 return False
245
246 # Only apply to "old" branches.
247 if branch.endswith('.B'):
248 version = branch[:-2].split('-')[-1]
249 major = int(version.split('.')[0])
250 return major <= 9667 # This is the newest known to be failing.
251
252 return False
Mike Frysinger9f470262018-08-03 15:09:58 -0400253 except Exception as e:
Lann Martin8c4c6802018-05-23 11:09:46 -0600254 logging.warning(' failed: %s', e)
255 # Conservatively continue without the fix.
256 return False
257
258
Mike Nichols9fb48832021-01-29 14:47:15 -0700259def _ShouldDowngradeRepo(options):
260 """Determine which repo version to set for the branch.
261
262 Repo version is set at cache creation time, in the nightly builder,
263 which means we are typically at the latest version. Older branches
264 are incompatible with newer version of ToT, therefore we downgrade
265 repo to a known working version.
266
267 Args:
268 options: A parsed options object from a cbuildbot parser.
269
270 Returns:
271 bool of whether to downgrade repo version based on branch.
272 """
273 try:
274 branch = options.branch or ''
275 # Only apply to "old" branches.
276 if branch.endswith('.B'):
277 branch_num = branch[:-2].split('-')[1][1:3]
278 return branch_num <= 79 # This is the newest known to be failing.
279
280 return False
281 except Exception as e:
282 logging.warning(' failed: %s', e)
283 # Conservatively continue without the fix.
284 return False
285
286
Don Garrett066e6f52017-09-28 19:14:01 -0700287@StageDecorator
Don Garrett6e5c6b92018-04-06 17:58:49 -0700288def Cbuildbot(buildroot, depot_tools_path, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700289 """Start cbuildbot in specified directory with all arguments.
290
291 Args:
Don Garrettbf90cdf2017-05-19 15:54:02 -0700292 buildroot: Directory to be passed to cbuildbot with --buildroot.
Don Garretta50bf492017-09-28 18:33:02 -0700293 depot_tools_path: Directory for depot_tools to be used by cbuildbot.
Don Garrettd1d90dd2017-06-13 17:35:52 -0700294 argv: Command line options passed to cbuildbot_launch.
Don Garrettc4114cc2016-11-01 20:04:06 -0700295
296 Returns:
297 Return code of cbuildbot as an integer.
298 """
Don Garrettbf90cdf2017-05-19 15:54:02 -0700299 logging.info('Bootstrap cbuildbot in: %s', buildroot)
Don Garrettbf90cdf2017-05-19 15:54:02 -0700300
Don Garrettd1d90dd2017-06-13 17:35:52 -0700301 # Fixup buildroot parameter.
302 argv = argv[:]
Mike Frysinger79cca962019-06-13 15:26:53 -0400303 for i, arg in enumerate(argv):
304 if arg in ('-r', '--buildroot'):
305 argv[i + 1] = buildroot
Don Garrett597ddff2017-02-17 18:29:37 -0800306
Don Garrettd1d90dd2017-06-13 17:35:52 -0700307 # This filters out command line arguments not supported by older versions
308 # of cbuildbot.
309 parser = cbuildbot.CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400310 options = cbuildbot.ParseCommandLine(parser, argv)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700311 cbuildbot_path = os.path.join(buildroot, 'chromite', 'bin', 'cbuildbot')
Don Garrett597ddff2017-02-17 18:29:37 -0800312 cmd = sync_stages.BootstrapStage.FilterArgsForTargetCbuildbot(
Don Garrettbf90cdf2017-05-19 15:54:02 -0700313 buildroot, cbuildbot_path, options)
Don Garrett597ddff2017-02-17 18:29:37 -0800314
Don Garretta50bf492017-09-28 18:33:02 -0700315 # We want cbuildbot to use branched depot_tools scripts from our manifest,
316 # so that depot_tools is branched to match cbuildbot.
317 logging.info('Adding depot_tools into PATH: %s', depot_tools_path)
318 extra_env = {'PATH': PrependPath(depot_tools_path)}
319
Lann Martinebae73d2018-05-21 17:12:00 -0600320 # TODO(crbug.com/845304): Remove once underlying boto issues are resolved.
Lann Martin8c4c6802018-05-23 11:09:46 -0600321 fix_boto = ShouldFixBotoCerts(options)
Lann Martinebae73d2018-05-21 17:12:00 -0600322
323 with boto_compat.FixBotoCerts(activate=fix_boto):
Mike Frysinger45602c72019-09-22 02:15:11 -0400324 result = cros_build_lib.run(
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500325 cmd, extra_env=extra_env, check=False, cwd=buildroot)
Lann Martinebae73d2018-05-21 17:12:00 -0600326
Don Garrettacbb2392017-05-11 18:27:41 -0700327 return result.returncode
Don Garrettc4114cc2016-11-01 20:04:06 -0700328
Don Garrett60967922017-04-12 18:51:44 -0700329
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700330@StageDecorator
331def CleanupChroot(buildroot):
332 """Unmount/clean up an image-based chroot without deleting the backing image.
333
334 Args:
335 buildroot: Directory containing the chroot to be cleaned up.
336 """
337 chroot_dir = os.path.join(buildroot, constants.DEFAULT_CHROOT_DIR)
338 logging.info('Cleaning up chroot at %s', chroot_dir)
339 if os.path.exists(chroot_dir) or os.path.exists(chroot_dir + '.img'):
Mike Frysingerf0146252019-09-02 13:31:05 -0400340 try:
341 cros_sdk_lib.CleanupChrootMount(chroot_dir, delete=False)
342 except timeout_util.TimeoutError:
343 logging.exception('Cleaning up chroot timed out')
344 # Dump debug info to help https://crbug.com/1000034.
Mike Frysingerf5a3b2d2019-12-12 14:36:17 -0500345 cros_build_lib.run(['mount'], check=True)
346 cros_build_lib.run(['uname', '-a'], check=True)
347 cros_build_lib.sudo_run(['losetup', '-a'], check=True)
348 cros_build_lib.run(['dmesg'], check=True)
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400349 logging.warning('Assuming the bot is going to reboot, so ignoring this '
350 'failure; see https://crbug.com/1000034')
Mike Frysingerf0146252019-09-02 13:31:05 -0400351
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400352 # NB: We ignore errors at this point because this stage runs last. If the
353 # chroot failed to unmount, we're going to reboot the system once we're done,
354 # and that will implicitly take care of cleaning things up. If the bots stop
355 # rebooting after every run, we'll need to make this fatal all the time.
356 #
357 # TODO(crbug.com/1000034): This should be fatal all the time.
Benjamin Gordonaee36b82018-02-05 14:25:26 -0700358
359
Don Garrettf15d65b2017-04-12 12:39:55 -0700360def ConfigureGlobalEnvironment():
361 """Setup process wide environmental changes."""
Don Garrettf15d65b2017-04-12 12:39:55 -0700362 # Set umask to 022 so files created by buildbot are readable.
363 os.umask(0o22)
364
Don Garrett86fec482017-05-17 18:13:33 -0700365 # These variables can interfere with LANG / locale behavior.
366 unwanted_local_vars = [
367 'LC_ALL', 'LC_CTYPE', 'LC_COLLATE', 'LC_TIME', 'LC_NUMERIC',
368 'LC_MONETARY', 'LC_MESSAGES', 'LC_PAPER', 'LC_NAME', 'LC_ADDRESS',
369 'LC_TELEPHONE', 'LC_MEASUREMENT', 'LC_IDENTIFICATION',
370 ]
371 for v in unwanted_local_vars:
372 os.environ.pop(v, None)
373
374 # This variable is required for repo sync's to work in all cases.
375 os.environ['LANG'] = 'en_US.UTF-8'
376
Aviv Keshetc38eebe2018-09-27 23:19:58 +0000377
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600378def _main(options, argv):
Don Garrettc4114cc2016-11-01 20:04:06 -0700379 """main method of script.
380
381 Args:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600382 options: preparsed options object for the build.
Don Garrettc4114cc2016-11-01 20:04:06 -0700383 argv: All command line arguments to pass as list of strings.
384
385 Returns:
386 Return code of cbuildbot as an integer.
387 """
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000388 branchname = options.branch or 'main'
Mike Nichols207e2a12021-05-20 14:00:29 -0600389 buildroot = options.buildroot
390 workspace = options.workspace
Don Garretta50bf492017-09-28 18:33:02 -0700391 depot_tools_path = os.path.join(buildroot, constants.DEPOT_TOOLS_SUBPATH)
Don Garrettd1d90dd2017-06-13 17:35:52 -0700392
Ben Pastenec8e4e792018-05-14 20:20:25 +0000393 # Does the entire build pass or fail.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600394 with metrics.Presence(METRIC_ACTIVE), \
395 metrics.SuccessCounter(METRIC_COMPLETED) as s_fields:
Don Garrettc4114cc2016-11-01 20:04:06 -0700396
Ben Pastenec8e4e792018-05-14 20:20:25 +0000397 # Preliminary set, mostly command line parsing.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600398 with metrics.SuccessCounter(METRIC_INVOKED):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000399 if options.enable_buildbot_tags:
400 logging.EnableBuildbotMarkers()
401 ConfigureGlobalEnvironment()
Don Garrett86881cb2017-02-15 15:41:55 -0800402
Ben Pastenec8e4e792018-05-14 20:20:25 +0000403 # Prepare the buildroot with source for the build.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600404 with metrics.SuccessCounter(METRIC_PREP):
Alex Klein2ab29cc2018-07-19 12:01:00 -0600405 manifest_url = config_lib.GetSiteParams().MANIFEST_INT_URL
Ben Pastenec8e4e792018-05-14 20:20:25 +0000406 repo = repository.RepoRepository(manifest_url, buildroot,
407 branch=branchname,
Don Garrett33872502018-08-03 22:30:40 +0000408 git_cache_dir=options.git_cache_dir)
Mike Nichols207e2a12021-05-20 14:00:29 -0600409 previous_build_state = GetLastBuildState(buildroot)
Don Garrett86881cb2017-02-15 15:41:55 -0800410
Mike Nichols207e2a12021-05-20 14:00:29 -0600411 build_state = GetCurrentBuildState(options, branchname)
Don Garrettacbb2392017-05-11 18:27:41 -0700412
Ben Pastenec8e4e792018-05-14 20:20:25 +0000413 # Get a checkout close enough to the branch that cbuildbot can handle it.
414 if options.sync:
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600415 with metrics.SecondsTimer(METRIC_INITIAL):
Mike Nichols9fb48832021-01-29 14:47:15 -0700416 InitialCheckout(repo, options)
Don Garrettacbb2392017-05-11 18:27:41 -0700417
Ben Pastenec8e4e792018-05-14 20:20:25 +0000418 # Run cbuildbot inside the full ChromeOS checkout, on the specified branch.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600419 with metrics.SecondsTimer(METRIC_CBUILDBOT), \
420 metrics.SecondsInstanceTimer(METRIC_CBUILDBOT_INSTANCE):
Ben Pastenec8e4e792018-05-14 20:20:25 +0000421 if previous_build_state.is_valid():
422 argv.append('--previous-build-state')
Mike Frysinger1a443332019-11-24 02:48:03 -0500423 argv.append(base64.b64encode(previous_build_state.to_json().encode(
424 'utf-8')).decode('utf-8'))
Don Garrettb497f552018-07-09 16:01:13 -0700425 argv.extend(['--workspace', workspace])
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600426
Don Garrett61ce1ee2019-02-26 16:20:25 -0800427 if not options.cache_dir_specified:
428 argv.extend(['--cache-dir', options.cache_dir])
429
Ben Pastenec8e4e792018-05-14 20:20:25 +0000430 result = Cbuildbot(buildroot, depot_tools_path, argv)
431 s_fields['success'] = (result == 0)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600432
Ben Pastenec8e4e792018-05-14 20:20:25 +0000433 build_state.status = (
434 constants.BUILDER_STATUS_PASSED
435 if result == 0 else constants.BUILDER_STATUS_FAILED)
Mike Nichols207e2a12021-05-20 14:00:29 -0600436 SetLastBuildState(buildroot, build_state)
Benjamin Gordon90b2dd92018-04-12 14:04:21 -0600437
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600438 with metrics.SecondsTimer(METRIC_CHROOT_CLEANUP):
Mike Frysinger7a63ee72019-09-03 14:24:06 -0400439 CleanupChroot(buildroot)
Don Garrett91a8cfc2018-06-22 15:39:36 -0700440
Ben Pastenec8e4e792018-05-14 20:20:25 +0000441 return result
442
Don Garrettacbb2392017-05-11 18:27:41 -0700443
444def main(argv):
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600445 options = PreParseArguments(argv)
446 metric_fields = {
Julio Hurtado9265c7e2021-04-19 23:04:44 +0000447 'branch_name': options.branch or 'main',
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600448 'build_config': options.build_config_name,
449 'tryjob': options.remote_trybot,
450 }
451
Ben Pastenec8e4e792018-05-14 20:20:25 +0000452 # Enable Monarch metrics gathering.
Dhanya Ganesh95c5c152018-10-08 16:48:29 -0600453 with ts_mon_config.SetupTsMonGlobalState('cbuildbot_launch',
454 common_metric_fields=metric_fields,
455 indirect=True):
456 return _main(options, argv)