blob: a5b5f28ce9c45a76a13163406cb30f84604ae9a1 [file] [log] [blame]
Mike Frysingerd6925b52012-07-16 16:11:00 -04001# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
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:
153 with open(options.metadata_dump, "r") as metadata_file:
154 metadata_dump_dict = json.loads(metadata_file.read())
155
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 )
316 # TODO(crbug.com/1359171): cleanup the flag.
317 parser.add_option(
318 "--goma_client_json",
319 type="path",
320 api=constants.REEXEC_API_GOMA,
321 help="Specify a service-account-goma-client.json path.",
322 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800323
Alex Klein1699fab2022-09-08 08:46:06 -0600324 group = CustomGroup(parser, "Deprecated Options")
Don Garrett211df8c2017-09-06 13:33:02 -0700325
Alex Klein1699fab2022-09-08 08:46:06 -0600326 parser.add_option(
327 "--local",
328 action="store_true",
329 default=False,
330 help="Deprecated. See cros tryjob.",
331 )
332 parser.add_option(
333 "--remote",
334 action="store_true",
335 default=False,
336 help="Deprecated. See cros tryjob.",
337 )
Don Garrett211df8c2017-09-06 13:33:02 -0700338
Alex Klein1699fab2022-09-08 08:46:06 -0600339 #
340 # Patch selection options.
341 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400342
Alex Klein1699fab2022-09-08 08:46:06 -0600343 group = CustomGroup(parser, "Patch Options")
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400344
Alex Klein1699fab2022-09-08 08:46:06 -0600345 group.add_remote_option(
346 "-g",
347 "--gerrit-patches",
348 action="split_extend",
349 type="string",
350 default=[],
351 metavar="'Id1 *int_Id2...IdN'",
352 help="Space-separated list of short-form Gerrit "
353 "Change-Id's or change numbers to patch. "
354 "Please prepend '*' to internal Change-Id's",
355 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400356
Alex Klein1699fab2022-09-08 08:46:06 -0600357 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400358
Alex Klein1699fab2022-09-08 08:46:06 -0600359 #
360 # Remote trybot options.
361 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400362
Alex Klein1699fab2022-09-08 08:46:06 -0600363 group = CustomGroup(parser, "Options used to configure tryjob behavior.")
364 group.add_remote_option(
365 "--hwtest",
366 action="store_true",
367 default=False,
368 help="Run the HWTest stage (tests on real hardware)",
369 )
370 group.add_option(
371 "--hwtest_dut_dimensions",
372 type="string",
373 action="split_extend",
374 default=None,
375 help="Space-separated list of key:val Swarming bot "
376 "dimensions to run each builders SkylabHWTest "
377 "stages against (this overrides the configured "
378 "DUT dimensions for each test). Requires at least "
379 '"label-board", "label-model", and "label-pool".',
380 )
381 group.add_remote_option(
382 "--channel",
383 action="split_extend",
384 dest="channels",
385 default=[],
386 help="Specify a channel for a payloads trybot. Can "
387 "be specified multiple times. No valid for "
388 "non-payloads configs.",
389 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400390
Alex Klein1699fab2022-09-08 08:46:06 -0600391 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400392
Alex Klein1699fab2022-09-08 08:46:06 -0600393 #
394 # Advanced options.
395 #
Ryan Cuif4f84be2012-07-09 18:50:41 -0700396
Alex Klein1699fab2022-09-08 08:46:06 -0600397 group = CustomGroup(
398 parser,
399 "Advanced Options",
400 "Caution: use these options at your own risk.",
401 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800402
Alex Klein1699fab2022-09-08 08:46:06 -0600403 group.add_remote_option(
404 "--bootstrap-args",
405 action="append",
406 default=[],
407 help="Args passed directly to the bootstrap re-exec "
408 "to skip verification by the bootstrap code",
409 )
410 group.add_remote_option(
411 "--buildbot",
412 action="store_true",
413 dest="buildbot",
414 default=False,
415 help="This is running on a buildbot. "
416 "This can be used to make a build operate "
417 "like an official builder, e.g. generate "
418 "new version numbers and archive official "
419 "artifacts and such. This should only be "
420 "used if you are confident in what you are "
421 "doing, as it will make automated commits.",
422 )
423 parser.add_remote_option(
424 "--repo-cache",
425 type="path",
426 dest="_repo_cache",
427 help="Present for backwards compatibility, ignored.",
428 )
429 group.add_remote_option(
430 "--no-buildbot-tags",
431 action="store_false",
432 dest="enable_buildbot_tags",
433 default=True,
434 help="Suppress buildbot specific tags from log "
435 "output. This is used to hide recursive "
436 "cbuilbot runs on the waterfall.",
437 )
438 group.add_remote_option(
439 "--buildnumber", type="int", default=0, help="build number"
440 )
441 group.add_option(
442 "--chrome_root",
443 action="callback",
444 type="path",
445 callback=_CheckChromeRootOption,
446 help="Local checkout of Chrome to use.",
447 )
448 group.add_remote_option(
449 "--chrome_version",
450 action="callback",
451 type="string",
452 dest="chrome_version",
453 callback=_CheckChromeVersionOption,
454 help="Used with SPEC logic to force a particular "
455 "git revision of chrome rather than the "
456 "latest.",
457 )
458 group.add_remote_option(
459 "--clobber",
460 action="store_true",
461 default=False,
462 help="Clears an old checkout before syncing",
463 )
464 group.add_remote_option(
465 "--latest-toolchain",
466 action="store_true",
467 default=False,
468 help="Use the latest toolchain.",
469 )
470 parser.add_option(
471 "--log_dir",
472 dest="log_dir",
473 type="path",
474 help="Directory where logs are stored.",
475 )
476 group.add_remote_option(
477 "--maxarchives",
478 type="int",
479 dest="max_archive_builds",
480 default=3,
481 help="Change the local saved build count limit.",
482 )
483 parser.add_remote_option(
484 "--manifest-repo-url", help="Overrides the default manifest repo url."
485 )
486 group.add_remote_option(
487 "--compilecheck",
488 action="store_true",
489 default=False,
490 help="Only verify compilation and unit tests.",
491 )
492 group.add_remote_option(
493 "--noarchive",
494 action="store_false",
495 dest="archive",
496 default=True,
497 help="Don't run archive stage.",
498 )
499 group.add_remote_option(
500 "--nobootstrap",
501 action="store_false",
502 dest="bootstrap",
503 default=True,
504 help="Don't checkout and run from a standalone " "chromite repo.",
505 )
506 group.add_remote_option(
507 "--nobuild",
508 action="store_false",
509 dest="build",
510 default=True,
511 help="Don't actually build (for cbuildbot dev)",
512 )
513 group.add_remote_option(
514 "--noclean",
515 action="store_false",
516 dest="clean",
517 default=True,
518 help="Don't clean the buildroot",
519 )
520 group.add_remote_option(
521 "--nocgroups",
522 action="store_false",
523 dest="cgroups",
524 default=True,
525 help="Disable cbuildbots usage of cgroups.",
526 )
527 group.add_remote_option(
528 "--nochromesdk",
529 action="store_false",
530 dest="chrome_sdk",
531 default=True,
532 help="Don't run the ChromeSDK stage which builds "
533 "Chrome outside of the chroot.",
534 )
535 group.add_remote_option(
536 "--noprebuilts",
537 action="store_false",
538 dest="prebuilts",
539 default=True,
540 help="Don't upload prebuilts.",
541 )
542 group.add_remote_option(
543 "--nopatch",
544 action="store_false",
545 dest="postsync_patch",
546 default=True,
547 help="Don't run PatchChanges stage. This does not "
548 "disable patching in of chromite patches "
549 "during BootstrapStage.",
550 )
551 group.add_remote_option(
552 "--nopaygen",
553 action="store_false",
554 dest="paygen",
555 default=True,
556 help="Don't generate payloads.",
557 )
558 group.add_remote_option(
559 "--noreexec",
560 action="store_false",
561 dest="postsync_reexec",
562 default=True,
563 help="Don't reexec into the buildroot after syncing.",
564 )
565 group.add_remote_option(
566 "--nosdk",
567 action="store_true",
568 default=False,
569 help="Re-create the SDK from scratch.",
570 )
571 group.add_remote_option(
572 "--nosync",
573 action="store_false",
574 dest="sync",
575 default=True,
576 help="Don't sync before building.",
577 )
578 group.add_remote_option(
579 "--notests",
580 action="store_false",
581 dest="tests",
582 default=True,
583 help="Override values from buildconfig, run no "
584 "tests, and build no autotest and artifacts.",
585 )
586 group.add_remote_option(
587 "--novmtests",
588 action="store_false",
589 dest="vmtests",
590 default=True,
591 help="Override values from buildconfig, run no " "vmtests.",
592 )
593 group.add_remote_option(
594 "--noimagetests",
595 action="store_false",
596 dest="image_test",
597 default=True,
598 help="Override values from buildconfig and run no " "image tests.",
599 )
600 group.add_remote_option(
601 "--nouprev",
602 action="store_false",
603 dest="uprev",
604 default=True,
605 help="Override values from buildconfig and never " "uprev.",
606 )
607 group.add_option(
608 "--reference-repo",
609 help="Reuse git data stored in an existing repo "
610 "checkout. This can drastically reduce the network "
611 "time spent setting up the trybot checkout. By "
612 "default, if this option isn't given but cbuildbot "
613 "is invoked from a repo checkout, cbuildbot will "
614 "use the repo root.",
615 )
616 group.add_option(
617 "--resume",
618 action="store_true",
619 default=False,
620 help="Skip stages already successfully completed.",
621 )
622 group.add_remote_option(
623 "--timeout",
624 type="int",
625 default=0,
626 help="Specify the maximum amount of time this job "
627 "can run for, at which point the build will be "
628 "aborted. If set to zero, then there is no "
629 "timeout.",
630 )
631 group.add_remote_option(
632 "--version",
633 dest="force_version",
634 help="Used with manifest logic. Forces use of this "
635 "version rather than create or get latest. "
636 "Examples: 4815.0.0-rc1, 4815.1.2",
637 )
638 group.add_remote_option(
639 "--git-cache-dir",
640 type="path",
641 api=constants.REEXEC_API_GIT_CACHE_DIR,
642 help="Specify the cache directory to store the "
643 "project caches populated by the git-cache "
644 "tool. Bootstrap the projects based on the git "
645 "cache files instead of fetching them directly "
646 "from the GoB servers.",
647 )
648 group.add_remote_option(
649 "--chrome-preload-dir",
650 type="path",
651 api=constants.REEXEC_API_CHROME_PRELOAD_DIR,
652 help="Specify a preloaded chrome source cache "
653 "directory populated by the git-cache tool. "
654 "Bootstrap chrome based on the cached files "
655 "instead of fetching them directly from the GoB "
656 "servers. When both this argument and "
657 "--git-cache-dir are provided this value will "
658 "be preferred for the chrome source cache.",
659 )
660 group.add_remote_option(
661 "--source_cache",
662 action="store_true",
663 default=False,
664 help="Whether to utilize cache snapshot mounts.",
665 )
666 group.add_remote_option(
667 "--debug-cidb",
668 action="store_true",
669 default=False,
670 help="Force Debug CIDB to be used.",
671 )
672 # cbuildbot ChromeOS Findit options
673 group.add_remote_option(
674 "--cbb_build_packages",
675 action="split_extend",
676 dest="cbb_build_packages",
677 default=[],
678 help="Specify an explicit list of packages to build "
679 "for integration with Findit.",
680 )
681 group.add_remote_option(
682 "--cbb_snapshot_revision",
683 type="string",
684 dest="cbb_snapshot_revision",
685 default=None,
686 help="Snapshot manifest revision to sync to " "for building.",
687 )
688 group.add_remote_option(
689 "--no-publish-prebuilt-confs",
690 dest="publish",
691 action="store_false",
692 default=True,
693 help="Don't publish git commits to prebuilt.conf or sdk_version.conf",
694 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400695
Alex Klein1699fab2022-09-08 08:46:06 -0600696 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400697
Alex Klein1699fab2022-09-08 08:46:06 -0600698 #
699 # Internal options.
700 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400701
Alex Klein1699fab2022-09-08 08:46:06 -0600702 group = CustomGroup(
703 parser,
704 "Internal Chromium OS Build Team Options",
705 "Caution: these are for meant for the Chromium OS build team only",
706 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400707
Alex Klein1699fab2022-09-08 08:46:06 -0600708 group.add_remote_option(
709 "--archive-base",
710 type="gs_path",
711 help="Base GS URL (gs://<bucket_name>/<path>) to "
712 "upload archive artifacts to",
713 )
714 group.add_remote_option(
715 "--cq-gerrit-query",
716 dest="cq_gerrit_override",
717 help="If given, this gerrit query will be used to find what patches to "
718 "test, rather than the normal 'CommitQueue>=1 AND Verified=1 AND "
719 "CodeReview=2' query it defaults to. Use with care- note "
720 "additionally this setting only has an effect if the buildbot "
721 "target is a cq target, and we're in buildbot mode.",
722 )
723 group.add_option(
724 "--pass-through",
725 action="append",
726 type="string",
727 dest="pass_through_args",
728 default=[],
729 )
730 group.add_option(
731 "--reexec-api-version",
732 action="store_true",
733 dest="output_api_version",
734 default=False,
735 help="Used for handling forwards/backwards compatibility "
736 "with --resume and --bootstrap",
737 )
738 group.add_option(
739 "--remote-trybot",
740 action="store_true",
741 default=False,
742 help="Indicates this is running on a remote trybot machine",
743 )
744 group.add_option(
745 "--buildbucket-id",
746 api=constants.REEXEC_API_GOMA, # Approximate.
747 help="The unique ID in buildbucket of current build "
748 "generated by buildbucket.",
749 )
750 group.add_remote_option(
751 "--remote-patches",
752 action="split_extend",
753 default=[],
754 help="Patches uploaded by the trybot client when "
755 "run using the -p option",
756 )
757 # Note the default here needs to be hardcoded to 3; that is the last version
758 # that lacked this functionality.
759 group.add_option(
760 "--remote-version",
761 type="int",
762 default=3,
763 help="Deprecated and ignored.",
764 )
765 group.add_option("--sourceroot", type="path", default=constants.SOURCE_ROOT)
766 group.add_remote_option(
767 "--test-bootstrap",
768 action="store_true",
769 default=False,
770 help="Causes cbuildbot to bootstrap itself twice, "
771 "in the sequence A->B->C: A(unpatched) patches "
772 "and bootstraps B; B patches and bootstraps C",
773 )
774 group.add_remote_option(
775 "--validation_pool",
776 help="Path to a pickled validation pool. Intended "
777 "for use only with the commit queue.",
778 )
779 group.add_remote_option(
780 "--metadata_dump",
781 help="Path to a json dumped metadata file. This "
782 "will be used as the initial metadata.",
783 )
784 group.add_remote_option(
785 "--master-build-id",
786 type="int",
787 api=constants.REEXEC_API_MASTER_BUILD_ID,
788 help="cidb build id of the master build to this " "slave build.",
789 )
790 group.add_remote_option(
791 "--master-buildbucket-id",
792 api=constants.REEXEC_API_MASTER_BUILDBUCKET_ID,
793 help="buildbucket id of the master build to this " "slave build.",
794 )
795 # TODO(nxia): crbug.com/778838
796 # cbuildbot doesn't use pickle files anymore, remove this.
797 group.add_remote_option(
798 "--mock-slave-status",
799 metavar="MOCK_SLAVE_STATUS_PICKLE_FILE",
800 help="Override the result of the _FetchSlaveStatuses "
801 "method of MasterSlaveSyncCompletionStage, by "
802 "specifying a file with a pickle of the result "
803 "to be returned.",
804 )
805 group.add_option(
806 "--previous-build-state",
807 type="string",
808 default="",
809 api=constants.REEXEC_API_PREVIOUS_BUILD_STATE,
810 help="A base64-encoded BuildSummary object describing the "
811 "previous build run on the same build machine.",
812 )
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400813
Alex Klein1699fab2022-09-08 08:46:06 -0600814 parser.add_argument_group(group)
Ryan Cuif4f84be2012-07-09 18:50:41 -0700815
Alex Klein1699fab2022-09-08 08:46:06 -0600816 #
817 # Debug options
818 #
819 # Temporary hack; in place till --dry-run replaces --debug.
820 # pylint: disable=protected-access
821 group = parser.debug_group
822 debug = [x for x in group.option_list if x._long_opts == ["--debug"]][0]
823 debug.help += " Currently functions as --dry-run in addition."
824 debug.pass_through = True
825 group.add_option(
826 "--notee",
827 action="store_false",
828 dest="tee",
829 default=True,
830 help="Disable logging and internal tee process. Primarily "
831 "used for debugging cbuildbot itself.",
832 )
833 return parser
Brian Harring3fec5a82012-03-01 05:57:03 -0800834
835
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400836def _FinishParsing(options):
Alex Klein1699fab2022-09-08 08:46:06 -0600837 """Perform some parsing tasks that need to take place after optparse.
Ryan Cui85867972012-02-23 18:21:49 -0800838
Alex Klein1699fab2022-09-08 08:46:06 -0600839 This function needs to be easily testable! Keep it free of
840 environment-dependent code. Put more detailed usage validation in
841 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800842
Alex Klein1699fab2022-09-08 08:46:06 -0600843 Args:
844 options: The options object returned by optparse
845 """
846 # Populate options.pass_through_args.
847 accepted, _ = commandline.FilteringParser.FilterArgs(
848 options.parsed_args, lambda x: x.opt_inst.pass_through
849 )
850 options.pass_through_args.extend(accepted)
Brian Harring07039b52012-05-13 17:56:47 -0700851
Alex Klein1699fab2022-09-08 08:46:06 -0600852 if options.local or options.remote:
853 cros_build_lib.Die("Deprecated usage. Please use cros tryjob instead.")
Don Garrettcc0ee522017-09-13 14:28:42 -0700854
Alex Klein1699fab2022-09-08 08:46:06 -0600855 if not options.buildroot:
856 cros_build_lib.Die("A buildroot is required to build.")
Don Garrett211df8c2017-09-06 13:33:02 -0700857
Alex Klein1699fab2022-09-08 08:46:06 -0600858 if options.chrome_root:
859 if options.chrome_rev != constants.CHROME_REV_LOCAL:
860 cros_build_lib.Die(
861 "Chrome rev must be %s if chrome_root is set."
862 % constants.CHROME_REV_LOCAL
863 )
864 elif options.chrome_rev == constants.CHROME_REV_LOCAL:
865 cros_build_lib.Die(
866 "Chrome root must be set if chrome_rev is %s."
867 % constants.CHROME_REV_LOCAL
868 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800869
Alex Klein1699fab2022-09-08 08:46:06 -0600870 if options.chrome_version:
871 if options.chrome_rev != constants.CHROME_REV_SPEC:
872 cros_build_lib.Die(
873 "Chrome rev must be %s if chrome_version is set."
874 % constants.CHROME_REV_SPEC
875 )
876 elif options.chrome_rev == constants.CHROME_REV_SPEC:
877 cros_build_lib.Die(
878 "Chrome rev must not be %s if chrome_version is not set."
879 % constants.CHROME_REV_SPEC
880 )
Brian Harring3fec5a82012-03-01 05:57:03 -0800881
Alex Klein1699fab2022-09-08 08:46:06 -0600882 patches = bool(options.gerrit_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700883
Alex Klein1699fab2022-09-08 08:46:06 -0600884 # When running in release mode, make sure we are running with checked-in code.
885 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
886 # a release image with checked-in code for CrOS packages.
887 if options.buildbot and patches and not options.debug:
888 cros_build_lib.Die(
889 "Cannot provide patches when running with --buildbot!"
890 )
David James5734ea32012-08-15 20:23:49 -0700891
Alex Klein1699fab2022-09-08 08:46:06 -0600892 if options.buildbot and options.remote_trybot:
893 cros_build_lib.Die(
894 "--buildbot and --remote-trybot cannot be used together."
895 )
Ryan Cuiba41ad32012-03-08 17:15:29 -0800896
Alex Klein1699fab2022-09-08 08:46:06 -0600897 # Record whether --debug was set explicitly vs. it was inferred.
898 options.debug_forced = options.debug
899 # We force --debug to be set for builds that are not 'official'.
900 options.debug = options.debug or not options.buildbot
Brian Harring3fec5a82012-03-01 05:57:03 -0800901
Alex Klein1699fab2022-09-08 08:46:06 -0600902 options.hwtest_dut_override = ParseHWTestDUTDims(
903 options.hwtest_dut_dimensions
904 )
905
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600906
907def ParseHWTestDUTDims(dims):
Alex Klein1699fab2022-09-08 08:46:06 -0600908 """Parse HWTest DUT dimensions into a valid HWTestDUTOverride object.
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600909
Alex Klein1699fab2022-09-08 08:46:06 -0600910 Raises an error if any of board, model, or pool is missing.
911 """
912 if not dims:
913 return None
914 board = model = pool = None
915 extra_dims = []
916 for dim in dims:
917 if dim.startswith(BOARD_DIM_LABEL):
918 # Remove one extra character to account for the ":" or "=" symbol
919 # separating the label from the dimension itself.
920 board = dim[len(BOARD_DIM_LABEL) + 1 :]
921 elif dim.startswith(MODEL_DIM_LABEL):
922 model = dim[len(MODEL_DIM_LABEL) + 1 :]
923 elif dim.startswith(POOL_DIM_LABEL):
924 pool = dim[len(POOL_DIM_LABEL) + 1 :]
925 else:
926 extra_dims.append(dim)
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600927
Alex Klein1699fab2022-09-08 08:46:06 -0600928 if not (board and model and pool):
929 cros_build_lib.Die(
930 "HWTest DUT dimensions must include board, model, and "
931 "pool (given %s)." % dims
932 )
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600933
Alex Klein1699fab2022-09-08 08:46:06 -0600934 return test_stages.HWTestDUTOverride(board, model, pool, extra_dims)
Jared Loucksa9e94bf2021-06-28 10:03:31 -0600935
Brian Harring3fec5a82012-03-01 05:57:03 -0800936
Mike Frysinger27e21b72018-07-12 14:20:21 -0400937# pylint: disable=unused-argument
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400938def _PostParseCheck(parser, options, site_config):
Alex Klein1699fab2022-09-08 08:46:06 -0600939 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800940
Alex Klein1699fab2022-09-08 08:46:06 -0600941 Args:
942 parser: Option parser that was used to parse arguments.
943 options: The options returned by optparse.
944 site_config: config_lib.SiteConfig containing all config info.
945 """
Don Garrett0a873e02015-06-30 17:55:10 -0700946
Alex Klein1699fab2022-09-08 08:46:06 -0600947 if not options.branch:
948 options.branch = git.GetChromiteTrackingBranch()
Ryan Cuie1e4e662012-05-21 16:39:46 -0700949
Alex Klein1699fab2022-09-08 08:46:06 -0600950 # Because the default cache dir depends on other options, FindCacheDir
951 # always returns None, and we setup the default here.
952 if options.cache_dir is None:
953 # Note, options.sourceroot is set regardless of the path
954 # actually existing.
955 options.cache_dir = os.path.join(options.buildroot, ".cache")
956 options.cache_dir = os.path.abspath(options.cache_dir)
957 parser.ConfigureCacheDir(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700958
Alex Klein1699fab2022-09-08 08:46:06 -0600959 osutils.SafeMakedirsNonRoot(options.cache_dir)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700960
Alex Klein1699fab2022-09-08 08:46:06 -0600961 # Ensure that all args are legitimate config targets.
962 if options.build_config_name not in site_config:
963 cros_build_lib.Die(
964 'Unknown build config: "%s"' % options.build_config_name
965 )
Don Garrett4bb21682014-03-03 16:16:23 -0800966
Alex Klein1699fab2022-09-08 08:46:06 -0600967 build_config = site_config[options.build_config_name]
968 is_payloads_build = build_config.build_type == constants.PAYLOADS_TYPE
Don Garrett4af20982015-05-29 19:02:23 -0700969
Alex Klein1699fab2022-09-08 08:46:06 -0600970 if options.channels and not is_payloads_build:
971 cros_build_lib.Die(
972 "--channel must only be used with a payload config,"
973 " not target (%s)." % options.build_config_name
974 )
Don Garrett5af1d262014-05-16 15:49:37 -0700975
Alex Klein1699fab2022-09-08 08:46:06 -0600976 if not options.channels and is_payloads_build:
977 cros_build_lib.Die(
978 "payload configs (%s) require --channel to do anything"
979 " useful." % options.build_config_name
980 )
Matt Tennant763497d2014-01-17 16:45:54 -0800981
Alex Klein1699fab2022-09-08 08:46:06 -0600982 # If the build config explicitly forces the debug flag, set the debug flag
983 # as if it was set from the command line.
984 if build_config.debug:
985 options.debug = True
Don Garrett370839f2017-10-19 18:32:34 -0700986
Alex Klein1699fab2022-09-08 08:46:06 -0600987 if not (config_lib.isTryjobConfig(build_config) or options.buildbot):
988 cros_build_lib.Die(
989 "Refusing to run non-tryjob config as a tryjob.\n"
990 'Please "repo sync && cros tryjob --list %s" for alternatives.\n'
991 "See go/cros-explicit-tryjob-build-configs-psa.",
992 build_config.name,
993 )
Don Garrett02d2f582017-11-08 14:01:24 -0800994
Alex Klein1699fab2022-09-08 08:46:06 -0600995 # The --version option is not compatible with an external target unless the
996 # --buildbot option is specified. More correctly, only "paladin versions"
997 # will work with external targets, and those are only used with --buildbot.
998 # If --buildbot is specified, then user should know what they are doing and
999 # only specify a version that will work. See crbug.com/311648.
1000 if options.force_version and not (
1001 options.buildbot or build_config.internal
1002 ):
1003 cros_build_lib.Die(
1004 "Cannot specify --version without --buildbot for an"
1005 " external target (%s)." % options.build_config_name
1006 )
Matt Tennant763497d2014-01-17 16:45:54 -08001007
Ryan Cui85867972012-02-23 18:21:49 -08001008
Don Garrett597ddff2017-02-17 18:29:37 -08001009def ParseCommandLine(parser, argv):
Alex Klein1699fab2022-09-08 08:46:06 -06001010 """Completely parse the commandline arguments"""
1011 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -07001012
Alex Klein1699fab2022-09-08 08:46:06 -06001013 # Handle the request for the reexec command line API version number.
1014 if options.output_api_version:
1015 print(constants.REEXEC_API_VERSION)
1016 sys.exit(0)
Brian Harring37e559b2012-05-22 20:47:32 -07001017
Alex Klein1699fab2022-09-08 08:46:06 -06001018 # Record the configs targeted. Strip out null arguments.
1019 build_config_names = [x for x in args if x]
1020 if len(build_config_names) != 1:
1021 cros_build_lib.Die(
1022 "Expected exactly one build config. Got: %r", build_config_names
1023 )
1024 options.build_config_name = build_config_names[-1]
Don Garrettf0761152017-10-19 19:38:27 -07001025
Alex Klein1699fab2022-09-08 08:46:06 -06001026 _FinishParsing(options)
1027 return options
Ryan Cui85867972012-02-23 18:21:49 -08001028
1029
Alex Klein1699fab2022-09-08 08:46:06 -06001030_ENVIRONMENT_PROD = "prod"
1031_ENVIRONMENT_DEBUG = "debug"
1032_ENVIRONMENT_STANDALONE = "standalone"
Aviv Keshet420de512015-05-18 14:28:48 -07001033
1034
1035def _GetRunEnvironment(options, build_config):
Alex Klein1699fab2022-09-08 08:46:06 -06001036 """Determine whether this is a prod/debug/standalone run."""
1037 if options.debug_cidb:
1038 return _ENVIRONMENT_DEBUG
Don Garretta90f0142018-02-28 14:25:19 -08001039
Alex Klein1699fab2022-09-08 08:46:06 -06001040 # One of these arguments should always be set if running on a real builder.
1041 # If we aren't on a real builder, we are standalone.
1042 if not options.buildbot and not options.remote_trybot:
1043 return _ENVIRONMENT_STANDALONE
Aviv Keshet420de512015-05-18 14:28:48 -07001044
Alex Klein1699fab2022-09-08 08:46:06 -06001045 if build_config["debug_cidb"]:
1046 return _ENVIRONMENT_DEBUG
Aviv Keshet420de512015-05-18 14:28:48 -07001047
Alex Klein1699fab2022-09-08 08:46:06 -06001048 return _ENVIRONMENT_PROD
Aviv Keshet420de512015-05-18 14:28:48 -07001049
1050
Gabe Blackde694a32015-02-19 15:11:11 -08001051def _SetupConnections(options, build_config):
Alex Klein1699fab2022-09-08 08:46:06 -06001052 """Set up CIDB connections using the appropriate Setup call.
Aviv Keshet2982af52014-08-13 16:07:57 -07001053
Alex Klein1699fab2022-09-08 08:46:06 -06001054 Args:
1055 options: Command line options structure.
1056 build_config: Config object for this build.
1057 """
1058 # Outline:
1059 # 1) Based on options and build_config, decide whether we are a production
1060 # run, debug run, or standalone run.
1061 # 2) Set up cidb instance accordingly.
1062 # 3) Update topology info from cidb, so that any other service set up can use
1063 # topology.
1064 # 4) Set up any other services.
1065 run_type = _GetRunEnvironment(options, build_config)
Aviv Keshet420de512015-05-18 14:28:48 -07001066
Alex Klein1699fab2022-09-08 08:46:06 -06001067 if run_type == _ENVIRONMENT_PROD:
1068 cidb.CIDBConnectionFactory.SetupProdCidb()
1069 context = ts_mon_config.SetupTsMonGlobalState(
1070 "cbuildbot", indirect=True
1071 )
1072 elif run_type == _ENVIRONMENT_DEBUG:
1073 cidb.CIDBConnectionFactory.SetupDebugCidb()
1074 context = ts_mon_config.TrivialContextManager()
1075 else:
1076 cidb.CIDBConnectionFactory.SetupNoCidb()
1077 context = ts_mon_config.TrivialContextManager()
Aviv Keshet62d1a0e2014-08-22 21:16:13 -07001078
Alex Klein1699fab2022-09-08 08:46:06 -06001079 topology.FetchTopology()
1080 return context
Paul Hobbsd5a0f812016-07-26 16:10:31 -07001081
Aviv Keshet2982af52014-08-13 16:07:57 -07001082
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001083class _MockMethodWithReturnValue(object):
Alex Klein1699fab2022-09-08 08:46:06 -06001084 """A method mocker which just returns the specific value."""
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001085
Alex Klein1699fab2022-09-08 08:46:06 -06001086 def __init__(self, return_value):
1087 self.return_value = return_value
1088
1089 def __call__(self, *args, **kwargs):
1090 return self.return_value
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001091
1092
1093class _ObjectMethodPatcher(object):
Alex Klein1699fab2022-09-08 08:46:06 -06001094 """A simplified mock.object.patch.
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001095
Alex Klein1699fab2022-09-08 08:46:06 -06001096 It is a context manager that patches an object's method with specified
1097 return value.
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001098 """
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001099
Alex Klein1699fab2022-09-08 08:46:06 -06001100 def __init__(self, target, attr, return_value=None):
1101 """Constructor.
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001102
Alex Klein1699fab2022-09-08 08:46:06 -06001103 Args:
1104 target: object to patch.
1105 attr: method name of the object to patch.
1106 return_value: the return value when calling target.attr
1107 """
1108 self.target = target
1109 self.attr = attr
1110 self.return_value = return_value
1111 self.original_attr = None
1112 self.new_attr = _MockMethodWithReturnValue(self.return_value)
1113
1114 def __enter__(self):
1115 self.original_attr = self.target.__dict__[self.attr]
1116 setattr(self.target, self.attr, self.new_attr)
1117
1118 def __exit__(self, *args):
1119 if self.target and self.original_attr:
1120 setattr(self.target, self.attr, self.original_attr)
Dean Liaoe5b0aca2018-01-24 15:27:26 +08001121
1122
Matt Tennant759e2352013-09-27 15:14:44 -07001123# TODO(build): This function is too damn long.
Ryan Cui85867972012-02-23 18:21:49 -08001124def main(argv):
Alex Klein1699fab2022-09-08 08:46:06 -06001125 # We get false positives with the options object.
1126 # pylint: disable=attribute-defined-outside-init
Mike Frysinger80bba8a2017-08-18 15:28:36 -04001127
Alex Klein1699fab2022-09-08 08:46:06 -06001128 # Turn on strict sudo checks.
1129 cros_build_lib.STRICT_SUDO = True
David James59a0a2b2013-03-22 14:04:44 -07001130
Alex Klein1699fab2022-09-08 08:46:06 -06001131 # Set umask to 022 so files created by buildbot are readable.
1132 os.umask(0o22)
Ryan Cui85867972012-02-23 18:21:49 -08001133
Alex Klein1699fab2022-09-08 08:46:06 -06001134 parser = _CreateParser()
1135 options = ParseCommandLine(parser, argv)
Don Garrett0a873e02015-06-30 17:55:10 -07001136
Alex Klein1699fab2022-09-08 08:46:06 -06001137 # Fetch our site_config now, because we need it to do anything else.
1138 site_config = config_lib.GetConfig()
Don Garrettb85658c2015-06-30 19:07:22 -07001139
Alex Klein1699fab2022-09-08 08:46:06 -06001140 _PostParseCheck(parser, options, site_config)
Brian Harring3fec5a82012-03-01 05:57:03 -08001141
Alex Klein1699fab2022-09-08 08:46:06 -06001142 cros_build_lib.AssertOutsideChroot()
Zdenek Behan98ec2fb2012-08-31 17:12:18 +02001143
Alex Klein1699fab2022-09-08 08:46:06 -06001144 if options.enable_buildbot_tags:
1145 cbuildbot_alerts.EnableBuildbotMarkers()
Matt Tennant759e2352013-09-27 15:14:44 -07001146
Alex Klein1699fab2022-09-08 08:46:06 -06001147 if (
1148 options.buildbot
1149 and not options.debug
1150 and not cros_build_lib.HostIsCIBuilder()
1151 ):
1152 # --buildbot can only be used on a real builder, unless it's debug.
1153 cros_build_lib.Die("This host is not a supported build machine.")
Ningning Xiac691e432016-08-11 14:52:59 -07001154
Alex Klein1699fab2022-09-08 08:46:06 -06001155 # Only one config arg is allowed in this mode, which was confirmed earlier.
1156 build_config = site_config[options.build_config_name]
Brian Harring3fec5a82012-03-01 05:57:03 -08001157
Alex Klein1699fab2022-09-08 08:46:06 -06001158 # TODO: Re-enable this block when reference_repo support handles this
1159 # properly. (see chromium:330775)
1160 # if options.reference_repo is None:
1161 # repo_path = os.path.join(options.sourceroot, '.repo')
1162 # # If we're being run from a repo checkout, reuse the repo's git pool to
1163 # # cut down on sync time.
1164 # if os.path.exists(repo_path):
1165 # options.reference_repo = options.sourceroot
Don Garrettbbd7b552014-05-16 13:15:21 -07001166
Alex Klein1699fab2022-09-08 08:46:06 -06001167 if options.reference_repo:
1168 if not os.path.exists(options.reference_repo):
1169 parser.error(
1170 "Reference path %s does not exist" % (options.reference_repo,)
1171 )
1172 elif not os.path.exists(os.path.join(options.reference_repo, ".repo")):
1173 parser.error(
1174 "Reference path %s does not look to be the base of a "
1175 "repo checkout; no .repo exists in the root."
1176 % (options.reference_repo,)
1177 )
David Jamesdac7a912013-11-18 11:14:44 -08001178
Alex Klein1699fab2022-09-08 08:46:06 -06001179 if (options.buildbot or options.remote_trybot) and not options.resume:
1180 missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
1181 if missing:
1182 parser.error(
1183 "Option --buildbot/--remote-trybot requires the following "
1184 "binaries which couldn't be found in $PATH: %s"
1185 % (", ".join(missing))
1186 )
Brian Harring351ce442012-03-09 16:38:14 -08001187
Alex Klein1699fab2022-09-08 08:46:06 -06001188 if options.reference_repo:
1189 options.reference_repo = os.path.abspath(options.reference_repo)
David Jamesdac7a912013-11-18 11:14:44 -08001190
Alex Klein1699fab2022-09-08 08:46:06 -06001191 # Sanity check of buildroot- specifically that it's not pointing into the
1192 # midst of an existing repo since git-repo doesn't support nesting.
1193 if not repository.IsARepoRoot(options.buildroot) and git.FindRepoDir(
1194 options.buildroot
1195 ):
1196 cros_build_lib.Die(
1197 "Configured buildroot %s is a subdir of an existing repo checkout."
1198 % options.buildroot
1199 )
Brian Harring3fec5a82012-03-01 05:57:03 -08001200
Alex Klein1699fab2022-09-08 08:46:06 -06001201 if not options.log_dir:
1202 options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
Chris Sosab5ea3b42012-10-25 15:25:20 -07001203
Alex Klein1699fab2022-09-08 08:46:06 -06001204 log_file = None
1205 if options.tee:
1206 log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
1207 osutils.SafeMakedirs(options.log_dir)
1208 _BackupPreviousLog(log_file)
Brian Harringd166aaf2012-05-14 18:31:53 -07001209
Alex Klein1699fab2022-09-08 08:46:06 -06001210 with cros_build_lib.ContextManagerStack() as stack:
1211 # Preserve chromite; we might be running from there!
1212 options.preserve_paths = set(["chromite"])
1213 if log_file is not None:
1214 # We don't want the critical section to try to clean up the tee process,
1215 # so we run Tee (forked off) outside of it. This prevents a deadlock
1216 # because the Tee process only exits when its pipe is closed, and the
1217 # critical section accidentally holds on to that file handle.
1218 stack.Add(tee.Tee, log_file)
1219 options.preserve_paths.add(_DEFAULT_LOG_DIR)
David Jamescebc7272013-07-17 16:45:05 -07001220
Alex Klein1699fab2022-09-08 08:46:06 -06001221 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
1222 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -07001223
Alex Klein1699fab2022-09-08 08:46:06 -06001224 if not options.resume:
1225 # If we're in resume mode, use our parents tempdir rather than
1226 # nesting another layer.
1227 stack.Add(osutils.TempDir, prefix="cbuildbot-tmp", set_global=True)
1228 logging.debug("Cbuildbot tempdir is %r.", os.environ.get("TMP"))
Brian Harringd166aaf2012-05-14 18:31:53 -07001229
Alex Klein1699fab2022-09-08 08:46:06 -06001230 if options.cgroups:
1231 stack.Add(cgroups.SimpleContainChildren, "cbuildbot")
Brian Harringa184efa2012-03-04 11:51:25 -08001232
Alex Klein1699fab2022-09-08 08:46:06 -06001233 # Mark everything between EnforcedCleanupSection and here as having to
1234 # be rolled back via the contextmanager cleanup handlers. This
1235 # ensures that sudo bits cannot outlive cbuildbot, that anything
1236 # cgroups would kill gets killed, etc.
1237 stack.Add(critical_section.ForkWatchdog)
Brian Harringd166aaf2012-05-14 18:31:53 -07001238
Alex Klein1699fab2022-09-08 08:46:06 -06001239 if options.mock_slave_status is not None:
1240 with open(options.mock_slave_status, "r") as f:
1241 mock_statuses = pickle.load(f)
1242 for key, value in mock_statuses.items():
1243 mock_statuses[key] = builder_status_lib.BuilderStatus(
1244 **value
1245 )
1246 stack.Add(
1247 _ObjectMethodPatcher,
Mike Nicholsa1414162021-04-22 20:07:22 +00001248 completion_stages.MasterSlaveSyncCompletionStage,
Alex Klein1699fab2022-09-08 08:46:06 -06001249 "_FetchSlaveStatuses",
1250 return_value=mock_statuses,
1251 )
Aviv Keshetcf9c2722014-02-25 15:15:10 -08001252
Alex Klein1699fab2022-09-08 08:46:06 -06001253 stack.Add(_SetupConnections, options, build_config)
1254 retry_stats.SetupStats()
Aviv Keshet2982af52014-08-13 16:07:57 -07001255
Alex Klein1699fab2022-09-08 08:46:06 -06001256 timeout_display_message = (
1257 "This build has reached the timeout deadline set by the master. "
1258 "Either this stage or a previous one took too long (see stage "
1259 "timing historical summary in ReportStage) or the build failed "
1260 "to start on time."
1261 )
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -08001262
Alex Klein1699fab2022-09-08 08:46:06 -06001263 if options.timeout > 0:
1264 stack.Add(
1265 timeout_util.FatalTimeout,
1266 options.timeout,
1267 timeout_display_message,
1268 )
1269 try:
1270 _RunBuildStagesWrapper(options, site_config, build_config)
1271 except failures_lib.ExitEarlyException as ex:
1272 # This build finished successfully. Do not re-raise ExitEarlyException.
1273 logging.info("One stage exited early: %s", ex)