blob: ddd7f526e269e5f240d13ff6755bacf69345b9d9 [file] [log] [blame]
Mike Frysingerf1ba7ad2022-09-12 05:42:57 -04001# Copyright 2012 The ChromiumOS Authors
Brian Harring3fec5a82012-03-01 05:57:03 -08002# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Main builder code for Chromium OS.
6
7Used by Chromium OS buildbot configuration for all Chromium OS builds including
8full and pre-flight-queue builds.
9"""
10
Chris McDonaldb55b7032021-06-17 16:41:32 -060011import distutils.version # pylint: disable=import-error,no-name-in-module
Brian Harring3fec5a82012-03-01 05:57:03 -080012import glob
Aviv Keshet669eb5e2014-06-23 08:53:01 -070013import json
Chris McDonaldb55b7032021-06-17 16:41:32 -060014import logging
Mike Frysingerb0b0caa2015-11-07 01:05:18 -050015import optparse # pylint: disable=deprecated-module
Brian Harring3fec5a82012-03-01 05:57:03 -080016import os
Aviv Keshetcf9c2722014-02-25 15:15:10 -080017import pickle
Brian Harring3fec5a82012-03-01 05:57:03 -080018import sys
19
Mike Frysingere4d68c22015-02-04 21:26:24 -050020from chromite.cbuildbot import builders
Chris McDonaldb55b7032021-06-17 16:41:32 -060021from chromite.cbuildbot import cbuildbot_alerts
Don Garrett88b8d782014-05-13 17:30:55 -070022from chromite.cbuildbot import cbuildbot_run
Don Garrett88b8d782014-05-13 17:30:55 -070023from chromite.cbuildbot import repository
Aviv Keshet420de512015-05-18 14:28:48 -070024from chromite.cbuildbot import topology
Don Garrett88b8d782014-05-13 17:30:55 -070025from chromite.cbuildbot.stages import completion_stages
Jared Loucksa9e94bf2021-06-28 10:03:31 -060026from chromite.cbuildbot.stages import test_stages
Ningning Xiaf342b952017-02-15 14:13:33 -080027from chromite.lib import builder_status_lib
Brian Harringc92a7012012-02-29 10:11:34 -080028from chromite.lib import cgroups
Chris McDonaldb55b7032021-06-17 16:41:32 -060029from chromite.lib import cidb
Brian Harringa184efa2012-03-04 11:51:25 -080030from chromite.lib import cleanup
Brian Harringb6cf9142012-09-01 20:43:17 -070031from chromite.lib import commandline
Ningning Xia6a718052016-12-22 10:08:15 -080032from chromite.lib import config_lib
33from chromite.lib import constants
Brian Harring1b8c4c82012-05-29 23:03:04 -070034from chromite.lib import cros_build_lib
Ningning Xia6a718052016-12-22 10:08:15 -080035from chromite.lib import failures_lib
David James97d95872012-11-16 15:09:56 -080036from chromite.lib import git
Stefan Zagerd49d9ff2014-08-15 21:33:37 -070037from chromite.lib import gob_util
Brian Harringaf019fb2012-05-10 15:06:13 -070038from chromite.lib import osutils
David James6450a0a2012-12-04 07:59:53 -080039from chromite.lib import parallel
Don Garrettb4318362014-10-03 15:49:36 -070040from chromite.lib import retry_stats
Brian Harring3fec5a82012-03-01 05:57:03 -080041from chromite.lib import sudo
Michael Mortensen3e86c1e2019-11-21 15:51:54 -070042from chromite.lib import tee
David James3432acd2013-11-27 10:02:18 -080043from chromite.lib import timeout_util
Paul Hobbsfcf10342015-12-29 15:52:31 -080044from chromite.lib import ts_mon_config
Dhanya Ganesh39a48a82018-12-06 16:01:11 -070045from chromite.lib.buildstore import BuildStore
Brian Harring3fec5a82012-03-01 05:57:03 -080046
Ryan Cuiadd49122012-03-21 22:19:58 -070047
Alex Klein1699fab2022-09-08 08:46:06 -060048_DEFAULT_LOG_DIR = "cbuildbot_logs"
49_BUILDBOT_LOG_FILE = "cbuildbot.log"
50_DEFAULT_EXT_BUILDROOT = "trybot"
51_DEFAULT_INT_BUILDROOT = "trybot-internal"
52_BUILDBOT_REQUIRED_BINARIES = ("pbzip2",)
53_API_VERSION_ATTR = "api_version"
54BOARD_DIM_LABEL = "label-board"
55MODEL_DIM_LABEL = "label-model"
56POOL_DIM_LABEL = "label-pool"
Brian Harring3fec5a82012-03-01 05:57:03 -080057
58
Brian Harring3fec5a82012-03-01 05:57:03 -080059def _BackupPreviousLog(log_file, backup_limit=25):
Alex Klein1699fab2022-09-08 08:46:06 -060060 """Rename previous log.
Brian Harring3fec5a82012-03-01 05:57:03 -080061
Alex Klein1699fab2022-09-08 08:46:06 -060062 Args:
63 log_file: The absolute path to the previous log.
64 backup_limit: Maximum number of old logs to keep.
65 """
66 if os.path.exists(log_file):
67 old_logs = sorted(
68 glob.glob(log_file + ".*"), key=distutils.version.LooseVersion
69 )
Brian Harring3fec5a82012-03-01 05:57:03 -080070
Alex Klein1699fab2022-09-08 08:46:06 -060071 if len(old_logs) >= backup_limit:
72 os.remove(old_logs[0])
Brian Harring3fec5a82012-03-01 05:57:03 -080073
Alex Klein1699fab2022-09-08 08:46:06 -060074 last = 0
75 if old_logs:
76 last = int(old_logs.pop().rpartition(".")[2])
Brian Harring3fec5a82012-03-01 05:57:03 -080077
Alex Klein1699fab2022-09-08 08:46:06 -060078 os.rename(log_file, log_file + "." + str(last + 1))
Brian Harring3fec5a82012-03-01 05:57:03 -080079
Ryan Cui5616a512012-08-17 13:39:36 -070080
Gaurav Shah298aa372014-01-31 09:27:24 -080081def _IsDistributedBuilder(options, chrome_rev, build_config):
Alex Klein1699fab2022-09-08 08:46:06 -060082 """Determines whether the builder should be a DistributedBuilder.
Gaurav Shah298aa372014-01-31 09:27:24 -080083
Alex Klein1699fab2022-09-08 08:46:06 -060084 Args:
85 options: options passed on the commandline.
86 chrome_rev: Chrome revision to build.
87 build_config: Builder configuration dictionary.
Gaurav Shah298aa372014-01-31 09:27:24 -080088
Alex Klein1699fab2022-09-08 08:46:06 -060089 Returns:
90 True if the builder should be a distributed_builder
91 """
92 if not options.buildbot:
93 return False
94 elif chrome_rev in (
95 constants.CHROME_REV_TOT,
96 constants.CHROME_REV_LOCAL,
97 constants.CHROME_REV_SPEC,
98 ):
99 # We don't do distributed logic to TOT Chrome PFQ's, nor local
100 # chrome roots (e.g. chrome try bots)
101 # TODO(davidjames): Update any builders that rely on this logic to use
102 # manifest_version=False instead.
103 return False
104 elif build_config["manifest_version"]:
105 return True
106
Gaurav Shah298aa372014-01-31 09:27:24 -0800107 return False
Gaurav Shah298aa372014-01-31 09:27:24 -0800108
109
Don Garretta52a5b02015-06-02 14:52:57 -0700110def _RunBuildStagesWrapper(options, site_config, build_config):
Alex Klein1699fab2022-09-08 08:46:06 -0600111 """Helper function that wraps RunBuildStages()."""
112 logging.info(
113 "cbuildbot was executed with args %s", cros_build_lib.CmdToStr(sys.argv)
114 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800115
Alex Klein1699fab2022-09-08 08:46:06 -0600116 chrome_rev = build_config["chrome_rev"]
117 if options.chrome_rev:
118 chrome_rev = options.chrome_rev
119 if chrome_rev == constants.CHROME_REV_TOT:
120 options.chrome_version = gob_util.GetTipOfTrunkRevision(
121 constants.CHROMIUM_GOB_URL
122 )
123 options.chrome_rev = constants.CHROME_REV_SPEC
David Jamesa0a664e2013-02-13 09:52:01 -0800124
Alex Klein1699fab2022-09-08 08:46:06 -0600125 # If it's likely we'll need to build Chrome, fetch the source.
126 if build_config["sync_chrome"] is None:
127 options.managed_chrome = chrome_rev != constants.CHROME_REV_LOCAL and (
128 not build_config["usepkg_build_packages"]
129 or chrome_rev
130 or build_config["profile"]
131 )
Matt Tennant0940c382014-01-21 20:43:55 -0800132 else:
Alex Klein1699fab2022-09-08 08:46:06 -0600133 options.managed_chrome = build_config["sync_chrome"]
Mike Frysingere4d68c22015-02-04 21:26:24 -0500134
Alex Klein1699fab2022-09-08 08:46:06 -0600135 chrome_root_mgr = None
136 if options.managed_chrome:
137 # Create a temp directory for syncing Chrome source.
138 chrome_root_mgr = osutils.TempDir(prefix="chrome_root_")
139 options.chrome_root = chrome_root_mgr.tempdir
140
141 # We are done munging options values, so freeze options object now to avoid
142 # further abuse of it.
143 # TODO(mtennant): one by one identify each options value override and see if
144 # it can be handled another way. Try to push this freeze closer and closer
145 # to the start of the script (e.g. in or after _PostParseCheck).
146 options.Freeze()
147
148 metadata_dump_dict = {
149 # A detected default has been set before now if it wasn't explicit.
150 "branch": options.branch,
151 }
152 if options.metadata_dump:
Mike Frysinger31fdddd2023-02-24 15:50:55 -0500153 with open(options.metadata_dump, "rb") as metadata_file:
154 metadata_dump_dict = json.load(metadata_file)
Alex Klein1699fab2022-09-08 08:46:06 -0600155
156 with parallel.Manager() as manager:
157 builder_run = cbuildbot_run.BuilderRun(
158 options, site_config, build_config, manager
159 )
160 buildstore = BuildStore()
161 if metadata_dump_dict:
162 builder_run.attrs.metadata.UpdateWithDict(metadata_dump_dict)
163
164 if builder_run.config.builder_class_name is None:
165 # TODO: This should get relocated to chromeos_config.
166 if _IsDistributedBuilder(options, chrome_rev, build_config):
167 builder_cls_name = "simple_builders.DistributedBuilder"
168 else:
169 builder_cls_name = "simple_builders.SimpleBuilder"
170 builder_cls = builders.GetBuilderClass(builder_cls_name)
171 builder = builder_cls(builder_run, buildstore)
172 else:
173 builder = builders.Builder(builder_run, buildstore)
174
175 try:
176 if not builder.Run():
177 sys.exit(1)
178 finally:
179 if chrome_root_mgr:
180 chrome_root_mgr.Cleanup()
Brian Harring3fec5a82012-03-01 05:57:03 -0800181
182
Brian Harring3fec5a82012-03-01 05:57:03 -0800183def _CheckChromeVersionOption(_option, _opt_str, value, parser):
Alex Klein1699fab2022-09-08 08:46:06 -0600184 """Upgrade other options based on chrome_version being passed."""
185 value = value.strip()
Brian Harring3fec5a82012-03-01 05:57:03 -0800186
Alex Klein1699fab2022-09-08 08:46:06 -0600187 if parser.values.chrome_rev is None and value:
188 parser.values.chrome_rev = constants.CHROME_REV_SPEC
Brian Harring3fec5a82012-03-01 05:57:03 -0800189
Alex Klein1699fab2022-09-08 08:46:06 -0600190 parser.values.chrome_version = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800191
192
193def _CheckChromeRootOption(_option, _opt_str, value, parser):
Alex Klein1699fab2022-09-08 08:46:06 -0600194 """Validate and convert chrome_root to full-path form."""
195 if parser.values.chrome_rev is None:
196 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
Brian Harring3fec5a82012-03-01 05:57:03 -0800197
Alex Klein1699fab2022-09-08 08:46:06 -0600198 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800199
200
David Jamesac8c2a72013-02-13 18:44:33 -0800201def FindCacheDir(_parser, _options):
Alex Klein1699fab2022-09-08 08:46:06 -0600202 return None
Brian Harringae0a5322012-09-15 01:46:51 -0700203
204
Ryan Cui5ba7e152012-05-10 14:36:52 -0700205class CustomGroup(optparse.OptionGroup):
Alex Klein1699fab2022-09-08 08:46:06 -0600206 """Custom option group which supports arguments passed-through to trybot."""
David Jameseecba232014-06-11 11:35:11 -0700207
Alex Klein1699fab2022-09-08 08:46:06 -0600208 def add_remote_option(self, *args, **kwargs):
209 """For arguments that are passed-through to remote trybot."""
210 return optparse.OptionGroup.add_option(
211 self, *args, remote_pass_through=True, **kwargs
212 )
Ryan Cui5ba7e152012-05-10 14:36:52 -0700213
214
Ryan Cui1c13a252012-10-16 15:00:16 -0700215class CustomOption(commandline.FilteringOption):
Alex Klein1699fab2022-09-08 08:46:06 -0600216 """Subclass FilteringOption class to implement pass-through and api."""
Ryan Cui5ba7e152012-05-10 14:36:52 -0700217
Alex Klein1699fab2022-09-08 08:46:06 -0600218 def __init__(self, *args, **kwargs):
219 # The remote_pass_through argument specifies whether we should directly
220 # pass the argument (with its value) onto the remote trybot.
221 self.pass_through = kwargs.pop("remote_pass_through", False)
222 self.api_version = int(kwargs.pop("api", "0"))
223 commandline.FilteringOption.__init__(self, *args, **kwargs)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700224
Ryan Cui5ba7e152012-05-10 14:36:52 -0700225
Ryan Cui1c13a252012-10-16 15:00:16 -0700226class CustomParser(commandline.FilteringParser):
Alex Klein1699fab2022-09-08 08:46:06 -0600227 """Custom option parser which supports arguments passed-through to trybot"""
Matt Tennante8179042013-10-01 15:47:32 -0700228
Alex Klein1699fab2022-09-08 08:46:06 -0600229 DEFAULT_OPTION_CLASS = CustomOption
Brian Harringb6cf9142012-09-01 20:43:17 -0700230
Alex Klein1699fab2022-09-08 08:46:06 -0600231 def add_remote_option(self, *args, **kwargs):
232 """For arguments that are passed-through to remote trybot."""
233 return self.add_option(*args, remote_pass_through=True, **kwargs)
Brian Harringb6cf9142012-09-01 20:43:17 -0700234
235
Don Garrett86881cb2017-02-15 15:41:55 -0800236def CreateParser():
Alex Klein1699fab2022-09-08 08:46:06 -0600237 """Expose _CreateParser publicly."""
238 # Name _CreateParser is needed for commandline library.
239 return _CreateParser()
Don Garrett86881cb2017-02-15 15:41:55 -0800240
241
Brian Harring3fec5a82012-03-01 05:57:03 -0800242def _CreateParser():
Alex Klein1699fab2022-09-08 08:46:06 -0600243 """Generate and return the parser with all the options."""
244 # Parse options
245 usage = "usage: %prog [options] buildbot_config [buildbot_config ...]"
246 parser = CustomParser(usage=usage, caching=FindCacheDir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800247
Alex Klein1699fab2022-09-08 08:46:06 -0600248 # Main options
249 parser.add_remote_option(
250 "-b",
251 "--branch",
252 help="The manifest branch to test. The branch to "
253 "check the buildroot out to.",
254 )
255 parser.add_option(
256 "-r",
257 "--buildroot",
258 type="path",
259 dest="buildroot",
260 help="Root directory where source is checked out to, and "
261 "where the build occurs. For external build configs, "
262 "defaults to 'trybot' directory at top level of your "
263 "repo-managed checkout.",
264 )
265 parser.add_option(
266 "--workspace",
267 type="path",
268 api=constants.REEXEC_API_WORKSPACE,
269 help="Root directory for a secondary checkout .",
270 )
271 parser.add_option(
272 "--bootstrap-dir",
273 type="path",
274 help="Bootstrapping cbuildbot may involve checking out "
275 "multiple copies of chromite. All these checkouts "
276 "will be contained in the directory specified here. "
277 "Default:%s" % osutils.GetGlobalTempDir(),
278 )
279 parser.add_remote_option(
280 "--android_rev",
281 type="choice",
282 choices=constants.VALID_ANDROID_REVISIONS,
283 help=(
284 "Revision of Android to use, of type [%s]"
285 % "|".join(constants.VALID_ANDROID_REVISIONS)
286 ),
287 )
288 parser.add_remote_option(
289 "--chrome_rev",
290 type="choice",
291 choices=constants.VALID_CHROME_REVISIONS,
292 help=(
293 "Revision of Chrome to use, of type [%s]"
294 % "|".join(constants.VALID_CHROME_REVISIONS)
295 ),
296 )
297 parser.add_remote_option(
298 "--profile", help="Name of profile to sub-specify board variant."
299 )
300 # TODO(crbug.com/279618): Running GOMA is under development. Following
301 # flags are added for development purpose due to repository dependency,
302 # but not officially supported yet.
303 parser.add_option(
304 "--goma_dir",
305 type="path",
306 api=constants.REEXEC_API_GOMA,
307 help="Specify a directory containing goma. When this is "
308 "set, GOMA is used to build Chrome.",
309 )
310 parser.add_option(
311 "--chromeos_goma_dir",
312 type="path",
313 api=constants.REEXEC_API_CHROMEOS_GOMA_DIR,
314 help="Specify a directory containing goma for " "build package.",
315 )
Alex Klein1699fab2022-09-08 08:46:06 -0600316 group = CustomGroup(parser, "Deprecated Options")
Don Garrett211df8c2017-09-06 13:33:02 -0700317
Alex Klein1699fab2022-09-08 08:46:06 -0600318 parser.add_option(
319 "--local",
320 action="store_true",
321 default=False,
322 help="Deprecated. See cros tryjob.",
323 )
324 parser.add_option(
325 "--remote",
326 action="store_true",
327 default=False,
328 help="Deprecated. See cros tryjob.",
329 )
Don Garrett211df8c2017-09-06 13:33:02 -0700330
Alex Klein1699fab2022-09-08 08:46:06 -0600331 #
332 # Patch selection options.
333 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400334
Alex Klein1699fab2022-09-08 08:46:06 -0600335 group = CustomGroup(parser, "Patch Options")
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400336
Alex Klein1699fab2022-09-08 08:46:06 -0600337 group.add_remote_option(
338 "-g",
339 "--gerrit-patches",
340 action="split_extend",
341 type="string",
342 default=[],
343 metavar="'Id1 *int_Id2...IdN'",
344 help="Space-separated list of short-form Gerrit "
345 "Change-Id's or change numbers to patch. "
346 "Please prepend '*' to internal Change-Id's",
347 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400348
Alex Klein1699fab2022-09-08 08:46:06 -0600349 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400350
Alex Klein1699fab2022-09-08 08:46:06 -0600351 #
352 # Remote trybot options.
353 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400354
Alex Klein1699fab2022-09-08 08:46:06 -0600355 group = CustomGroup(parser, "Options used to configure tryjob behavior.")
356 group.add_remote_option(
357 "--hwtest",
358 action="store_true",
359 default=False,
360 help="Run the HWTest stage (tests on real hardware)",
361 )
362 group.add_option(
363 "--hwtest_dut_dimensions",
364 type="string",
365 action="split_extend",
366 default=None,
367 help="Space-separated list of key:val Swarming bot "
368 "dimensions to run each builders SkylabHWTest "
369 "stages against (this overrides the configured "
370 "DUT dimensions for each test). Requires at least "
371 '"label-board", "label-model", and "label-pool".',
372 )
373 group.add_remote_option(
374 "--channel",
375 action="split_extend",
376 dest="channels",
377 default=[],
378 help="Specify a channel for a payloads trybot. Can "
379 "be specified multiple times. No valid for "
380 "non-payloads configs.",
381 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400382
Alex Klein1699fab2022-09-08 08:46:06 -0600383 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400384
Alex Klein1699fab2022-09-08 08:46:06 -0600385 #
386 # Advanced options.
387 #
Ryan Cuif4f84be2012-07-09 18:50:41 -0700388
Alex Klein1699fab2022-09-08 08:46:06 -0600389 group = CustomGroup(
390 parser,
391 "Advanced Options",
392 "Caution: use these options at your own risk.",
393 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800394
Alex Klein1699fab2022-09-08 08:46:06 -0600395 group.add_remote_option(
396 "--bootstrap-args",
397 action="append",
398 default=[],
399 help="Args passed directly to the bootstrap re-exec "
400 "to skip verification by the bootstrap code",
401 )
402 group.add_remote_option(
403 "--buildbot",
404 action="store_true",
405 dest="buildbot",
406 default=False,
407 help="This is running on a buildbot. "
408 "This can be used to make a build operate "
409 "like an official builder, e.g. generate "
410 "new version numbers and archive official "
411 "artifacts and such. This should only be "
412 "used if you are confident in what you are "
413 "doing, as it will make automated commits.",
414 )
415 parser.add_remote_option(
416 "--repo-cache",
417 type="path",
418 dest="_repo_cache",
419 help="Present for backwards compatibility, ignored.",
420 )
421 group.add_remote_option(
422 "--no-buildbot-tags",
423 action="store_false",
424 dest="enable_buildbot_tags",
425 default=True,
426 help="Suppress buildbot specific tags from log "
427 "output. This is used to hide recursive "
428 "cbuilbot runs on the waterfall.",
429 )
430 group.add_remote_option(
431 "--buildnumber", type="int", default=0, help="build number"
432 )
433 group.add_option(
434 "--chrome_root",
435 action="callback",
436 type="path",
437 callback=_CheckChromeRootOption,
438 help="Local checkout of Chrome to use.",
439 )
440 group.add_remote_option(
441 "--chrome_version",
442 action="callback",
443 type="string",
444 dest="chrome_version",
445 callback=_CheckChromeVersionOption,
446 help="Used with SPEC logic to force a particular "
447 "git revision of chrome rather than the "
448 "latest.",
449 )
450 group.add_remote_option(
451 "--clobber",
452 action="store_true",
453 default=False,
454 help="Clears an old checkout before syncing",
455 )
456 group.add_remote_option(
457 "--latest-toolchain",
458 action="store_true",
459 default=False,
460 help="Use the latest toolchain.",
461 )
462 parser.add_option(
463 "--log_dir",
464 dest="log_dir",
465 type="path",
466 help="Directory where logs are stored.",
467 )
468 group.add_remote_option(
469 "--maxarchives",
470 type="int",
471 dest="max_archive_builds",
472 default=3,
473 help="Change the local saved build count limit.",
474 )
475 parser.add_remote_option(
476 "--manifest-repo-url", help="Overrides the default manifest repo url."
477 )
478 group.add_remote_option(
479 "--compilecheck",
480 action="store_true",
481 default=False,
482 help="Only verify compilation and unit tests.",
483 )
484 group.add_remote_option(
485 "--noarchive",
486 action="store_false",
487 dest="archive",
488 default=True,
489 help="Don't run archive stage.",
490 )
491 group.add_remote_option(
492 "--nobootstrap",
493 action="store_false",
494 dest="bootstrap",
495 default=True,
496 help="Don't checkout and run from a standalone " "chromite repo.",
497 )
498 group.add_remote_option(
499 "--nobuild",
500 action="store_false",
501 dest="build",
502 default=True,
503 help="Don't actually build (for cbuildbot dev)",
504 )
505 group.add_remote_option(
506 "--noclean",
507 action="store_false",
508 dest="clean",
509 default=True,
510 help="Don't clean the buildroot",
511 )
512 group.add_remote_option(
513 "--nocgroups",
514 action="store_false",
515 dest="cgroups",
516 default=True,
517 help="Disable cbuildbots usage of cgroups.",
518 )
519 group.add_remote_option(
520 "--nochromesdk",
521 action="store_false",
522 dest="chrome_sdk",
523 default=True,
524 help="Don't run the ChromeSDK stage which builds "
525 "Chrome outside of the chroot.",
526 )
527 group.add_remote_option(
528 "--noprebuilts",
529 action="store_false",
530 dest="prebuilts",
531 default=True,
532 help="Don't upload prebuilts.",
533 )
534 group.add_remote_option(
535 "--nopatch",
536 action="store_false",
537 dest="postsync_patch",
538 default=True,
539 help="Don't run PatchChanges stage. This does not "
540 "disable patching in of chromite patches "
541 "during BootstrapStage.",
542 )
543 group.add_remote_option(
544 "--nopaygen",
545 action="store_false",
546 dest="paygen",
547 default=True,
548 help="Don't generate payloads.",
549 )
550 group.add_remote_option(
551 "--noreexec",
552 action="store_false",
553 dest="postsync_reexec",
554 default=True,
555 help="Don't reexec into the buildroot after syncing.",
556 )
557 group.add_remote_option(
558 "--nosdk",
559 action="store_true",
560 default=False,
561 help="Re-create the SDK from scratch.",
562 )
563 group.add_remote_option(
564 "--nosync",
565 action="store_false",
566 dest="sync",
567 default=True,
568 help="Don't sync before building.",
569 )
570 group.add_remote_option(
571 "--notests",
572 action="store_false",
573 dest="tests",
574 default=True,
575 help="Override values from buildconfig, run no "
576 "tests, and build no autotest and artifacts.",
577 )
578 group.add_remote_option(
579 "--novmtests",
580 action="store_false",
581 dest="vmtests",
582 default=True,
583 help="Override values from buildconfig, run no " "vmtests.",
584 )
585 group.add_remote_option(
586 "--noimagetests",
587 action="store_false",
588 dest="image_test",
589 default=True,
590 help="Override values from buildconfig and run no " "image tests.",
591 )
592 group.add_remote_option(
593 "--nouprev",
594 action="store_false",
595 dest="uprev",
596 default=True,
597 help="Override values from buildconfig and never " "uprev.",
598 )
599 group.add_option(
600 "--reference-repo",
601 help="Reuse git data stored in an existing repo "
602 "checkout. This can drastically reduce the network "
603 "time spent setting up the trybot checkout. By "
604 "default, if this option isn't given but cbuildbot "
605 "is invoked from a repo checkout, cbuildbot will "
606 "use the repo root.",
607 )
608 group.add_option(
609 "--resume",
610 action="store_true",
611 default=False,
612 help="Skip stages already successfully completed.",
613 )
614 group.add_remote_option(
615 "--timeout",
616 type="int",
617 default=0,
618 help="Specify the maximum amount of time this job "
619 "can run for, at which point the build will be "
620 "aborted. If set to zero, then there is no "
621 "timeout.",
622 )
623 group.add_remote_option(
624 "--version",
625 dest="force_version",
626 help="Used with manifest logic. Forces use of this "
627 "version rather than create or get latest. "
628 "Examples: 4815.0.0-rc1, 4815.1.2",
629 )
630 group.add_remote_option(
631 "--git-cache-dir",
632 type="path",
633 api=constants.REEXEC_API_GIT_CACHE_DIR,
634 help="Specify the cache directory to store the "
635 "project caches populated by the git-cache "
636 "tool. Bootstrap the projects based on the git "
637 "cache files instead of fetching them directly "
638 "from the GoB servers.",
639 )
640 group.add_remote_option(
641 "--chrome-preload-dir",
642 type="path",
643 api=constants.REEXEC_API_CHROME_PRELOAD_DIR,
644 help="Specify a preloaded chrome source cache "
645 "directory populated by the git-cache tool. "
646 "Bootstrap chrome based on the cached files "
647 "instead of fetching them directly from the GoB "
648 "servers. When both this argument and "
649 "--git-cache-dir are provided this value will "
650 "be preferred for the chrome source cache.",
651 )
652 group.add_remote_option(
653 "--source_cache",
654 action="store_true",
655 default=False,
656 help="Whether to utilize cache snapshot mounts.",
657 )
658 group.add_remote_option(
659 "--debug-cidb",
660 action="store_true",
661 default=False,
662 help="Force Debug CIDB to be used.",
663 )
664 # cbuildbot ChromeOS Findit options
665 group.add_remote_option(
666 "--cbb_build_packages",
667 action="split_extend",
668 dest="cbb_build_packages",
669 default=[],
670 help="Specify an explicit list of packages to build "
671 "for integration with Findit.",
672 )
673 group.add_remote_option(
674 "--cbb_snapshot_revision",
675 type="string",
676 dest="cbb_snapshot_revision",
677 default=None,
678 help="Snapshot manifest revision to sync to " "for building.",
679 )
680 group.add_remote_option(
681 "--no-publish-prebuilt-confs",
682 dest="publish",
683 action="store_false",
684 default=True,
685 help="Don't publish git commits to prebuilt.conf or sdk_version.conf",
686 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400687
Alex Klein1699fab2022-09-08 08:46:06 -0600688 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400689
Alex Klein1699fab2022-09-08 08:46:06 -0600690 #
691 # Internal options.
692 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400693
Alex Klein1699fab2022-09-08 08:46:06 -0600694 group = CustomGroup(
695 parser,
696 "Internal Chromium OS Build Team Options",
697 "Caution: these are for meant for the Chromium OS build team only",
698 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400699
Alex Klein1699fab2022-09-08 08:46:06 -0600700 group.add_remote_option(
701 "--archive-base",
702 type="gs_path",
703 help="Base GS URL (gs://<bucket_name>/<path>) to "
704 "upload archive artifacts to",
705 )
706 group.add_remote_option(
707 "--cq-gerrit-query",
708 dest="cq_gerrit_override",
709 help="If given, this gerrit query will be used to find what patches to "
710 "test, rather than the normal 'CommitQueue>=1 AND Verified=1 AND "
711 "CodeReview=2' query it defaults to. Use with care- note "
712 "additionally this setting only has an effect if the buildbot "
713 "target is a cq target, and we're in buildbot mode.",
714 )
715 group.add_option(
716 "--pass-through",
717 action="append",
718 type="string",
719 dest="pass_through_args",
720 default=[],
721 )
722 group.add_option(
723 "--reexec-api-version",
724 action="store_true",
725 dest="output_api_version",
726 default=False,
727 help="Used for handling forwards/backwards compatibility "
728 "with --resume and --bootstrap",
729 )
730 group.add_option(
731 "--remote-trybot",
732 action="store_true",
733 default=False,
734 help="Indicates this is running on a remote trybot machine",
735 )
736 group.add_option(
737 "--buildbucket-id",
738 api=constants.REEXEC_API_GOMA, # Approximate.
739 help="The unique ID in buildbucket of current build "
740 "generated by buildbucket.",
741 )
742 group.add_remote_option(
743 "--remote-patches",
744 action="split_extend",
745 default=[],
746 help="Patches uploaded by the trybot client when "
747 "run using the -p option",
748 )
749 # Note the default here needs to be hardcoded to 3; that is the last version
750 # that lacked this functionality.
751 group.add_option(
752 "--remote-version",
753 type="int",
754 default=3,
755 help="Deprecated and ignored.",
756 )
757 group.add_option("--sourceroot", type="path", default=constants.SOURCE_ROOT)
758 group.add_remote_option(
759 "--test-bootstrap",
760 action="store_true",
761 default=False,
762 help="Causes cbuildbot to bootstrap itself twice, "
763 "in the sequence A->B->C: A(unpatched) patches "
764 "and bootstraps B; B patches and bootstraps C",
765 )
766 group.add_remote_option(
767 "--validation_pool",
768 help="Path to a pickled validation pool. Intended "
769 "for use only with the commit queue.",
770 )
771 group.add_remote_option(
772 "--metadata_dump",
773 help="Path to a json dumped metadata file. This "
774 "will be used as the initial metadata.",
775 )
776 group.add_remote_option(
777 "--master-build-id",
778 type="int",
779 api=constants.REEXEC_API_MASTER_BUILD_ID,
780 help="cidb build id of the master build to this " "slave build.",
781 )
782 group.add_remote_option(
783 "--master-buildbucket-id",
784 api=constants.REEXEC_API_MASTER_BUILDBUCKET_ID,
785 help="buildbucket id of the master build to this " "slave build.",
786 )
787 # TODO(nxia): crbug.com/778838
788 # cbuildbot doesn't use pickle files anymore, remove this.
789 group.add_remote_option(
790 "--mock-slave-status",
791 metavar="MOCK_SLAVE_STATUS_PICKLE_FILE",
792 help="Override the result of the _FetchSlaveStatuses "
793 "method of MasterSlaveSyncCompletionStage, by "
794 "specifying a file with a pickle of the result "
795 "to be returned.",
796 )
797 group.add_option(
798 "--previous-build-state",
799 type="string",
800 default="",
801 api=constants.REEXEC_API_PREVIOUS_BUILD_STATE,
802 help="A base64-encoded BuildSummary object describing the "
803 "previous build run on the same build machine.",
804 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400805
Alex Klein1699fab2022-09-08 08:46:06 -0600806 parser.add_argument_group(group)
Ryan Cuif4f84be2012-07-09 18:50:41 -0700807
Alex Klein1699fab2022-09-08 08:46:06 -0600808 #
809 # Debug options
810 #
811 # Temporary hack; in place till --dry-run replaces --debug.
812 # pylint: disable=protected-access
813 group = parser.debug_group
814 debug = [x for x in group.option_list if x._long_opts == ["--debug"]][0]
815 debug.help += " Currently functions as --dry-run in addition."
816 debug.pass_through = True
817 group.add_option(
818 "--notee",
819 action="store_false",
820 dest="tee",
821 default=True,
822 help="Disable logging and internal tee process. Primarily "
823 "used for debugging cbuildbot itself.",
824 )
825 return parser
Brian Harring3fec5a82012-03-01 05:57:03 -0800826
827
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400828def _FinishParsing(options):
Alex Klein1699fab2022-09-08 08:46:06 -0600829 """Perform some parsing tasks that need to take place after optparse.
Ryan Cui85867972012-02-23 18:21:49 -0800830
Alex Klein1699fab2022-09-08 08:46:06 -0600831 This function needs to be easily testable! Keep it free of
832 environment-dependent code. Put more detailed usage validation in
833 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800834
Alex Klein1699fab2022-09-08 08:46:06 -0600835 Args:
836 options: The options object returned by optparse
837 """
838 # Populate options.pass_through_args.
839 accepted, _ = commandline.FilteringParser.FilterArgs(
840 options.parsed_args, lambda x: x.opt_inst.pass_through
841 )
842 options.pass_through_args.extend(accepted)
Brian Harring07039b52012-05-13 17:56:47 -0700843
Alex Klein1699fab2022-09-08 08:46:06 -0600844 if options.local or options.remote:
845 cros_build_lib.Die("Deprecated usage. Please use cros tryjob instead.")
Don Garrettcc0ee522017-09-13 14:28:42 -0700846
Alex Klein1699fab2022-09-08 08:46:06 -0600847 if not options.buildroot:
848 cros_build_lib.Die("A buildroot is required to build.")
Don Garrett211df8c2017-09-06 13:33:02 -0700849
Alex Klein1699fab2022-09-08 08:46:06 -0600850 if options.chrome_root:
851 if options.chrome_rev != constants.CHROME_REV_LOCAL:
852 cros_build_lib.Die(
853 "Chrome rev must be %s if chrome_root is set."
854 % constants.CHROME_REV_LOCAL
855 )
856 elif options.chrome_rev == constants.CHROME_REV_LOCAL:
857 cros_build_lib.Die(
858 "Chrome root must be set if chrome_rev is %s."
859 % constants.CHROME_REV_LOCAL
860 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800861
Alex Klein1699fab2022-09-08 08:46:06 -0600862 if options.chrome_version:
863 if options.chrome_rev != constants.CHROME_REV_SPEC:
864 cros_build_lib.Die(
865 "Chrome rev must be %s if chrome_version is set."
866 % constants.CHROME_REV_SPEC
867 )
868 elif options.chrome_rev == constants.CHROME_REV_SPEC:
869 cros_build_lib.Die(
870 "Chrome rev must not be %s if chrome_version is not set."
871 % constants.CHROME_REV_SPEC
872 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800873
Alex Klein1699fab2022-09-08 08:46:06 -0600874 patches = bool(options.gerrit_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700875
Alex Klein1699fab2022-09-08 08:46:06 -0600876 # When running in release mode, make sure we are running with checked-in code.
877 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
878 # a release image with checked-in code for CrOS packages.
879 if options.buildbot and patches and not options.debug:
880 cros_build_lib.Die(
881 "Cannot provide patches when running with --buildbot!"
882 )
David James5734ea32012-08-15 20:23:49 -0700883
Alex Klein1699fab2022-09-08 08:46:06 -0600884 if options.buildbot and options.remote_trybot:
885 cros_build_lib.Die(
886 "--buildbot and --remote-trybot cannot be used together."
887 )
Ryan Cuiba41ad32012-03-08 17:15:29 -0800888
Alex Klein1699fab2022-09-08 08:46:06 -0600889 # Record whether --debug was set explicitly vs. it was inferred.
890 options.debug_forced = options.debug
891 # We force --debug to be set for builds that are not 'official'.
892 options.debug = options.debug or not options.buildbot
Brian Harring3fec5a82012-03-01 05:57:03 -0800893
Alex Klein1699fab2022-09-08 08:46:06 -0600894 options.hwtest_dut_override = ParseHWTestDUTDims(
895 options.hwtest_dut_dimensions
896 )
897
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600898
899def ParseHWTestDUTDims(dims):
Alex Klein1699fab2022-09-08 08:46:06 -0600900 """Parse HWTest DUT dimensions into a valid HWTestDUTOverride object.
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600901
Alex Klein1699fab2022-09-08 08:46:06 -0600902 Raises an error if any of board, model, or pool is missing.
903 """
904 if not dims:
905 return None
906 board = model = pool = None
907 extra_dims = []
908 for dim in dims:
909 if dim.startswith(BOARD_DIM_LABEL):
910 # Remove one extra character to account for the ":" or "=" symbol
911 # separating the label from the dimension itself.
912 board = dim[len(BOARD_DIM_LABEL) + 1 :]
913 elif dim.startswith(MODEL_DIM_LABEL):
914 model = dim[len(MODEL_DIM_LABEL) + 1 :]
915 elif dim.startswith(POOL_DIM_LABEL):
916 pool = dim[len(POOL_DIM_LABEL) + 1 :]
917 else:
918 extra_dims.append(dim)
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600919
Alex Klein1699fab2022-09-08 08:46:06 -0600920 if not (board and model and pool):
921 cros_build_lib.Die(
922 "HWTest DUT dimensions must include board, model, and "
923 "pool (given %s)." % dims
924 )
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600925
Alex Klein1699fab2022-09-08 08:46:06 -0600926 return test_stages.HWTestDUTOverride(board, model, pool, extra_dims)
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600927
Brian Harring3fec5a82012-03-01 05:57:03 -0800928
Mike Frysinger27e21b72018-07-12 14:20:21 -0400929# pylint: disable=unused-argument
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400930def _PostParseCheck(parser, options, site_config):
Alex Klein1699fab2022-09-08 08:46:06 -0600931 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800932
Alex Klein1699fab2022-09-08 08:46:06 -0600933 Args:
934 parser: Option parser that was used to parse arguments.
935 options: The options returned by optparse.
936 site_config: config_lib.SiteConfig containing all config info.
937 """
Don Garrett0a873e02015-06-30 17:55:10 -0700938
Alex Klein1699fab2022-09-08 08:46:06 -0600939 if not options.branch:
940 options.branch = git.GetChromiteTrackingBranch()
Ryan Cuie1e4e662012-05-21 16:39:46 -0700941
Alex Klein1699fab2022-09-08 08:46:06 -0600942 # Because the default cache dir depends on other options, FindCacheDir
943 # always returns None, and we setup the default here.
944 if options.cache_dir is None:
945 # Note, options.sourceroot is set regardless of the path
946 # actually existing.
947 options.cache_dir = os.path.join(options.buildroot, ".cache")
948 options.cache_dir = os.path.abspath(options.cache_dir)
949 parser.ConfigureCacheDir(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700950
Alex Klein1699fab2022-09-08 08:46:06 -0600951 osutils.SafeMakedirsNonRoot(options.cache_dir)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700952
Alex Klein1699fab2022-09-08 08:46:06 -0600953 # Ensure that all args are legitimate config targets.
954 if options.build_config_name not in site_config:
955 cros_build_lib.Die(
956 'Unknown build config: "%s"' % options.build_config_name
957 )
Don Garrett4bb21682014-03-03 16:16:23 -0800958
Alex Klein1699fab2022-09-08 08:46:06 -0600959 build_config = site_config[options.build_config_name]
960 is_payloads_build = build_config.build_type == constants.PAYLOADS_TYPE
Don Garrett4af20982015-05-29 19:02:23 -0700961
Alex Klein1699fab2022-09-08 08:46:06 -0600962 if options.channels and not is_payloads_build:
963 cros_build_lib.Die(
964 "--channel must only be used with a payload config,"
965 " not target (%s)." % options.build_config_name
966 )
Don Garrett5af1d262014-05-16 15:49:37 -0700967
Alex Klein1699fab2022-09-08 08:46:06 -0600968 if not options.channels and is_payloads_build:
969 cros_build_lib.Die(
970 "payload configs (%s) require --channel to do anything"
971 " useful." % options.build_config_name
972 )
Matt Tennant763497d2014-01-17 16:45:54 -0800973
Alex Klein1699fab2022-09-08 08:46:06 -0600974 # If the build config explicitly forces the debug flag, set the debug flag
975 # as if it was set from the command line.
976 if build_config.debug:
977 options.debug = True
Don Garrett370839f2017-10-19 18:32:34 -0700978
Alex Klein1699fab2022-09-08 08:46:06 -0600979 if not (config_lib.isTryjobConfig(build_config) or options.buildbot):
980 cros_build_lib.Die(
981 "Refusing to run non-tryjob config as a tryjob.\n"
982 'Please "repo sync && cros tryjob --list %s" for alternatives.\n'
983 "See go/cros-explicit-tryjob-build-configs-psa.",
984 build_config.name,
985 )
Don Garrett02d2f582017-11-08 14:01:24 -0800986
Alex Klein1699fab2022-09-08 08:46:06 -0600987 # The --version option is not compatible with an external target unless the
988 # --buildbot option is specified. More correctly, only "paladin versions"
989 # will work with external targets, and those are only used with --buildbot.
990 # If --buildbot is specified, then user should know what they are doing and
991 # only specify a version that will work. See crbug.com/311648.
992 if options.force_version and not (
993 options.buildbot or build_config.internal
994 ):
995 cros_build_lib.Die(
996 "Cannot specify --version without --buildbot for an"
997 " external target (%s)." % options.build_config_name
998 )
Matt Tennant763497d2014-01-17 16:45:54 -0800999
Ryan Cui85867972012-02-23 18:21:49 -08001000
Don Garrett597ddff2017-02-17 18:29:37 -08001001def ParseCommandLine(parser, argv):
Alex Klein1699fab2022-09-08 08:46:06 -06001002 """Completely parse the commandline arguments"""
1003 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -07001004
Alex Klein1699fab2022-09-08 08:46:06 -06001005 # Handle the request for the reexec command line API version number.
1006 if options.output_api_version:
1007 print(constants.REEXEC_API_VERSION)
1008 sys.exit(0)
Brian Harring37e559b2012-05-22 20:47:32 -07001009
Alex Klein1699fab2022-09-08 08:46:06 -06001010 # Record the configs targeted. Strip out null arguments.
1011 build_config_names = [x for x in args if x]
1012 if len(build_config_names) != 1:
1013 cros_build_lib.Die(
1014 "Expected exactly one build config. Got: %r", build_config_names
1015 )
1016 options.build_config_name = build_config_names[-1]
Don Garrettf0761152017-10-19 19:38:27 -07001017
Alex Klein1699fab2022-09-08 08:46:06 -06001018 _FinishParsing(options)
1019 return options
Ryan Cui85867972012-02-23 18:21:49 -08001020
1021
Alex Klein1699fab2022-09-08 08:46:06 -06001022_ENVIRONMENT_PROD = "prod"
1023_ENVIRONMENT_DEBUG = "debug"
1024_ENVIRONMENT_STANDALONE = "standalone"
Aviv Keshet420de512015-05-18 14:28:48 -07001025
1026
1027def _GetRunEnvironment(options, build_config):
Alex Klein1699fab2022-09-08 08:46:06 -06001028 """Determine whether this is a prod/debug/standalone run."""
1029 if options.debug_cidb:
1030 return _ENVIRONMENT_DEBUG
Don Garretta90f0142018-02-28 14:25:19 -08001031
Alex Klein1699fab2022-09-08 08:46:06 -06001032 # One of these arguments should always be set if running on a real builder.
1033 # If we aren't on a real builder, we are standalone.
1034 if not options.buildbot and not options.remote_trybot:
1035 return _ENVIRONMENT_STANDALONE
Aviv Keshet420de512015-05-18 14:28:48 -07001036
Alex Klein1699fab2022-09-08 08:46:06 -06001037 if build_config["debug_cidb"]:
1038 return _ENVIRONMENT_DEBUG
Aviv Keshet420de512015-05-18 14:28:48 -07001039
Alex Klein1699fab2022-09-08 08:46:06 -06001040 return _ENVIRONMENT_PROD
Aviv Keshet420de512015-05-18 14:28:48 -07001041
1042
Gabe Blackde694a32015-02-19 15:11:11 -08001043def _SetupConnections(options, build_config):
George Engelbrecht7e07c702022-09-19 17:03:55 -06001044 """Set up CIDB connections using the appropriate Setup call.
Aviv Keshet2982af52014-08-13 16:07:57 -07001045
Alex Klein1699fab2022-09-08 08:46:06 -06001046 Args:
1047 options: Command line options structure.
1048 build_config: Config object for this build.
1049 """
George Engelbrecht7e07c702022-09-19 17:03:55 -06001050 # Outline:
1051 # 1) Based on options and build_config, decide whether we are a production
1052 # run, debug run, or standalone run.
1053 # 2) Set up cidb instance accordingly.
1054 # 3) Update topology info from cidb, so that any other service set up can use
1055 # topology.
1056 # 4) Set up any other services.
1057 run_type = _GetRunEnvironment(options, build_config)
1058
1059 if run_type == _ENVIRONMENT_PROD:
1060 cidb.CIDBConnectionFactory.SetupProdCidb()
1061 context = ts_mon_config.SetupTsMonGlobalState(
1062 "cbuildbot", indirect=True
1063 )
1064 elif run_type == _ENVIRONMENT_DEBUG:
1065 cidb.CIDBConnectionFactory.SetupDebugCidb()
1066 context = ts_mon_config.TrivialContextManager()
1067 else:
1068 cidb.CIDBConnectionFactory.SetupNoCidb()
1069 context = ts_mon_config.TrivialContextManager()
Aviv Keshet62d1a0e2014-08-22 21:16:13 -07001070
Alex Klein1699fab2022-09-08 08:46:06 -06001071 topology.FetchTopology()
1072 return context
Paul Hobbsd5a0f812016-07-26 16:10:31 -07001073
Aviv Keshet2982af52014-08-13 16:07:57 -07001074
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001075class _MockMethodWithReturnValue(object):
Alex Klein1699fab2022-09-08 08:46:06 -06001076 """A method mocker which just returns the specific value."""
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001077
Alex Klein1699fab2022-09-08 08:46:06 -06001078 def __init__(self, return_value):
1079 self.return_value = return_value
1080
1081 def __call__(self, *args, **kwargs):
1082 return self.return_value
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001083
1084
1085class _ObjectMethodPatcher(object):
Alex Klein1699fab2022-09-08 08:46:06 -06001086 """A simplified mock.object.patch.
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001087
Alex Klein1699fab2022-09-08 08:46:06 -06001088 It is a context manager that patches an object's method with specified
1089 return value.
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001090 """
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001091
Alex Klein1699fab2022-09-08 08:46:06 -06001092 def __init__(self, target, attr, return_value=None):
1093 """Constructor.
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001094
Alex Klein1699fab2022-09-08 08:46:06 -06001095 Args:
1096 target: object to patch.
1097 attr: method name of the object to patch.
1098 return_value: the return value when calling target.attr
1099 """
1100 self.target = target
1101 self.attr = attr
1102 self.return_value = return_value
1103 self.original_attr = None
1104 self.new_attr = _MockMethodWithReturnValue(self.return_value)
1105
1106 def __enter__(self):
1107 self.original_attr = self.target.__dict__[self.attr]
1108 setattr(self.target, self.attr, self.new_attr)
1109
1110 def __exit__(self, *args):
1111 if self.target and self.original_attr:
1112 setattr(self.target, self.attr, self.original_attr)
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001113
1114
Matt Tennant759e2352013-09-27 15:14:44 -07001115# TODO(build): This function is too damn long.
Ryan Cui85867972012-02-23 18:21:49 -08001116def main(argv):
Alex Klein1699fab2022-09-08 08:46:06 -06001117 # We get false positives with the options object.
1118 # pylint: disable=attribute-defined-outside-init
Mike Frysinger80bba8a2017-08-18 15:28:36 -04001119
Alex Klein1699fab2022-09-08 08:46:06 -06001120 # Turn on strict sudo checks.
1121 cros_build_lib.STRICT_SUDO = True
David James59a0a2b2013-03-22 14:04:44 -07001122
Alex Klein1699fab2022-09-08 08:46:06 -06001123 # Set umask to 022 so files created by buildbot are readable.
1124 os.umask(0o22)
Ryan Cui85867972012-02-23 18:21:49 -08001125
Alex Klein1699fab2022-09-08 08:46:06 -06001126 parser = _CreateParser()
1127 options = ParseCommandLine(parser, argv)
Don Garrett0a873e02015-06-30 17:55:10 -07001128
Alex Klein1699fab2022-09-08 08:46:06 -06001129 # Fetch our site_config now, because we need it to do anything else.
1130 site_config = config_lib.GetConfig()
Don Garrettb85658c2015-06-30 19:07:22 -07001131
Alex Klein1699fab2022-09-08 08:46:06 -06001132 _PostParseCheck(parser, options, site_config)
Brian Harring3fec5a82012-03-01 05:57:03 -08001133
Alex Klein1699fab2022-09-08 08:46:06 -06001134 cros_build_lib.AssertOutsideChroot()
Zdenek Behan98ec2fb2012-08-31 17:12:18 +02001135
Alex Klein1699fab2022-09-08 08:46:06 -06001136 if options.enable_buildbot_tags:
1137 cbuildbot_alerts.EnableBuildbotMarkers()
Matt Tennant759e2352013-09-27 15:14:44 -07001138
Alex Klein1699fab2022-09-08 08:46:06 -06001139 if (
1140 options.buildbot
1141 and not options.debug
1142 and not cros_build_lib.HostIsCIBuilder()
1143 ):
1144 # --buildbot can only be used on a real builder, unless it's debug.
1145 cros_build_lib.Die("This host is not a supported build machine.")
Ningning Xiac691e432016-08-11 14:52:59 -07001146
Alex Klein1699fab2022-09-08 08:46:06 -06001147 # Only one config arg is allowed in this mode, which was confirmed earlier.
1148 build_config = site_config[options.build_config_name]
Brian Harring3fec5a82012-03-01 05:57:03 -08001149
Alex Klein1699fab2022-09-08 08:46:06 -06001150 # TODO: Re-enable this block when reference_repo support handles this
1151 # properly. (see chromium:330775)
1152 # if options.reference_repo is None:
1153 # repo_path = os.path.join(options.sourceroot, '.repo')
1154 # # If we're being run from a repo checkout, reuse the repo's git pool to
1155 # # cut down on sync time.
1156 # if os.path.exists(repo_path):
1157 # options.reference_repo = options.sourceroot
Don Garrettbbd7b552014-05-16 13:15:21 -07001158
Alex Klein1699fab2022-09-08 08:46:06 -06001159 if options.reference_repo:
1160 if not os.path.exists(options.reference_repo):
1161 parser.error(
1162 "Reference path %s does not exist" % (options.reference_repo,)
1163 )
1164 elif not os.path.exists(os.path.join(options.reference_repo, ".repo")):
1165 parser.error(
1166 "Reference path %s does not look to be the base of a "
1167 "repo checkout; no .repo exists in the root."
1168 % (options.reference_repo,)
1169 )
David Jamesdac7a912013-11-18 11:14:44 -08001170
Alex Klein1699fab2022-09-08 08:46:06 -06001171 if (options.buildbot or options.remote_trybot) and not options.resume:
1172 missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
1173 if missing:
1174 parser.error(
1175 "Option --buildbot/--remote-trybot requires the following "
1176 "binaries which couldn't be found in $PATH: %s"
1177 % (", ".join(missing))
1178 )
Brian Harring351ce442012-03-09 16:38:14 -08001179
Alex Klein1699fab2022-09-08 08:46:06 -06001180 if options.reference_repo:
1181 options.reference_repo = os.path.abspath(options.reference_repo)
David Jamesdac7a912013-11-18 11:14:44 -08001182
Alex Klein1699fab2022-09-08 08:46:06 -06001183 # Sanity check of buildroot- specifically that it's not pointing into the
1184 # midst of an existing repo since git-repo doesn't support nesting.
1185 if not repository.IsARepoRoot(options.buildroot) and git.FindRepoDir(
1186 options.buildroot
1187 ):
1188 cros_build_lib.Die(
1189 "Configured buildroot %s is a subdir of an existing repo checkout."
1190 % options.buildroot
1191 )
Brian Harring3fec5a82012-03-01 05:57:03 -08001192
Alex Klein1699fab2022-09-08 08:46:06 -06001193 if not options.log_dir:
1194 options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
Chris Sosab5ea3b42012-10-25 15:25:20 -07001195
Alex Klein1699fab2022-09-08 08:46:06 -06001196 log_file = None
1197 if options.tee:
1198 log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
1199 osutils.SafeMakedirs(options.log_dir)
1200 _BackupPreviousLog(log_file)
Brian Harringd166aaf2012-05-14 18:31:53 -07001201
Alex Klein1699fab2022-09-08 08:46:06 -06001202 with cros_build_lib.ContextManagerStack() as stack:
1203 # Preserve chromite; we might be running from there!
1204 options.preserve_paths = set(["chromite"])
1205 if log_file is not None:
1206 # We don't want the critical section to try to clean up the tee process,
1207 # so we run Tee (forked off) outside of it. This prevents a deadlock
1208 # because the Tee process only exits when its pipe is closed, and the
1209 # critical section accidentally holds on to that file handle.
1210 stack.Add(tee.Tee, log_file)
1211 options.preserve_paths.add(_DEFAULT_LOG_DIR)
David Jamescebc7272013-07-17 16:45:05 -07001212
Alex Klein1699fab2022-09-08 08:46:06 -06001213 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1214 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001215
Alex Klein1699fab2022-09-08 08:46:06 -06001216 if not options.resume:
1217 # If we're in resume mode, use our parents tempdir rather than
1218 # nesting another layer.
Andrew Lamb5a727f92022-09-30 20:39:46 +00001219 stack.Add(osutils.TempDir, prefix="cbb", set_global=True)
Alex Klein1699fab2022-09-08 08:46:06 -06001220 logging.debug("Cbuildbot tempdir is %r.", os.environ.get("TMP"))
Brian Harringd166aaf2012-05-14 18:31:53 -07001221
Alex Klein1699fab2022-09-08 08:46:06 -06001222 if options.cgroups:
1223 stack.Add(cgroups.SimpleContainChildren, "cbuildbot")
Brian Harringa184efa2012-03-04 11:51:25 -08001224
Alex Klein1699fab2022-09-08 08:46:06 -06001225 # Mark everything between EnforcedCleanupSection and here as having to
1226 # be rolled back via the contextmanager cleanup handlers. This
1227 # ensures that sudo bits cannot outlive cbuildbot, that anything
1228 # cgroups would kill gets killed, etc.
1229 stack.Add(critical_section.ForkWatchdog)
Brian Harringd166aaf2012-05-14 18:31:53 -07001230
Alex Klein1699fab2022-09-08 08:46:06 -06001231 if options.mock_slave_status is not None:
Mike Frysinger31fdddd2023-02-24 15:50:55 -05001232 with open(options.mock_slave_status, "rb") as f:
Alex Klein1699fab2022-09-08 08:46:06 -06001233 mock_statuses = pickle.load(f)
1234 for key, value in mock_statuses.items():
1235 mock_statuses[key] = builder_status_lib.BuilderStatus(
1236 **value
1237 )
1238 stack.Add(
1239 _ObjectMethodPatcher,
Mike Nicholsa1414162021-04-22 20:07:22 +00001240 completion_stages.MasterSlaveSyncCompletionStage,
Alex Klein1699fab2022-09-08 08:46:06 -06001241 "_FetchSlaveStatuses",
1242 return_value=mock_statuses,
1243 )
Aviv Keshetcf9c2722014-02-25 15:15:10 -08001244
Alex Klein1699fab2022-09-08 08:46:06 -06001245 stack.Add(_SetupConnections, options, build_config)
1246 retry_stats.SetupStats()
Aviv Keshet2982af52014-08-13 16:07:57 -07001247
Alex Klein1699fab2022-09-08 08:46:06 -06001248 timeout_display_message = (
1249 "This build has reached the timeout deadline set by the master. "
1250 "Either this stage or a previous one took too long (see stage "
1251 "timing historical summary in ReportStage) or the build failed "
1252 "to start on time."
1253 )
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001254
Alex Klein1699fab2022-09-08 08:46:06 -06001255 if options.timeout > 0:
1256 stack.Add(
1257 timeout_util.FatalTimeout,
1258 options.timeout,
1259 timeout_display_message,
1260 )
1261 try:
1262 _RunBuildStagesWrapper(options, site_config, build_config)
1263 except failures_lib.ExitEarlyException as ex:
1264 # This build finished successfully. Do not re-raise ExitEarlyException.
1265 logging.info("One stage exited early: %s", ex)