blob: b5864a27370b5a02d4fa67b9156f4825d6c59f68 [file] [log] [blame]
Mike Frysingere58c0e22017-10-04 15:43:30 -04001# -*- coding: utf-8 -*-
Mike Frysingerd6925b52012-07-16 16:11:00 -04002# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
Brian Harring3fec5a82012-03-01 05:57:03 -08003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Main builder code for Chromium OS.
7
8Used by Chromium OS buildbot configuration for all Chromium OS builds including
9full and pre-flight-queue builds.
10"""
11
Mike Frysinger383367e2014-09-16 15:06:17 -040012from __future__ import print_function
13
Aviv Keshet593014d2017-07-18 17:28:25 -070014import distutils.version # pylint: disable=import-error,no-name-in-module
Brian Harring3fec5a82012-03-01 05:57:03 -080015import glob
Aviv Keshet669eb5e2014-06-23 08:53:01 -070016import json
Mike Frysingerb0b0caa2015-11-07 01:05:18 -050017import optparse # pylint: disable=deprecated-module
Brian Harring3fec5a82012-03-01 05:57:03 -080018import os
Aviv Keshetcf9c2722014-02-25 15:15:10 -080019import pickle
Brian Harring3fec5a82012-03-01 05:57:03 -080020import sys
21
Mike Frysingere4d68c22015-02-04 21:26:24 -050022from chromite.cbuildbot import builders
Don Garrett88b8d782014-05-13 17:30:55 -070023from chromite.cbuildbot import cbuildbot_run
Don Garrett88b8d782014-05-13 17:30:55 -070024from chromite.cbuildbot import repository
Aviv Keshet420de512015-05-18 14:28:48 -070025from chromite.cbuildbot import topology
Don Garrett88b8d782014-05-13 17:30:55 -070026from chromite.cbuildbot.stages import completion_stages
Ningning Xiaf342b952017-02-15 14:13:33 -080027from chromite.lib import builder_status_lib
Aviv Keshet2982af52014-08-13 16:07:57 -070028from chromite.lib import cidb
Brian Harringc92a7012012-02-29 10:11:34 -080029from chromite.lib import cgroups
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
Ralph Nathan91874ca2015-03-19 13:29:41 -070035from chromite.lib import cros_logging as logging
Ningning Xia6a718052016-12-22 10:08:15 -080036from chromite.lib import failures_lib
David James97d95872012-11-16 15:09:56 -080037from chromite.lib import git
Stefan Zagerd49d9ff2014-08-15 21:33:37 -070038from chromite.lib import gob_util
Brian Harringaf019fb2012-05-10 15:06:13 -070039from chromite.lib import osutils
David James6450a0a2012-12-04 07:59:53 -080040from chromite.lib import parallel
Don Garrettb4318362014-10-03 15:49:36 -070041from chromite.lib import retry_stats
Brian Harring3fec5a82012-03-01 05:57:03 -080042from chromite.lib import sudo
Michael Mortensen3e86c1e2019-11-21 15:51:54 -070043from chromite.lib import tee
David James3432acd2013-11-27 10:02:18 -080044from chromite.lib import timeout_util
Paul Hobbsfcf10342015-12-29 15:52:31 -080045from chromite.lib import ts_mon_config
Dhanya Ganesh39a48a82018-12-06 16:01:11 -070046from chromite.lib.buildstore import BuildStore
Brian Harring3fec5a82012-03-01 05:57:03 -080047
Ryan Cuiadd49122012-03-21 22:19:58 -070048
Brian Harring3fec5a82012-03-01 05:57:03 -080049_DEFAULT_LOG_DIR = 'cbuildbot_logs'
50_BUILDBOT_LOG_FILE = 'cbuildbot.log'
51_DEFAULT_EXT_BUILDROOT = 'trybot'
52_DEFAULT_INT_BUILDROOT = 'trybot-internal'
Brian Harring351ce442012-03-09 16:38:14 -080053_BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
Ryan Cui1c13a252012-10-16 15:00:16 -070054_API_VERSION_ATTR = 'api_version'
Brian Harring3fec5a82012-03-01 05:57:03 -080055
56
Brian Harring3fec5a82012-03-01 05:57:03 -080057def _BackupPreviousLog(log_file, backup_limit=25):
58 """Rename previous log.
59
60 Args:
61 log_file: The absolute path to the previous log.
Aviv Keshet9e4236b2013-12-13 13:07:50 -080062 backup_limit: Maximum number of old logs to keep.
Brian Harring3fec5a82012-03-01 05:57:03 -080063 """
64 if os.path.exists(log_file):
65 old_logs = sorted(glob.glob(log_file + '.*'),
66 key=distutils.version.LooseVersion)
67
68 if len(old_logs) >= backup_limit:
69 os.remove(old_logs[0])
70
71 last = 0
72 if old_logs:
73 last = int(old_logs.pop().rpartition('.')[2])
74
75 os.rename(log_file, log_file + '.' + str(last + 1))
76
Ryan Cui5616a512012-08-17 13:39:36 -070077
Gaurav Shah298aa372014-01-31 09:27:24 -080078def _IsDistributedBuilder(options, chrome_rev, build_config):
79 """Determines whether the builder should be a DistributedBuilder.
80
81 Args:
82 options: options passed on the commandline.
83 chrome_rev: Chrome revision to build.
84 build_config: Builder configuration dictionary.
85
86 Returns:
87 True if the builder should be a distributed_builder
88 """
Mike Frysingerc3e88fa2020-03-26 02:49:02 -040089 if not options.buildbot:
Gaurav Shah298aa372014-01-31 09:27:24 -080090 return False
91 elif chrome_rev in (constants.CHROME_REV_TOT,
92 constants.CHROME_REV_LOCAL,
93 constants.CHROME_REV_SPEC):
94 # We don't do distributed logic to TOT Chrome PFQ's, nor local
95 # chrome roots (e.g. chrome try bots)
96 # TODO(davidjames): Update any builders that rely on this logic to use
97 # manifest_version=False instead.
98 return False
99 elif build_config['manifest_version']:
100 return True
101
102 return False
103
104
Don Garretta52a5b02015-06-02 14:52:57 -0700105def _RunBuildStagesWrapper(options, site_config, build_config):
Brian Harring3fec5a82012-03-01 05:57:03 -0800106 """Helper function that wraps RunBuildStages()."""
Lann Martinffb95162018-08-28 12:02:54 -0600107 logging.info('cbuildbot was executed with args %s',
Ralph Nathan03047282015-03-23 11:09:32 -0700108 cros_build_lib.CmdToStr(sys.argv))
Brian Harring3fec5a82012-03-01 05:57:03 -0800109
David Jamesa0a664e2013-02-13 09:52:01 -0800110 chrome_rev = build_config['chrome_rev']
111 if options.chrome_rev:
112 chrome_rev = options.chrome_rev
113 if chrome_rev == constants.CHROME_REV_TOT:
Stefan Zagerd49d9ff2014-08-15 21:33:37 -0700114 options.chrome_version = gob_util.GetTipOfTrunkRevision(
115 constants.CHROMIUM_GOB_URL)
David Jamesa0a664e2013-02-13 09:52:01 -0800116 options.chrome_rev = constants.CHROME_REV_SPEC
117
David James4a404a52013-02-19 13:07:59 -0800118 # If it's likely we'll need to build Chrome, fetch the source.
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500119 if build_config['sync_chrome'] is None:
David Jameseecba232014-06-11 11:35:11 -0700120 options.managed_chrome = (
121 chrome_rev != constants.CHROME_REV_LOCAL and
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500122 (not build_config['usepkg_build_packages'] or chrome_rev or
Mike Frysinger8b1bd822017-08-11 16:11:42 -0400123 build_config['profile']))
Mike Frysingerf4d9ab82013-03-05 19:38:05 -0500124 else:
125 options.managed_chrome = build_config['sync_chrome']
David James2333c182013-02-13 16:16:15 -0800126
Don Garrett94c603f2019-02-01 16:26:43 -0800127 chrome_root_mgr = None
David James2333c182013-02-13 16:16:15 -0800128 if options.managed_chrome:
Don Garrett94c603f2019-02-01 16:26:43 -0800129 # Create a temp directory for syncing Chrome source.
130 chrome_root_mgr = osutils.TempDir(prefix='chrome_root_')
131 options.chrome_root = chrome_root_mgr.tempdir
David James2333c182013-02-13 16:16:15 -0800132
Matt Tennant95a42ad2013-12-27 15:38:36 -0800133 # We are done munging options values, so freeze options object now to avoid
134 # further abuse of it.
135 # TODO(mtennant): one by one identify each options value override and see if
136 # it can be handled another way. Try to push this freeze closer and closer
137 # to the start of the script (e.g. in or after _PostParseCheck).
138 options.Freeze()
139
Don Garrett5ba2c452018-01-30 16:34:41 -0800140 metadata_dump_dict = {
141 # A detected default has been set before now if it wasn't explicit.
142 'branch': options.branch,
143 }
144 if options.metadata_dump:
145 with open(options.metadata_dump, 'r') as metadata_file:
146 metadata_dump_dict = json.loads(metadata_file.read())
147
Matt Tennant0940c382014-01-21 20:43:55 -0800148 with parallel.Manager() as manager:
Don Garretta52a5b02015-06-02 14:52:57 -0700149 builder_run = cbuildbot_run.BuilderRun(
150 options, site_config, build_config, manager)
Dhanya Ganesh39a48a82018-12-06 16:01:11 -0700151 buildstore = BuildStore()
Aviv Keshet669eb5e2014-06-23 08:53:01 -0700152 if metadata_dump_dict:
153 builder_run.attrs.metadata.UpdateWithDict(metadata_dump_dict)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500154
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500155 if builder_run.config.builder_class_name is None:
Don Garrett56e6ed32015-06-23 16:52:20 -0700156 # TODO: This should get relocated to chromeos_config.
Mike Frysingere4d68c22015-02-04 21:26:24 -0500157 if _IsDistributedBuilder(options, chrome_rev, build_config):
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500158 builder_cls_name = 'simple_builders.DistributedBuilder'
Mike Frysingere4d68c22015-02-04 21:26:24 -0500159 else:
Mike Frysinger05c5faf2015-02-04 21:46:46 -0500160 builder_cls_name = 'simple_builders.SimpleBuilder'
161 builder_cls = builders.GetBuilderClass(builder_cls_name)
Dhanya Ganesh39a48a82018-12-06 16:01:11 -0700162 builder = builder_cls(builder_run, buildstore)
Matt Tennant0940c382014-01-21 20:43:55 -0800163 else:
Dhanya Ganesh39a48a82018-12-06 16:01:11 -0700164 builder = builders.Builder(builder_run, buildstore)
Mike Frysingere4d68c22015-02-04 21:26:24 -0500165
Don Garrett94c603f2019-02-01 16:26:43 -0800166 try:
167 if not builder.Run():
168 sys.exit(1)
169 finally:
170 if chrome_root_mgr:
171 chrome_root_mgr.Cleanup()
Brian Harring3fec5a82012-03-01 05:57:03 -0800172
173
Brian Harring3fec5a82012-03-01 05:57:03 -0800174def _CheckChromeVersionOption(_option, _opt_str, value, parser):
175 """Upgrade other options based on chrome_version being passed."""
176 value = value.strip()
177
178 if parser.values.chrome_rev is None and value:
179 parser.values.chrome_rev = constants.CHROME_REV_SPEC
180
181 parser.values.chrome_version = value
182
183
184def _CheckChromeRootOption(_option, _opt_str, value, parser):
185 """Validate and convert chrome_root to full-path form."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800186 if parser.values.chrome_rev is None:
187 parser.values.chrome_rev = constants.CHROME_REV_LOCAL
188
Ryan Cui5ba7e152012-05-10 14:36:52 -0700189 parser.values.chrome_root = value
Brian Harring3fec5a82012-03-01 05:57:03 -0800190
191
David Jamesac8c2a72013-02-13 18:44:33 -0800192def FindCacheDir(_parser, _options):
Brian Harringae0a5322012-09-15 01:46:51 -0700193 return None
194
195
Ryan Cui5ba7e152012-05-10 14:36:52 -0700196class CustomGroup(optparse.OptionGroup):
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800197 """Custom option group which supports arguments passed-through to trybot."""
David Jameseecba232014-06-11 11:35:11 -0700198
Ryan Cui5ba7e152012-05-10 14:36:52 -0700199 def add_remote_option(self, *args, **kwargs):
200 """For arguments that are passed-through to remote trybot."""
201 return optparse.OptionGroup.add_option(self, *args,
202 remote_pass_through=True,
203 **kwargs)
204
205
Ryan Cui1c13a252012-10-16 15:00:16 -0700206class CustomOption(commandline.FilteringOption):
207 """Subclass FilteringOption class to implement pass-through and api."""
Ryan Cui5ba7e152012-05-10 14:36:52 -0700208
Ryan Cui5ba7e152012-05-10 14:36:52 -0700209 def __init__(self, *args, **kwargs):
210 # The remote_pass_through argument specifies whether we should directly
211 # pass the argument (with its value) onto the remote trybot.
212 self.pass_through = kwargs.pop('remote_pass_through', False)
Ryan Cui1c13a252012-10-16 15:00:16 -0700213 self.api_version = int(kwargs.pop('api', '0'))
214 commandline.FilteringOption.__init__(self, *args, **kwargs)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700215
Ryan Cui5ba7e152012-05-10 14:36:52 -0700216
Ryan Cui1c13a252012-10-16 15:00:16 -0700217class CustomParser(commandline.FilteringParser):
Gregory Meinke5a25ac72019-01-31 13:20:51 -0700218 """Custom option parser which supports arguments passed-through to trybot"""
Matt Tennante8179042013-10-01 15:47:32 -0700219
Brian Harringb6cf9142012-09-01 20:43:17 -0700220 DEFAULT_OPTION_CLASS = CustomOption
221
222 def add_remote_option(self, *args, **kwargs):
223 """For arguments that are passed-through to remote trybot."""
Ryan Cui1c13a252012-10-16 15:00:16 -0700224 return self.add_option(*args, remote_pass_through=True, **kwargs)
Brian Harringb6cf9142012-09-01 20:43:17 -0700225
226
Don Garrett86881cb2017-02-15 15:41:55 -0800227def CreateParser():
228 """Expose _CreateParser publicly."""
229 # Name _CreateParser is needed for commandline library.
230 return _CreateParser()
231
232
Brian Harring3fec5a82012-03-01 05:57:03 -0800233def _CreateParser():
Ryan Cui16d9e1f2012-05-11 10:50:18 -0700234 """Generate and return the parser with all the options."""
Brian Harring3fec5a82012-03-01 05:57:03 -0800235 # Parse options
David Jameseecba232014-06-11 11:35:11 -0700236 usage = 'usage: %prog [options] buildbot_config [buildbot_config ...]'
Brian Harringae0a5322012-09-15 01:46:51 -0700237 parser = CustomParser(usage=usage, caching=FindCacheDir)
Brian Harring3fec5a82012-03-01 05:57:03 -0800238
239 # Main options
Ryan Cuie1e4e662012-05-21 16:39:46 -0700240 parser.add_remote_option('-b', '--branch',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900241 help='The manifest branch to test. The branch to '
242 'check the buildroot out to.')
243 parser.add_option('-r', '--buildroot', type='path', dest='buildroot',
244 help='Root directory where source is checked out to, and '
245 'where the build occurs. For external build configs, '
246 "defaults to 'trybot' directory at top level of your "
247 'repo-managed checkout.')
Don Garrett10210fa2018-06-29 18:25:41 -0700248 parser.add_option('--workspace', type='path',
249 api=constants.REEXEC_API_WORKSPACE,
250 help='Root directory for a secondary checkout .')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900251 parser.add_option('--bootstrap-dir', type='path',
Prathmesh Prabhu867c1172015-06-02 17:57:59 -0700252 help='Bootstrapping cbuildbot may involve checking out '
253 'multiple copies of chromite. All these checkouts '
254 'will be contained in the directory specified here. '
255 'Default:%s' % osutils.GetGlobalTempDir())
Hidehiko Abe863d7882017-03-09 22:27:28 +0900256 parser.add_remote_option('--android_rev', type='choice',
David Riley486b2612016-02-22 19:59:26 -0800257 choices=constants.VALID_ANDROID_REVISIONS,
258 help=('Revision of Android to use, of type [%s]'
259 % '|'.join(constants.VALID_ANDROID_REVISIONS)))
Hidehiko Abe863d7882017-03-09 22:27:28 +0900260 parser.add_remote_option('--chrome_rev', type='choice',
David Riley486b2612016-02-22 19:59:26 -0800261 choices=constants.VALID_CHROME_REVISIONS,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700262 help=('Revision of Chrome to use, of type [%s]'
263 % '|'.join(constants.VALID_CHROME_REVISIONS)))
Hidehiko Abe863d7882017-03-09 22:27:28 +0900264 parser.add_remote_option('--profile',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700265 help='Name of profile to sub-specify board variant.')
Hidehiko Abe95d7cf62017-03-07 23:34:30 +0900266 # TODO(crbug.com/279618): Running GOMA is under development. Following
267 # flags are added for development purpose due to repository dependency,
268 # but not officially supported yet.
269 parser.add_option('--goma_dir', type='path',
270 api=constants.REEXEC_API_GOMA,
271 help='Specify a directory containing goma. When this is '
272 'set, GOMA is used to build Chrome.')
Yoshisato Yanagisawa13d55b32019-08-15 09:44:44 +0900273 parser.add_option('--chromeos_goma_dir', type='path',
274 api=constants.REEXEC_API_CHROMEOS_GOMA_DIR,
275 help='Specify a directory containing goma for '
276 'build package.')
Hidehiko Abe95d7cf62017-03-07 23:34:30 +0900277 parser.add_option('--goma_client_json', type='path',
278 api=constants.REEXEC_API_GOMA,
279 help='Specify a service-account-goma-client.json path. '
280 'The file is needed on bots to run GOMA.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800281
Don Garrett211df8c2017-09-06 13:33:02 -0700282 group = CustomGroup(
283 parser,
284 'Deprecated Options')
285
286 parser.add_option('--local', action='store_true', default=False,
Don Garrettcc0ee522017-09-13 14:28:42 -0700287 help='Deprecated. See cros tryjob.')
Don Garrett211df8c2017-09-06 13:33:02 -0700288 parser.add_option('--remote', action='store_true', default=False,
Don Garrettcc0ee522017-09-13 14:28:42 -0700289 help='Deprecated. See cros tryjob.')
Don Garrett211df8c2017-09-06 13:33:02 -0700290
Ryan Cuif4f84be2012-07-09 18:50:41 -0700291 #
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400292 # Patch selection options.
293 #
294
295 group = CustomGroup(
296 parser,
297 'Patch Options')
298
Mike Frysingerdad205d2017-08-11 16:00:14 -0400299 group.add_remote_option('-g', '--gerrit-patches', action='split_extend',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900300 type='string', default=[],
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400301 metavar="'Id1 *int_Id2...IdN'",
Hidehiko Abe863d7882017-03-09 22:27:28 +0900302 help='Space-separated list of short-form Gerrit '
303 "Change-Id's or change numbers to patch. "
304 "Please prepend '*' to internal Change-Id's")
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400305
Mike Frysinger68893242017-08-11 14:16:39 -0400306 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400307
308 #
309 # Remote trybot options.
310 #
311
312 group = CustomGroup(
313 parser,
Don Garrett211df8c2017-09-06 13:33:02 -0700314 'Options used to configure tryjob behavior.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900315 group.add_remote_option('--hwtest', action='store_true', default=False,
David Jameseecba232014-06-11 11:35:11 -0700316 help='Run the HWTest stage (tests on real hardware)')
Mike Frysingerdad205d2017-08-11 16:00:14 -0400317 group.add_remote_option('--channel', action='split_extend', dest='channels',
Don Garrett4bb21682014-03-03 16:16:23 -0800318 default=[],
Hidehiko Abe863d7882017-03-09 22:27:28 +0900319 help='Specify a channel for a payloads trybot. Can '
320 'be specified multiple times. No valid for '
321 'non-payloads configs.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400322
Mike Frysinger68893242017-08-11 14:16:39 -0400323 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400324
325 #
326 # Advanced options.
Ryan Cuif4f84be2012-07-09 18:50:41 -0700327 #
328
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700329 group = CustomGroup(
Brian Harring3fec5a82012-03-01 05:57:03 -0800330 parser,
331 'Advanced Options',
332 'Caution: use these options at your own risk.')
333
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400334 group.add_remote_option('--bootstrap-args', action='append', default=[],
Hidehiko Abe863d7882017-03-09 22:27:28 +0900335 help='Args passed directly to the bootstrap re-exec '
336 'to skip verification by the bootstrap code')
337 group.add_remote_option('--buildbot', action='store_true', dest='buildbot',
Bernie Thompson63f30062016-12-21 15:24:25 -0800338 default=False,
339 help='This is running on a buildbot. '
340 'This can be used to make a build operate '
341 'like an official builder, e.g. generate '
342 'new version numbers and archive official '
343 'artifacts and such. This should only be '
344 'used if you are confident in what you are '
345 'doing, as it will make automated commits.')
Don Garrett07d46262017-04-13 12:06:44 -0700346 parser.add_remote_option('--repo-cache', type='path', dest='_repo_cache',
347 help='Present for backwards compatibility, ignored.')
Prathmesh Prabhu51d774f2015-07-17 15:11:49 -0700348 group.add_remote_option('--no-buildbot-tags', action='store_false',
349 dest='enable_buildbot_tags', default=True,
350 help='Suppress buildbot specific tags from log '
351 'output. This is used to hide recursive '
352 'cbuilbot runs on the waterfall.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900353 group.add_remote_option('--buildnumber', type='int', default=0,
354 help='build number')
355 group.add_option('--chrome_root', action='callback', type='path',
356 callback=_CheckChromeRootOption,
357 help='Local checkout of Chrome to use.')
358 group.add_remote_option('--chrome_version', action='callback', type='string',
359 dest='chrome_version',
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700360 callback=_CheckChromeVersionOption,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900361 help='Used with SPEC logic to force a particular '
362 'git revision of chrome rather than the '
363 'latest.')
364 group.add_remote_option('--clobber', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700365 help='Clears an old checkout before syncing')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400366 group.add_remote_option('--latest-toolchain', action='store_true',
367 default=False,
368 help='Use the latest toolchain.')
Ryan Cui5ba7e152012-05-10 14:36:52 -0700369 parser.add_option('--log_dir', dest='log_dir', type='path',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900370 help='Directory where logs are stored.')
371 group.add_remote_option('--maxarchives', type='int',
372 dest='max_archive_builds', default=3,
David Jameseecba232014-06-11 11:35:11 -0700373 help='Change the local saved build count limit.')
Ryan Cuibbd3d4b2012-08-17 12:20:37 -0700374 parser.add_remote_option('--manifest-repo-url',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900375 help='Overrides the default manifest repo url.')
David James565bc9a2013-04-08 14:54:45 -0700376 group.add_remote_option('--compilecheck', action='store_true', default=False,
377 help='Only verify compilation and unit tests.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700378 group.add_remote_option('--noarchive', action='store_false', dest='archive',
379 default=True, help="Don't run archive stage.")
Ryan Cuif7f24692012-05-18 16:35:33 -0700380 group.add_remote_option('--nobootstrap', action='store_false',
381 dest='bootstrap', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900382 help="Don't checkout and run from a standalone "
383 'chromite repo.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700384 group.add_remote_option('--nobuild', action='store_false', dest='build',
385 default=True,
386 help="Don't actually build (for cbuildbot dev)")
387 group.add_remote_option('--noclean', action='store_false', dest='clean',
388 default=True, help="Don't clean the buildroot")
Ryan Cuif7f24692012-05-18 16:35:33 -0700389 group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
390 default=True,
391 help='Disable cbuildbots usage of cgroups.')
Ryan Cui3ea98e02013-08-07 16:01:48 -0700392 group.add_remote_option('--nochromesdk', action='store_false',
393 dest='chrome_sdk', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900394 help="Don't run the ChromeSDK stage which builds "
395 'Chrome outside of the chroot.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700396 group.add_remote_option('--noprebuilts', action='store_false',
397 dest='prebuilts', default=True,
398 help="Don't upload prebuilts.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700399 group.add_remote_option('--nopatch', action='store_false',
400 dest='postsync_patch', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900401 help="Don't run PatchChanges stage. This does not "
402 'disable patching in of chromite patches '
403 'during BootstrapStage.')
Don Garrett82c0ae82014-02-03 18:25:11 -0800404 group.add_remote_option('--nopaygen', action='store_false',
405 dest='paygen', default=True,
406 help="Don't generate payloads.")
Ryan Cui88b901c2013-06-21 11:35:30 -0700407 group.add_remote_option('--noreexec', action='store_false',
408 dest='postsync_reexec', default=True,
409 help="Don't reexec into the buildroot after syncing.")
Hidehiko Abe863d7882017-03-09 22:27:28 +0900410 group.add_remote_option('--nosdk', action='store_true', default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400411 help='Re-create the SDK from scratch.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700412 group.add_remote_option('--nosync', action='store_false', dest='sync',
413 default=True, help="Don't sync before building.")
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700414 group.add_remote_option('--notests', action='store_false', dest='tests',
415 default=True,
xixuan7774ba82017-06-22 16:04:00 -0700416 help='Override values from buildconfig, run no '
417 'tests, and build no autotest and artifacts.')
418 group.add_remote_option('--novmtests', action='store_false', dest='vmtests',
419 default=True,
420 help='Override values from buildconfig, run no '
421 'vmtests.')
Nam T. Nguyenc93f1342014-07-11 14:40:54 -0700422 group.add_remote_option('--noimagetests', action='store_false',
423 dest='image_test', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900424 help='Override values from buildconfig and run no '
425 'image tests.')
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700426 group.add_remote_option('--nouprev', action='store_false', dest='uprev',
427 default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900428 help='Override values from buildconfig and never '
429 'uprev.')
430 group.add_option('--reference-repo',
431 help='Reuse git data stored in an existing repo '
432 'checkout. This can drastically reduce the network '
433 'time spent setting up the trybot checkout. By '
434 "default, if this option isn't given but cbuildbot "
435 'is invoked from a repo checkout, cbuildbot will '
436 'use the repo root.')
Ryan Cuicedd8a52012-03-22 02:28:35 -0700437 group.add_option('--resume', action='store_true', default=False,
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700438 help='Skip stages already successfully completed.')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900439 group.add_remote_option('--timeout', type='int', default=0,
440 help='Specify the maximum amount of time this job '
441 'can run for, at which point the build will be '
442 'aborted. If set to zero, then there is no '
443 'timeout.')
444 group.add_remote_option('--version', dest='force_version',
445 help='Used with manifest logic. Forces use of this '
446 'version rather than create or get latest. '
447 'Examples: 4815.0.0-rc1, 4815.1.2')
448 group.add_remote_option('--git-cache-dir', type='path',
Don Garrettbb79be92016-09-27 11:14:07 -0700449 api=constants.REEXEC_API_GIT_CACHE_DIR,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900450 help='Specify the cache directory to store the '
451 'project caches populated by the git-cache '
452 'tool. Bootstrap the projects based on the git '
453 'cache files instead of fetching them directly '
454 'from the GoB servers.')
David Burger33c7d3c2020-02-19 09:57:54 -0700455 group.add_remote_option('--chrome-preload-dir', type='path',
456 api=constants.REEXEC_API_CHROME_PRELOAD_DIR,
457 help='Specify a preloaded chrome source cache '
458 'directory populated by the git-cache tool. '
459 'Bootstrap chrome based on the cached files '
460 'instead of fetching them directly from the GoB '
461 'servers. When both this argument and '
462 '--git-cache-dir are provided this value will '
463 'be preferred for the chrome source cache.')
Don Garretta90f0142018-02-28 14:25:19 -0800464 group.add_remote_option('--debug-cidb', action='store_true', default=False,
465 help='Force Debug CIDB to be used.')
Gregory Meinke5a25ac72019-01-31 13:20:51 -0700466 # cbuildbot ChromeOS Findit options
467 group.add_remote_option('--cbb_build_packages', action='split_extend',
468 dest='cbb_build_packages',
469 default=[],
470 help='Specify an explicit list of packages to build '
471 'for integration with Findit.')
Gregory Meinkead6d5672019-02-19 08:41:12 -0700472 group.add_remote_option('--cbb_snapshot_revision', type='string',
473 dest='cbb_snapshot_revision', default=None,
474 help='Snapshot manifest revision to sync to '
475 'for building.')
Chris McDonald2921fd42020-02-25 14:30:06 -0700476 group.add_remote_option(
477 '--no-publish-prebuilt-confs',
478 dest='publish',
479 action='store_false',
480 default=True,
481 help="Don't publish git commits to prebuilt.conf or sdk_version.conf")
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400482
Mike Frysinger68893242017-08-11 14:16:39 -0400483 parser.add_argument_group(group)
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400484
485 #
486 # Internal options.
487 #
488
489 group = CustomGroup(
490 parser,
Mike Frysinger34db8692013-11-11 14:54:08 -0500491 'Internal Chromium OS Build Team Options',
492 'Caution: these are for meant for the Chromium OS build team only')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400493
494 group.add_remote_option('--archive-base', type='gs_path',
Hidehiko Abe863d7882017-03-09 22:27:28 +0900495 help='Base GS URL (gs://<bucket_name>/<path>) to '
496 'upload archive artifacts to')
David Jameseecba232014-06-11 11:35:11 -0700497 group.add_remote_option(
Hidehiko Abe863d7882017-03-09 22:27:28 +0900498 '--cq-gerrit-query', dest='cq_gerrit_override',
499 help='If given, this gerrit query will be used to find what patches to '
500 "test, rather than the normal 'CommitQueue>=1 AND Verified=1 AND "
501 "CodeReview=2' query it defaults to. Use with care- note "
502 'additionally this setting only has an effect if the buildbot '
503 "target is a cq target, and we're in buildbot mode.")
504 group.add_option('--pass-through', action='append', type='string',
505 dest='pass_through_args', default=[])
506 group.add_option('--reexec-api-version', action='store_true',
507 dest='output_api_version', default=False,
508 help='Used for handling forwards/backwards compatibility '
509 'with --resume and --bootstrap')
510 group.add_option('--remote-trybot', action='store_true', default=False,
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400511 help='Indicates this is running on a remote trybot machine')
Hidehiko Abe863d7882017-03-09 22:27:28 +0900512 group.add_option('--buildbucket-id',
Don Garrettb01a8e62017-12-11 17:47:18 -0800513 api=constants.REEXEC_API_GOMA, # Approximate.
Hidehiko Abe863d7882017-03-09 22:27:28 +0900514 help='The unique ID in buildbucket of current build '
515 'generated by buildbucket.')
Mike Frysingerdad205d2017-08-11 16:00:14 -0400516 group.add_remote_option('--remote-patches', action='split_extend', default=[],
Hidehiko Abe863d7882017-03-09 22:27:28 +0900517 help='Patches uploaded by the trybot client when '
518 'run using the -p option')
Brian Harringf611e6e2012-07-17 18:47:44 -0700519 # Note the default here needs to be hardcoded to 3; that is the last version
520 # that lacked this functionality.
Hidehiko Abe863d7882017-03-09 22:27:28 +0900521 group.add_option('--remote-version', type='int', default=3,
Don Garrettbb965dc2017-09-14 17:24:18 -0700522 help='Deprecated and ignored.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400523 group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT)
524 group.add_remote_option('--test-bootstrap', action='store_true',
525 default=False,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900526 help='Causes cbuildbot to bootstrap itself twice, '
527 'in the sequence A->B->C: A(unpatched) patches '
528 'and bootstraps B; B patches and bootstraps C')
529 group.add_remote_option('--validation_pool',
530 help='Path to a pickled validation pool. Intended '
531 'for use only with the commit queue.')
532 group.add_remote_option('--metadata_dump',
533 help='Path to a json dumped metadata file. This '
534 'will be used as the initial metadata.')
535 group.add_remote_option('--master-build-id', type='int',
Aviv Keshetacf4cfb2014-07-30 12:31:22 -0700536 api=constants.REEXEC_API_MASTER_BUILD_ID,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900537 help='cidb build id of the master build to this '
538 'slave build.')
Dhanya Ganesh6e0e0282019-03-06 16:06:16 -0700539 group.add_remote_option('--master-buildbucket-id',
540 api=constants.REEXEC_API_MASTER_BUILDBUCKET_ID,
541 help='buildbucket id of the master build to this '
542 'slave build.')
Ningning Xia6c381652017-10-24 16:03:29 -0700543 # TODO(nxia): crbug.com/778838
544 # cbuildbot doesn't use pickle files anymore, remove this.
Hidehiko Abe863d7882017-03-09 22:27:28 +0900545 group.add_remote_option('--mock-slave-status',
546 metavar='MOCK_SLAVE_STATUS_PICKLE_FILE',
547 help='Override the result of the _FetchSlaveStatuses '
548 'method of MasterSlaveSyncCompletionStage, by '
549 'specifying a file with a pickle of the result '
550 'to be returned.')
Benjamin Gordon0443cb82018-04-17 12:38:49 -0600551 group.add_option('--previous-build-state', type='string', default='',
552 api=constants.REEXEC_API_PREVIOUS_BUILD_STATE,
553 help='A base64-encoded BuildSummary object describing the '
554 'previous build run on the same build machine.')
Mike Frysinger81af6ef2013-04-03 02:24:09 -0400555
Mike Frysinger68893242017-08-11 14:16:39 -0400556 parser.add_argument_group(group)
Ryan Cuif4f84be2012-07-09 18:50:41 -0700557
558 #
Brian Harring3fec5a82012-03-01 05:57:03 -0800559 # Debug options
Ryan Cuif4f84be2012-07-09 18:50:41 -0700560 #
Brian Harringfec89fe2012-09-23 07:30:54 -0700561 # Temporary hack; in place till --dry-run replaces --debug.
Mike Frysinger27e21b72018-07-12 14:20:21 -0400562 # pylint: disable=protected-access
Brian Harring009db502012-10-10 02:21:37 -0700563 group = parser.debug_group
Brian Harringfec89fe2012-09-23 07:30:54 -0700564 debug = [x for x in group.option_list if x._long_opts == ['--debug']][0]
David Jameseecba232014-06-11 11:35:11 -0700565 debug.help += ' Currently functions as --dry-run in addition.'
Brian Harringfec89fe2012-09-23 07:30:54 -0700566 debug.pass_through = True
Brian Harring3fec5a82012-03-01 05:57:03 -0800567 group.add_option('--notee', action='store_false', dest='tee', default=True,
Hidehiko Abe863d7882017-03-09 22:27:28 +0900568 help='Disable logging and internal tee process. Primarily '
569 'used for debugging cbuildbot itself.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800570 return parser
571
572
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400573def _FinishParsing(options):
Ryan Cui85867972012-02-23 18:21:49 -0800574 """Perform some parsing tasks that need to take place after optparse.
575
576 This function needs to be easily testable! Keep it free of
577 environment-dependent code. Put more detailed usage validation in
578 _PostParseCheck().
Brian Harring3fec5a82012-03-01 05:57:03 -0800579
580 Args:
Matt Tennant759e2352013-09-27 15:14:44 -0700581 options: The options object returned by optparse
Brian Harring3fec5a82012-03-01 05:57:03 -0800582 """
Ryan Cui41023d92012-11-13 19:59:50 -0800583 # Populate options.pass_through_args.
584 accepted, _ = commandline.FilteringParser.FilterArgs(
585 options.parsed_args, lambda x: x.opt_inst.pass_through)
586 options.pass_through_args.extend(accepted)
Brian Harring07039b52012-05-13 17:56:47 -0700587
Don Garrettcc0ee522017-09-13 14:28:42 -0700588 if options.local or options.remote:
589 cros_build_lib.Die('Deprecated usage. Please use cros tryjob instead.')
590
Don Garrett211df8c2017-09-06 13:33:02 -0700591 if not options.buildroot:
592 cros_build_lib.Die('A buildroot is required to build.')
593
Brian Harring3fec5a82012-03-01 05:57:03 -0800594 if options.chrome_root:
595 if options.chrome_rev != constants.CHROME_REV_LOCAL:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700596 cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
597 constants.CHROME_REV_LOCAL)
David Jamesa0a664e2013-02-13 09:52:01 -0800598 elif options.chrome_rev == constants.CHROME_REV_LOCAL:
599 cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
600 constants.CHROME_REV_LOCAL)
Brian Harring3fec5a82012-03-01 05:57:03 -0800601
602 if options.chrome_version:
603 if options.chrome_rev != constants.CHROME_REV_SPEC:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700604 cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
605 constants.CHROME_REV_SPEC)
David Jamesa0a664e2013-02-13 09:52:01 -0800606 elif options.chrome_rev == constants.CHROME_REV_SPEC:
607 cros_build_lib.Die(
608 'Chrome rev must not be %s if chrome_version is not set.'
609 % constants.CHROME_REV_SPEC)
Brian Harring3fec5a82012-03-01 05:57:03 -0800610
Don Garrett211df8c2017-09-06 13:33:02 -0700611 patches = bool(options.gerrit_patches)
Ryan Cuieaa9efd2012-04-25 17:56:45 -0700612
David James5734ea32012-08-15 20:23:49 -0700613 # When running in release mode, make sure we are running with checked-in code.
614 # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
615 # a release image with checked-in code for CrOS packages.
Don Garrett211df8c2017-09-06 13:33:02 -0700616 if options.buildbot and patches and not options.debug:
David James5734ea32012-08-15 20:23:49 -0700617 cros_build_lib.Die(
618 'Cannot provide patches when running with --buildbot!')
619
Ryan Cuiba41ad32012-03-08 17:15:29 -0800620 if options.buildbot and options.remote_trybot:
Brian Harring1b8c4c82012-05-29 23:03:04 -0700621 cros_build_lib.Die(
622 '--buildbot and --remote-trybot cannot be used together.')
Ryan Cuiba41ad32012-03-08 17:15:29 -0800623
Ryan Cui85867972012-02-23 18:21:49 -0800624 # Record whether --debug was set explicitly vs. it was inferred.
Don Garrett211df8c2017-09-06 13:33:02 -0700625 options.debug_forced = options.debug
626 # We force --debug to be set for builds that are not 'official'.
627 options.debug = options.debug or not options.buildbot
Brian Harring3fec5a82012-03-01 05:57:03 -0800628
Brian Harring3fec5a82012-03-01 05:57:03 -0800629
Mike Frysinger27e21b72018-07-12 14:20:21 -0400630# pylint: disable=unused-argument
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400631def _PostParseCheck(parser, options, site_config):
Ryan Cui85867972012-02-23 18:21:49 -0800632 """Perform some usage validation after we've parsed the arguments
Brian Harring3fec5a82012-03-01 05:57:03 -0800633
Ryan Cui85867972012-02-23 18:21:49 -0800634 Args:
Aviv Keshet9e4236b2013-12-13 13:07:50 -0800635 parser: Option parser that was used to parse arguments.
636 options: The options returned by optparse.
Don Garrett4af20982015-05-29 19:02:23 -0700637 site_config: config_lib.SiteConfig containing all config info.
Ryan Cui85867972012-02-23 18:21:49 -0800638 """
Don Garrett0a873e02015-06-30 17:55:10 -0700639
Ryan Cuie1e4e662012-05-21 16:39:46 -0700640 if not options.branch:
David James97d95872012-11-16 15:09:56 -0800641 options.branch = git.GetChromiteTrackingBranch()
Ryan Cuie1e4e662012-05-21 16:39:46 -0700642
David Jamesac8c2a72013-02-13 18:44:33 -0800643 # Because the default cache dir depends on other options, FindCacheDir
644 # always returns None, and we setup the default here.
Brian Harringae0a5322012-09-15 01:46:51 -0700645 if options.cache_dir is None:
646 # Note, options.sourceroot is set regardless of the path
647 # actually existing.
Don Garrett211df8c2017-09-06 13:33:02 -0700648 options.cache_dir = os.path.join(options.buildroot, '.cache')
Brian Harringae0a5322012-09-15 01:46:51 -0700649 options.cache_dir = os.path.abspath(options.cache_dir)
Brian Harring8c1d7b12012-10-04 17:36:32 -0700650 parser.ConfigureCacheDir(options.cache_dir)
Brian Harringae0a5322012-09-15 01:46:51 -0700651
Yu-Ju Hong2c066762013-10-28 14:05:08 -0700652 osutils.SafeMakedirsNonRoot(options.cache_dir)
Ryan Cui5ba7e152012-05-10 14:36:52 -0700653
Matt Tennant763497d2014-01-17 16:45:54 -0800654 # Ensure that all args are legitimate config targets.
Don Garrettf0761152017-10-19 19:38:27 -0700655 if options.build_config_name not in site_config:
Stephen Boydeb0cd632019-04-25 11:51:08 -0700656 cros_build_lib.Die('Unknown build config: "%s"' % options.build_config_name)
Don Garrett4bb21682014-03-03 16:16:23 -0800657
Don Garrettf0761152017-10-19 19:38:27 -0700658 build_config = site_config[options.build_config_name]
659 is_payloads_build = build_config.build_type == constants.PAYLOADS_TYPE
Don Garrett4af20982015-05-29 19:02:23 -0700660
Don Garrettf0761152017-10-19 19:38:27 -0700661 if options.channels and not is_payloads_build:
662 cros_build_lib.Die('--channel must only be used with a payload config,'
663 ' not target (%s).' % options.build_config_name)
Don Garrett5af1d262014-05-16 15:49:37 -0700664
Don Garrettf0761152017-10-19 19:38:27 -0700665 if not options.channels and is_payloads_build:
666 cros_build_lib.Die('payload configs (%s) require --channel to do anything'
667 ' useful.' % options.build_config_name)
Matt Tennant763497d2014-01-17 16:45:54 -0800668
Don Garrett370839f2017-10-19 18:32:34 -0700669 # If the build config explicitly forces the debug flag, set the debug flag
670 # as if it was set from the command line.
671 if build_config.debug:
672 options.debug = True
673
Don Garrett8bd52562017-11-20 14:16:37 -0800674 if not (config_lib.isTryjobConfig(build_config) or options.buildbot):
Don Garrett02d2f582017-11-08 14:01:24 -0800675 cros_build_lib.Die(
676 'Refusing to run non-tryjob config as a tryjob.\n'
Don Garrett8bd52562017-11-20 14:16:37 -0800677 'Please "repo sync && cros tryjob --list %s" for alternatives.\n'
Don Garrettf6661792017-11-15 13:13:23 -0800678 'See go/cros-explicit-tryjob-build-configs-psa.',
Don Garrett02d2f582017-11-08 14:01:24 -0800679 build_config.name)
680
Don Garrettf0761152017-10-19 19:38:27 -0700681 # The --version option is not compatible with an external target unless the
682 # --buildbot option is specified. More correctly, only "paladin versions"
683 # will work with external targets, and those are only used with --buildbot.
684 # If --buildbot is specified, then user should know what they are doing and
685 # only specify a version that will work. See crbug.com/311648.
686 if (options.force_version and
687 not (options.buildbot or build_config.internal)):
688 cros_build_lib.Die('Cannot specify --version without --buildbot for an'
689 ' external target (%s).' % options.build_config_name)
Matt Tennant763497d2014-01-17 16:45:54 -0800690
Ryan Cui85867972012-02-23 18:21:49 -0800691
Don Garrett597ddff2017-02-17 18:29:37 -0800692def ParseCommandLine(parser, argv):
Ryan Cui85867972012-02-23 18:21:49 -0800693 """Completely parse the commandline arguments"""
Brian Harring3fec5a82012-03-01 05:57:03 -0800694 (options, args) = parser.parse_args(argv)
Brian Harring37e559b2012-05-22 20:47:32 -0700695
Don Garrettf0761152017-10-19 19:38:27 -0700696 # Handle the request for the reexec command line API version number.
Brian Harring37e559b2012-05-22 20:47:32 -0700697 if options.output_api_version:
Mike Frysinger383367e2014-09-16 15:06:17 -0400698 print(constants.REEXEC_API_VERSION)
Brian Harring37e559b2012-05-22 20:47:32 -0700699 sys.exit(0)
700
Don Garrettf0761152017-10-19 19:38:27 -0700701 # Record the configs targeted. Strip out null arguments.
702 build_config_names = [x for x in args if x]
703 if len(build_config_names) != 1:
704 cros_build_lib.Die('Expected exactly one build config. Got: %r',
705 build_config_names)
706 options.build_config_name = build_config_names[-1]
707
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400708 _FinishParsing(options)
709 return options
Ryan Cui85867972012-02-23 18:21:49 -0800710
711
Aviv Keshet420de512015-05-18 14:28:48 -0700712_ENVIRONMENT_PROD = 'prod'
713_ENVIRONMENT_DEBUG = 'debug'
714_ENVIRONMENT_STANDALONE = 'standalone'
715
716
717def _GetRunEnvironment(options, build_config):
718 """Determine whether this is a prod/debug/standalone run."""
Don Garretta90f0142018-02-28 14:25:19 -0800719 if options.debug_cidb:
720 return _ENVIRONMENT_DEBUG
721
Don Garrett63765c42017-11-03 16:54:20 -0700722 # One of these arguments should always be set if running on a real builder.
723 # If we aren't on a real builder, we are standalone.
724 if not options.buildbot and not options.remote_trybot:
Aviv Keshet420de512015-05-18 14:28:48 -0700725 return _ENVIRONMENT_STANDALONE
726
Don Garrett63765c42017-11-03 16:54:20 -0700727 if build_config['debug_cidb']:
728 return _ENVIRONMENT_DEBUG
Aviv Keshet420de512015-05-18 14:28:48 -0700729
Don Garrett63765c42017-11-03 16:54:20 -0700730 return _ENVIRONMENT_PROD
Aviv Keshet420de512015-05-18 14:28:48 -0700731
732
Gabe Blackde694a32015-02-19 15:11:11 -0800733def _SetupConnections(options, build_config):
Aviv Keshet55491242017-07-13 17:04:07 -0700734 """Set up CIDB connections using the appropriate Setup call.
Aviv Keshet2982af52014-08-13 16:07:57 -0700735
736 Args:
737 options: Command line options structure.
Aviv Keshet64133022014-08-25 15:50:52 -0700738 build_config: Config object for this build.
Aviv Keshet2982af52014-08-13 16:07:57 -0700739 """
Aviv Keshet420de512015-05-18 14:28:48 -0700740 # Outline:
741 # 1) Based on options and build_config, decide whether we are a production
742 # run, debug run, or standalone run.
743 # 2) Set up cidb instance accordingly.
744 # 3) Update topology info from cidb, so that any other service set up can use
745 # topology.
746 # 4) Set up any other services.
747 run_type = _GetRunEnvironment(options, build_config)
748
749 if run_type == _ENVIRONMENT_PROD:
750 cidb.CIDBConnectionFactory.SetupProdCidb()
Mike Frysingercc292b42019-12-11 13:12:35 -0500751 context = ts_mon_config.SetupTsMonGlobalState('cbuildbot', indirect=True)
Aviv Keshet420de512015-05-18 14:28:48 -0700752 elif run_type == _ENVIRONMENT_DEBUG:
753 cidb.CIDBConnectionFactory.SetupDebugCidb()
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700754 context = ts_mon_config.TrivialContextManager()
Aviv Keshet420de512015-05-18 14:28:48 -0700755 else:
Aviv Keshet62d1a0e2014-08-22 21:16:13 -0700756 cidb.CIDBConnectionFactory.SetupNoCidb()
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700757 context = ts_mon_config.TrivialContextManager()
Aviv Keshet62d1a0e2014-08-22 21:16:13 -0700758
Dhanya Ganeshef0cd5b2019-02-06 16:29:36 -0700759 topology.FetchTopology()
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700760 return context
761
Aviv Keshet2982af52014-08-13 16:07:57 -0700762
Dean Liaoe5b0aca2018-01-24 15:27:26 +0800763class _MockMethodWithReturnValue(object):
764 """A method mocker which just returns the specific value."""
765 def __init__(self, return_value):
766 self.return_value = return_value
767
768 def __call__(self, *args, **kwargs):
769 return self.return_value
770
771
772class _ObjectMethodPatcher(object):
773 """A simplified mock.object.patch.
774
775 It is a context manager that patches an object's method with specified
776 return value.
777 """
778 def __init__(self, target, attr, return_value=None):
779 """Constructor.
780
781 Args:
782 target: object to patch.
783 attr: method name of the object to patch.
784 return_value: the return value when calling target.attr
785 """
786 self.target = target
787 self.attr = attr
788 self.return_value = return_value
789 self.original_attr = None
790 self.new_attr = _MockMethodWithReturnValue(self.return_value)
791
792 def __enter__(self):
793 self.original_attr = self.target.__dict__[self.attr]
794 setattr(self.target, self.attr, self.new_attr)
795
796 def __exit__(self, *args):
797 if self.target and self.original_attr:
798 setattr(self.target, self.attr, self.original_attr)
799
800
Matt Tennant759e2352013-09-27 15:14:44 -0700801# TODO(build): This function is too damn long.
Ryan Cui85867972012-02-23 18:21:49 -0800802def main(argv):
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400803 # We get false positives with the options object.
804 # pylint: disable=attribute-defined-outside-init
805
David James59a0a2b2013-03-22 14:04:44 -0700806 # Turn on strict sudo checks.
807 cros_build_lib.STRICT_SUDO = True
808
Ryan Cui85867972012-02-23 18:21:49 -0800809 # Set umask to 022 so files created by buildbot are readable.
Mike Frysinger60ec1012013-10-21 00:11:10 -0400810 os.umask(0o22)
Ryan Cui85867972012-02-23 18:21:49 -0800811
Ryan Cui85867972012-02-23 18:21:49 -0800812 parser = _CreateParser()
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400813 options = ParseCommandLine(parser, argv)
Don Garrett0a873e02015-06-30 17:55:10 -0700814
Don Garrettb85658c2015-06-30 19:07:22 -0700815 # Fetch our site_config now, because we need it to do anything else.
Don Garrettde81cc72015-07-07 13:23:28 -0700816 site_config = config_lib.GetConfig()
Don Garrettb85658c2015-06-30 19:07:22 -0700817
Mike Frysinger80bba8a2017-08-18 15:28:36 -0400818 _PostParseCheck(parser, options, site_config)
Brian Harring3fec5a82012-03-01 05:57:03 -0800819
Mike Frysinger8fd67dc2012-12-03 23:51:18 -0500820 cros_build_lib.AssertOutsideChroot()
Zdenek Behan98ec2fb2012-08-31 17:12:18 +0200821
Prathmesh Prabhu51d774f2015-07-17 15:11:49 -0700822 if options.enable_buildbot_tags:
823 logging.EnableBuildbotMarkers()
Matt Tennant759e2352013-09-27 15:14:44 -0700824
Don Garrett0c6e0272017-12-13 17:05:21 -0800825 if (options.buildbot and
826 not options.debug and
Don Garrett0c6e0272017-12-13 17:05:21 -0800827 not cros_build_lib.HostIsCIBuilder()):
Evan Hernandez73263be2019-03-14 15:17:59 -0600828 # --buildbot can only be used on a real builder, unless it's debug.
Don Garrett0c6e0272017-12-13 17:05:21 -0800829 cros_build_lib.Die('This host is not a supported build machine.')
Ningning Xiac691e432016-08-11 14:52:59 -0700830
Matt Tennant759e2352013-09-27 15:14:44 -0700831 # Only one config arg is allowed in this mode, which was confirmed earlier.
Don Garrettf0761152017-10-19 19:38:27 -0700832 build_config = site_config[options.build_config_name]
Brian Harring3fec5a82012-03-01 05:57:03 -0800833
Don Garrettbbd7b552014-05-16 13:15:21 -0700834 # TODO: Re-enable this block when reference_repo support handles this
835 # properly. (see chromium:330775)
836 # if options.reference_repo is None:
837 # repo_path = os.path.join(options.sourceroot, '.repo')
838 # # If we're being run from a repo checkout, reuse the repo's git pool to
839 # # cut down on sync time.
840 # if os.path.exists(repo_path):
841 # options.reference_repo = options.sourceroot
842
843 if options.reference_repo:
David Jamesdac7a912013-11-18 11:14:44 -0800844 if not os.path.exists(options.reference_repo):
845 parser.error('Reference path %s does not exist'
846 % (options.reference_repo,))
847 elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
848 parser.error('Reference path %s does not look to be the base of a '
849 'repo checkout; no .repo exists in the root.'
850 % (options.reference_repo,))
851
Brian Harringf11bf682012-05-14 15:53:43 -0700852 if (options.buildbot or options.remote_trybot) and not options.resume:
Brian Harring470f6112012-03-02 11:47:10 -0800853 if not options.cgroups:
Ryan Cuid4a24212012-04-04 18:08:12 -0700854 parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
855 'be used together. Cgroup support is required for '
856 'buildbot/remote-trybot mode.')
Mike Frysingera78a56e2012-11-20 06:02:30 -0500857 if not cgroups.Cgroup.IsSupported():
Ryan Cuid4a24212012-04-04 18:08:12 -0700858 parser.error('Option --buildbot/--remote-trybot was given, but this '
859 'system does not support cgroups. Failing.')
Brian Harring3fec5a82012-03-01 05:57:03 -0800860
David Jamesaad5cc72012-10-26 15:03:13 -0700861 missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
Brian Harring351ce442012-03-09 16:38:14 -0800862 if missing:
David Jameseecba232014-06-11 11:35:11 -0700863 parser.error('Option --buildbot/--remote-trybot requires the following '
Ryan Cuid4a24212012-04-04 18:08:12 -0700864 "binaries which couldn't be found in $PATH: %s"
Brian Harring351ce442012-03-09 16:38:14 -0800865 % (', '.join(missing)))
866
David Jamesdac7a912013-11-18 11:14:44 -0800867 if options.reference_repo:
868 options.reference_repo = os.path.abspath(options.reference_repo)
869
Brian Harring3fec5a82012-03-01 05:57:03 -0800870 # Sanity check of buildroot- specifically that it's not pointing into the
871 # midst of an existing repo since git-repo doesn't support nesting.
Brian Harring3fec5a82012-03-01 05:57:03 -0800872 if (not repository.IsARepoRoot(options.buildroot) and
David James13a69c92013-05-09 10:37:42 -0700873 git.FindRepoDir(options.buildroot)):
Don Garrett211df8c2017-09-06 13:33:02 -0700874 cros_build_lib.Die(
875 'Configured buildroot %s is a subdir of an existing repo checkout.'
876 % options.buildroot)
Brian Harring3fec5a82012-03-01 05:57:03 -0800877
Chris Sosab5ea3b42012-10-25 15:25:20 -0700878 if not options.log_dir:
879 options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
880
Brian Harringd166aaf2012-05-14 18:31:53 -0700881 log_file = None
882 if options.tee:
Chris Sosab5ea3b42012-10-25 15:25:20 -0700883 log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
884 osutils.SafeMakedirs(options.log_dir)
Brian Harringd166aaf2012-05-14 18:31:53 -0700885 _BackupPreviousLog(log_file)
886
Brian Harring1b8c4c82012-05-29 23:03:04 -0700887 with cros_build_lib.ContextManagerStack() as stack:
Lann Martin8cc2eab2018-09-05 17:17:57 -0600888 # Preserve chromite; we might be running from there!
889 options.preserve_paths = set(['chromite'])
David Jamescebc7272013-07-17 16:45:05 -0700890 if log_file is not None:
891 # We don't want the critical section to try to clean up the tee process,
892 # so we run Tee (forked off) outside of it. This prevents a deadlock
893 # because the Tee process only exits when its pipe is closed, and the
894 # critical section accidentally holds on to that file handle.
895 stack.Add(tee.Tee, log_file)
896 options.preserve_paths.add(_DEFAULT_LOG_DIR)
897
Brian Harringc2d09d92012-05-13 22:03:15 -0700898 critical_section = stack.Add(cleanup.EnforcedCleanupSection)
899 stack.Add(sudo.SudoKeepAlive)
Brian Harringd166aaf2012-05-14 18:31:53 -0700900
Brian Harringc2d09d92012-05-13 22:03:15 -0700901 if not options.resume:
Brian Harring2bf55e12012-05-13 21:31:55 -0700902 # If we're in resume mode, use our parents tempdir rather than
903 # nesting another layer.
David James4bc13702013-03-26 08:08:04 -0700904 stack.Add(osutils.TempDir, prefix='cbuildbot-tmp', set_global=True)
David Jameseecba232014-06-11 11:35:11 -0700905 logging.debug('Cbuildbot tempdir is %r.', os.environ.get('TMP'))
Brian Harringd166aaf2012-05-14 18:31:53 -0700906
Brian Harringc2d09d92012-05-13 22:03:15 -0700907 if options.cgroups:
908 stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
Brian Harringa184efa2012-03-04 11:51:25 -0800909
Brian Harringc2d09d92012-05-13 22:03:15 -0700910 # Mark everything between EnforcedCleanupSection and here as having to
911 # be rolled back via the contextmanager cleanup handlers. This
912 # ensures that sudo bits cannot outlive cbuildbot, that anything
913 # cgroups would kill gets killed, etc.
David Jamesfb3aac92013-10-16 13:26:52 -0700914 stack.Add(critical_section.ForkWatchdog)
Brian Harringd166aaf2012-05-14 18:31:53 -0700915
Aviv Keshetcf9c2722014-02-25 15:15:10 -0800916 if options.mock_slave_status is not None:
917 with open(options.mock_slave_status, 'r') as f:
Aviv Keshet4e750022014-03-07 16:50:34 -0800918 mock_statuses = pickle.load(f)
Mike Frysinger0bdbc102019-06-13 15:27:29 -0400919 for key, value in mock_statuses.items():
Ningning Xiaf342b952017-02-15 14:13:33 -0800920 mock_statuses[key] = builder_status_lib.BuilderStatus(**value)
Dean Liaoe5b0aca2018-01-24 15:27:26 +0800921 stack.Add(_ObjectMethodPatcher,
Yu-Ju Hongd0fda382014-05-09 15:28:24 -0700922 completion_stages.MasterSlaveSyncCompletionStage,
923 '_FetchSlaveStatuses',
924 return_value=mock_statuses)
Aviv Keshetcf9c2722014-02-25 15:15:10 -0800925
Paul Hobbsd5a0f812016-07-26 16:10:31 -0700926 stack.Add(_SetupConnections, options, build_config)
Don Garrettb4318362014-10-03 15:49:36 -0700927 retry_stats.SetupStats()
Aviv Keshet2982af52014-08-13 16:07:57 -0700928
Dhanya Ganesh4339cbc2019-03-08 12:02:14 -0700929 timeout_display_message = (
930 'This build has reached the timeout deadline set by the master. '
931 'Either this stage or a previous one took too long (see stage '
932 'timing historical summary in ReportStage) or the build failed '
933 'to start on time.')
Prathmesh Prabhu80e05df2014-12-11 15:20:33 -0800934
935 if options.timeout > 0:
Aviv Keshet446f07f2016-03-08 11:32:31 -0800936 stack.Add(timeout_util.FatalTimeout, options.timeout,
937 timeout_display_message)
Ningning Xiaad483542016-05-24 12:27:21 -0700938 try:
939 _RunBuildStagesWrapper(options, site_config, build_config)
940 except failures_lib.ExitEarlyException as ex:
941 # This build finished successfully. Do not re-raise ExitEarlyException.
942 logging.info('One stage exited early: %s', ex)