GoogleGit

blob: b886c9480d408169bf1cc18dea95c4b53fec9962 [file] [log] [blame]
  1. # Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """Main builder code for Chromium OS.
  5. Used by Chromium OS buildbot configuration for all Chromium OS builds including
  6. full and pre-flight-queue builds.
  7. """
  8. from __future__ import print_function
  9. import distutils.version
  10. import glob
  11. import json
  12. import mock
  13. import optparse
  14. import os
  15. import pickle
  16. import sys
  17. from chromite.cbuildbot import builders
  18. from chromite.cbuildbot import cbuildbot_config
  19. from chromite.cbuildbot import cbuildbot_run
  20. from chromite.cbuildbot import constants
  21. from chromite.cbuildbot import manifest_version
  22. from chromite.cbuildbot import remote_try
  23. from chromite.cbuildbot import repository
  24. from chromite.cbuildbot import tee
  25. from chromite.cbuildbot import tree_status
  26. from chromite.cbuildbot import trybot_patch_pool
  27. from chromite.cbuildbot.stages import completion_stages
  28. from chromite.lib import cidb
  29. from chromite.lib import cgroups
  30. from chromite.lib import cleanup
  31. from chromite.lib import commandline
  32. from chromite.lib import cros_build_lib
  33. from chromite.lib import cros_logging as logging
  34. from chromite.lib import git
  35. from chromite.lib import graphite
  36. from chromite.lib import gob_util
  37. from chromite.lib import osutils
  38. from chromite.lib import parallel
  39. from chromite.lib import retry_stats
  40. from chromite.lib import sudo
  41. from chromite.lib import timeout_util
  42. _DEFAULT_LOG_DIR = 'cbuildbot_logs'
  43. _BUILDBOT_LOG_FILE = 'cbuildbot.log'
  44. _DEFAULT_EXT_BUILDROOT = 'trybot'
  45. _DEFAULT_INT_BUILDROOT = 'trybot-internal'
  46. _BUILDBOT_REQUIRED_BINARIES = ('pbzip2',)
  47. _API_VERSION_ATTR = 'api_version'
  48. def _PrintValidConfigs(display_all=False):
  49. """Print a list of valid buildbot configs.
  50. Args:
  51. display_all: Print all configs. Otherwise, prints only configs with
  52. trybot_list=True.
  53. """
  54. def _GetSortKey(config_name):
  55. config_dict = cbuildbot_config.config[config_name]
  56. return (not config_dict['trybot_list'], config_dict['description'],
  57. config_name)
  58. COLUMN_WIDTH = 45
  59. print()
  60. print('config'.ljust(COLUMN_WIDTH), 'description')
  61. print('------'.ljust(COLUMN_WIDTH), '-----------')
  62. config_names = cbuildbot_config.config.keys()
  63. config_names.sort(key=_GetSortKey)
  64. for name in config_names:
  65. if display_all or cbuildbot_config.config[name]['trybot_list']:
  66. desc = cbuildbot_config.config[name].get('description')
  67. desc = desc if desc else ''
  68. print(name.ljust(COLUMN_WIDTH), desc)
  69. print()
  70. def _GetConfig(config_name):
  71. """Gets the configuration for the build if it exists, None otherwise."""
  72. if cbuildbot_config.config.has_key(config_name):
  73. return cbuildbot_config.config[config_name]
  74. def _ConfirmBuildRoot(buildroot):
  75. """Confirm with user the inferred buildroot, and mark it as confirmed."""
  76. logging.warning('Using default directory %s as buildroot', buildroot)
  77. if not cros_build_lib.BooleanPrompt(default=False):
  78. print('Please specify a different buildroot via the --buildroot option.')
  79. sys.exit(0)
  80. if not os.path.exists(buildroot):
  81. os.mkdir(buildroot)
  82. repository.CreateTrybotMarker(buildroot)
  83. def _ConfirmRemoteBuildbotRun():
  84. """Confirm user wants to run with --buildbot --remote."""
  85. logging.warning(
  86. 'You are about to launch a PRODUCTION job! This is *NOT* a '
  87. 'trybot run! Are you sure?')
  88. if not cros_build_lib.BooleanPrompt(default=False):
  89. print('Please specify --pass-through="--debug".')
  90. sys.exit(0)
  91. def _DetermineDefaultBuildRoot(sourceroot, internal_build):
  92. """Default buildroot to be under the directory that contains current checkout.
  93. Args:
  94. internal_build: Whether the build is an internal build
  95. sourceroot: Use specified sourceroot.
  96. """
  97. if not repository.IsARepoRoot(sourceroot):
  98. cros_build_lib.Die(
  99. 'Could not find root of local checkout at %s. Please specify '
  100. 'using the --sourceroot option.' % sourceroot)
  101. # Place trybot buildroot under the directory containing current checkout.
  102. top_level = os.path.dirname(os.path.realpath(sourceroot))
  103. if internal_build:
  104. buildroot = os.path.join(top_level, _DEFAULT_INT_BUILDROOT)
  105. else:
  106. buildroot = os.path.join(top_level, _DEFAULT_EXT_BUILDROOT)
  107. return buildroot
  108. def _BackupPreviousLog(log_file, backup_limit=25):
  109. """Rename previous log.
  110. Args:
  111. log_file: The absolute path to the previous log.
  112. backup_limit: Maximum number of old logs to keep.
  113. """
  114. if os.path.exists(log_file):
  115. old_logs = sorted(glob.glob(log_file + '.*'),
  116. key=distutils.version.LooseVersion)
  117. if len(old_logs) >= backup_limit:
  118. os.remove(old_logs[0])
  119. last = 0
  120. if old_logs:
  121. last = int(old_logs.pop().rpartition('.')[2])
  122. os.rename(log_file, log_file + '.' + str(last + 1))
  123. def _IsDistributedBuilder(options, chrome_rev, build_config):
  124. """Determines whether the builder should be a DistributedBuilder.
  125. Args:
  126. options: options passed on the commandline.
  127. chrome_rev: Chrome revision to build.
  128. build_config: Builder configuration dictionary.
  129. Returns:
  130. True if the builder should be a distributed_builder
  131. """
  132. if build_config['pre_cq'] or options.pre_cq:
  133. return True
  134. elif not options.buildbot:
  135. return False
  136. elif chrome_rev in (constants.CHROME_REV_TOT,
  137. constants.CHROME_REV_LOCAL,
  138. constants.CHROME_REV_SPEC):
  139. # We don't do distributed logic to TOT Chrome PFQ's, nor local
  140. # chrome roots (e.g. chrome try bots)
  141. # TODO(davidjames): Update any builders that rely on this logic to use
  142. # manifest_version=False instead.
  143. return False
  144. elif build_config['manifest_version']:
  145. return True
  146. return False
  147. def _RunBuildStagesWrapper(options, build_config):
  148. """Helper function that wraps RunBuildStages()."""
  149. logging.info('cbuildbot was executed with args %s' %
  150. cros_build_lib.CmdToStr(sys.argv))
  151. chrome_rev = build_config['chrome_rev']
  152. if options.chrome_rev:
  153. chrome_rev = options.chrome_rev
  154. if chrome_rev == constants.CHROME_REV_TOT:
  155. options.chrome_version = gob_util.GetTipOfTrunkRevision(
  156. constants.CHROMIUM_GOB_URL)
  157. options.chrome_rev = constants.CHROME_REV_SPEC
  158. # If it's likely we'll need to build Chrome, fetch the source.
  159. if build_config['sync_chrome'] is None:
  160. options.managed_chrome = (
  161. chrome_rev != constants.CHROME_REV_LOCAL and
  162. (not build_config['usepkg_build_packages'] or chrome_rev or
  163. build_config['profile'] or options.rietveld_patches))
  164. else:
  165. options.managed_chrome = build_config['sync_chrome']
  166. if options.managed_chrome:
  167. # Tell Chrome to fetch the source locally.
  168. internal = constants.USE_CHROME_INTERNAL in build_config['useflags']
  169. chrome_src = 'chrome-src-internal' if internal else 'chrome-src'
  170. options.chrome_root = os.path.join(options.cache_dir, 'distfiles', 'target',
  171. chrome_src)
  172. elif options.rietveld_patches:
  173. cros_build_lib.Die('This builder does not support Rietveld patches.')
  174. metadata_dump_dict = {}
  175. if options.metadata_dump:
  176. with open(options.metadata_dump, 'r') as metadata_file:
  177. metadata_dump_dict = json.loads(metadata_file.read())
  178. # We are done munging options values, so freeze options object now to avoid
  179. # further abuse of it.
  180. # TODO(mtennant): one by one identify each options value override and see if
  181. # it can be handled another way. Try to push this freeze closer and closer
  182. # to the start of the script (e.g. in or after _PostParseCheck).
  183. options.Freeze()
  184. with parallel.Manager() as manager:
  185. builder_run = cbuildbot_run.BuilderRun(options, build_config, manager)
  186. if metadata_dump_dict:
  187. builder_run.attrs.metadata.UpdateWithDict(metadata_dump_dict)
  188. if builder_run.config.builder_class_name is None:
  189. # TODO: This should get relocated to cbuildbot_config.
  190. if _IsDistributedBuilder(options, chrome_rev, build_config):
  191. builder_cls_name = 'simple_builders.DistributedBuilder'
  192. else:
  193. builder_cls_name = 'simple_builders.SimpleBuilder'
  194. builder_cls = builders.GetBuilderClass(builder_cls_name)
  195. builder = builder_cls(builder_run)
  196. else:
  197. builder = builders.Builder(builder_run)
  198. if not builder.Run():
  199. sys.exit(1)
  200. # Parser related functions
  201. def _CheckLocalPatches(sourceroot, local_patches):
  202. """Do an early quick check of the passed-in patches.
  203. If the branch of a project is not specified we append the current branch the
  204. project is on.
  205. TODO(davidjames): The project:branch format isn't unique, so this means that
  206. we can't differentiate what directory the user intended to apply patches to.
  207. We should references by directory instead.
  208. Args:
  209. sourceroot: The checkout where patches are coming from.
  210. local_patches: List of patches to check in project:branch format.
  211. Returns:
  212. A list of patches that have been verified, in project:branch format.
  213. """
  214. verified_patches = []
  215. manifest = git.ManifestCheckout.Cached(sourceroot)
  216. for patch in local_patches:
  217. project, _, branch = patch.partition(':')
  218. checkouts = manifest.FindCheckouts(project, only_patchable=True)
  219. if not checkouts:
  220. cros_build_lib.Die('Project %s does not exist.' % (project,))
  221. if len(checkouts) > 1:
  222. cros_build_lib.Die(
  223. 'We do not yet support local patching for projects that are checked '
  224. 'out to multiple directories. Try uploading your patch to gerrit '
  225. 'and referencing it via the -g option instead.'
  226. )
  227. ok = False
  228. for checkout in checkouts:
  229. project_dir = checkout.GetPath(absolute=True)
  230. # If no branch was specified, we use the project's current branch.
  231. if not branch:
  232. local_branch = git.GetCurrentBranch(project_dir)
  233. else:
  234. local_branch = branch
  235. if local_branch and git.DoesCommitExistInRepo(project_dir, local_branch):
  236. verified_patches.append('%s:%s' % (project, local_branch))
  237. ok = True
  238. if not ok:
  239. if branch:
  240. cros_build_lib.Die('Project %s does not have branch %s'
  241. % (project, branch))
  242. else:
  243. cros_build_lib.Die('Project %s is not on a branch!' % (project,))
  244. return verified_patches
  245. def _CheckChromeVersionOption(_option, _opt_str, value, parser):
  246. """Upgrade other options based on chrome_version being passed."""
  247. value = value.strip()
  248. if parser.values.chrome_rev is None and value:
  249. parser.values.chrome_rev = constants.CHROME_REV_SPEC
  250. parser.values.chrome_version = value
  251. def _CheckChromeRootOption(_option, _opt_str, value, parser):
  252. """Validate and convert chrome_root to full-path form."""
  253. if parser.values.chrome_rev is None:
  254. parser.values.chrome_rev = constants.CHROME_REV_LOCAL
  255. parser.values.chrome_root = value
  256. def _CheckChromeRevOption(_option, _opt_str, value, parser):
  257. """Validate the chrome_rev option."""
  258. value = value.strip()
  259. if value not in constants.VALID_CHROME_REVISIONS:
  260. raise optparse.OptionValueError('Invalid chrome rev specified')
  261. parser.values.chrome_rev = value
  262. def FindCacheDir(_parser, _options):
  263. return None
  264. class CustomGroup(optparse.OptionGroup):
  265. """Custom option group which supports arguments passed-through to trybot."""
  266. def add_remote_option(self, *args, **kwargs):
  267. """For arguments that are passed-through to remote trybot."""
  268. return optparse.OptionGroup.add_option(self, *args,
  269. remote_pass_through=True,
  270. **kwargs)
  271. class CustomOption(commandline.FilteringOption):
  272. """Subclass FilteringOption class to implement pass-through and api."""
  273. ACTIONS = commandline.FilteringOption.ACTIONS + ('extend',)
  274. STORE_ACTIONS = commandline.FilteringOption.STORE_ACTIONS + ('extend',)
  275. TYPED_ACTIONS = commandline.FilteringOption.TYPED_ACTIONS + ('extend',)
  276. ALWAYS_TYPED_ACTIONS = (commandline.FilteringOption.ALWAYS_TYPED_ACTIONS +
  277. ('extend',))
  278. def __init__(self, *args, **kwargs):
  279. # The remote_pass_through argument specifies whether we should directly
  280. # pass the argument (with its value) onto the remote trybot.
  281. self.pass_through = kwargs.pop('remote_pass_through', False)
  282. self.api_version = int(kwargs.pop('api', '0'))
  283. commandline.FilteringOption.__init__(self, *args, **kwargs)
  284. def take_action(self, action, dest, opt, value, values, parser):
  285. if action == 'extend':
  286. # If there is extra spaces between each argument, we get '' which later
  287. # code barfs on, so skip those. e.g. We see this with the forms:
  288. # cbuildbot -p 'proj:branch ' ...
  289. # cbuildbot -p ' proj:branch' ...
  290. # cbuildbot -p 'proj:branch proj2:branch' ...
  291. lvalue = value.split()
  292. values.ensure_value(dest, []).extend(lvalue)
  293. commandline.FilteringOption.take_action(
  294. self, action, dest, opt, value, values, parser)
  295. class CustomParser(commandline.FilteringParser):
  296. """Custom option parser which supports arguments passed-trhough to trybot"""
  297. DEFAULT_OPTION_CLASS = CustomOption
  298. def add_remote_option(self, *args, **kwargs):
  299. """For arguments that are passed-through to remote trybot."""
  300. return self.add_option(*args, remote_pass_through=True, **kwargs)
  301. def _CreateParser():
  302. """Generate and return the parser with all the options."""
  303. # Parse options
  304. usage = 'usage: %prog [options] buildbot_config [buildbot_config ...]'
  305. parser = CustomParser(usage=usage, caching=FindCacheDir)
  306. # Main options
  307. parser.add_option('-l', '--list', action='store_true', dest='list',
  308. default=False,
  309. help='List the suggested trybot configs to use (see --all)')
  310. parser.add_option('-a', '--all', action='store_true', dest='print_all',
  311. default=False,
  312. help='List all of the buildbot configs available w/--list')
  313. parser.add_option('--local', default=False, action='store_true',
  314. help=('Specifies that this tryjob should be run locally. '
  315. 'Implies --debug.'))
  316. parser.add_option('--remote', default=False, action='store_true',
  317. help='Specifies that this tryjob should be run remotely.')
  318. parser.add_remote_option('-b', '--branch',
  319. help=('The manifest branch to test. The branch to '
  320. 'check the buildroot out to.'))
  321. parser.add_option('-r', '--buildroot', dest='buildroot', type='path',
  322. help=('Root directory where source is checked out to, and '
  323. 'where the build occurs. For external build configs, '
  324. "defaults to 'trybot' directory at top level of your "
  325. 'repo-managed checkout.'))
  326. parser.add_remote_option('--chrome_rev', default=None, type='string',
  327. action='callback', dest='chrome_rev',
  328. callback=_CheckChromeRevOption,
  329. help=('Revision of Chrome to use, of type [%s]'
  330. % '|'.join(constants.VALID_CHROME_REVISIONS)))
  331. parser.add_remote_option('--profile', default=None, type='string',
  332. action='store', dest='profile',
  333. help='Name of profile to sub-specify board variant.')
  334. #
  335. # Patch selection options.
  336. #
  337. group = CustomGroup(
  338. parser,
  339. 'Patch Options')
  340. group.add_remote_option('-g', '--gerrit-patches', action='extend',
  341. default=[], type='string',
  342. metavar="'Id1 *int_Id2...IdN'",
  343. help=('Space-separated list of short-form Gerrit '
  344. "Change-Id's or change numbers to patch. "
  345. "Please prepend '*' to internal Change-Id's"))
  346. group.add_remote_option('-G', '--rietveld-patches', action='extend',
  347. default=[], type='string',
  348. metavar="'id1[:subdir1]...idN[:subdirN]'",
  349. help=('Space-separated list of short-form Rietveld '
  350. 'issue numbers to patch. If no subdir is '
  351. 'specified, the src directory is used.'))
  352. group.add_option('-p', '--local-patches', action='extend', default=[],
  353. metavar="'<project1>[:<branch1>]...<projectN>[:<branchN>]'",
  354. help=('Space-separated list of project branches with '
  355. 'patches to apply. Projects are specified by name. '
  356. 'If no branch is specified the current branch of the '
  357. 'project will be used.'))
  358. parser.add_option_group(group)
  359. #
  360. # Remote trybot options.
  361. #
  362. group = CustomGroup(
  363. parser,
  364. 'Remote Trybot Options (--remote)')
  365. group.add_remote_option('--hwtest', dest='hwtest', action='store_true',
  366. default=False,
  367. help='Run the HWTest stage (tests on real hardware)')
  368. group.add_option('--remote-description', default=None,
  369. help=('Attach an optional description to a --remote run '
  370. 'to make it easier to identify the results when it '
  371. 'finishes'))
  372. group.add_option('--slaves', action='extend', default=[],
  373. help=('Specify specific remote tryslaves to run on (e.g. '
  374. 'build149-m2); if the bot is busy, it will be queued'))
  375. group.add_remote_option('--channel', dest='channels', action='extend',
  376. default=[],
  377. help=('Specify a channel for a payloads trybot. Can '
  378. 'be specified multiple times. No valid for '
  379. 'non-payloads configs.'))
  380. group.add_option('--test-tryjob', action='store_true',
  381. default=False,
  382. help=('Submit a tryjob to the test repository. Will not '
  383. 'show up on the production trybot waterfall.'))
  384. parser.add_option_group(group)
  385. #
  386. # Branch creation options.
  387. #
  388. group = CustomGroup(
  389. parser,
  390. 'Branch Creation Options (used with branch-util)')
  391. group.add_remote_option('--branch-name',
  392. help='The branch to create or delete.')
  393. group.add_remote_option('--delete-branch', default=False, action='store_true',
  394. help='Delete the branch specified in --branch-name.')
  395. group.add_remote_option('--rename-to', type='string',
  396. help='Rename a branch to the specified name.')
  397. group.add_remote_option('--force-create', default=False, action='store_true',
  398. help='Overwrites an existing branch.')
  399. parser.add_option_group(group)
  400. #
  401. # Advanced options.
  402. #
  403. group = CustomGroup(
  404. parser,
  405. 'Advanced Options',
  406. 'Caution: use these options at your own risk.')
  407. group.add_remote_option('--bootstrap-args', action='append', default=[],
  408. help=('Args passed directly to the bootstrap re-exec '
  409. 'to skip verification by the bootstrap code'))
  410. group.add_remote_option('--buildbot', dest='buildbot', action='store_true',
  411. default=False, help='This is running on a buildbot')
  412. group.add_remote_option('--buildnumber', help='build number', type='int',
  413. default=0)
  414. group.add_option('--chrome_root', default=None, type='path',
  415. action='callback', callback=_CheckChromeRootOption,
  416. dest='chrome_root', help='Local checkout of Chrome to use.')
  417. group.add_remote_option('--chrome_version', default=None, type='string',
  418. action='callback', dest='chrome_version',
  419. callback=_CheckChromeVersionOption,
  420. help=('Used with SPEC logic to force a particular '
  421. 'git revision of chrome rather than the '
  422. 'latest.'))
  423. group.add_remote_option('--clobber', action='store_true', dest='clobber',
  424. default=False,
  425. help='Clears an old checkout before syncing')
  426. group.add_remote_option('--latest-toolchain', action='store_true',
  427. default=False,
  428. help='Use the latest toolchain.')
  429. parser.add_option('--log_dir', dest='log_dir', type='path',
  430. help=('Directory where logs are stored.'))
  431. group.add_remote_option('--maxarchives', dest='max_archive_builds',
  432. default=3, type='int',
  433. help='Change the local saved build count limit.')
  434. parser.add_remote_option('--manifest-repo-url',
  435. help=('Overrides the default manifest repo url.'))
  436. group.add_remote_option('--compilecheck', action='store_true', default=False,
  437. help='Only verify compilation and unit tests.')
  438. group.add_remote_option('--noarchive', action='store_false', dest='archive',
  439. default=True, help="Don't run archive stage.")
  440. group.add_remote_option('--nobootstrap', action='store_false',
  441. dest='bootstrap', default=True,
  442. help=("Don't checkout and run from a standalone "
  443. 'chromite repo.'))
  444. group.add_remote_option('--nobuild', action='store_false', dest='build',
  445. default=True,
  446. help="Don't actually build (for cbuildbot dev)")
  447. group.add_remote_option('--noclean', action='store_false', dest='clean',
  448. default=True, help="Don't clean the buildroot")
  449. group.add_remote_option('--nocgroups', action='store_false', dest='cgroups',
  450. default=True,
  451. help='Disable cbuildbots usage of cgroups.')
  452. group.add_remote_option('--nochromesdk', action='store_false',
  453. dest='chrome_sdk', default=True,
  454. help=("Don't run the ChromeSDK stage which builds "
  455. 'Chrome outside of the chroot.'))
  456. group.add_remote_option('--noprebuilts', action='store_false',
  457. dest='prebuilts', default=True,
  458. help="Don't upload prebuilts.")
  459. group.add_remote_option('--nopatch', action='store_false',
  460. dest='postsync_patch', default=True,
  461. help=("Don't run PatchChanges stage. This does not "
  462. 'disable patching in of chromite patches '
  463. 'during BootstrapStage.'))
  464. group.add_remote_option('--nopaygen', action='store_false',
  465. dest='paygen', default=True,
  466. help="Don't generate payloads.")
  467. group.add_remote_option('--noreexec', action='store_false',
  468. dest='postsync_reexec', default=True,
  469. help="Don't reexec into the buildroot after syncing.")
  470. group.add_remote_option('--nosdk', action='store_true',
  471. default=False,
  472. help='Re-create the SDK from scratch.')
  473. group.add_remote_option('--nosync', action='store_false', dest='sync',
  474. default=True, help="Don't sync before building.")
  475. group.add_remote_option('--notests', action='store_false', dest='tests',
  476. default=True,
  477. help=('Override values from buildconfig and run no '
  478. 'tests.'))
  479. group.add_remote_option('--noimagetests', action='store_false',
  480. dest='image_test', default=True,
  481. help=('Override values from buildconfig and run no '
  482. 'image tests.'))
  483. group.add_remote_option('--nouprev', action='store_false', dest='uprev',
  484. default=True,
  485. help=('Override values from buildconfig and never '
  486. 'uprev.'))
  487. group.add_option('--reference-repo', action='store', default=None,
  488. dest='reference_repo',
  489. help=('Reuse git data stored in an existing repo '
  490. 'checkout. This can drastically reduce the network '
  491. 'time spent setting up the trybot checkout. By '
  492. "default, if this option isn't given but cbuildbot "
  493. 'is invoked from a repo checkout, cbuildbot will '
  494. 'use the repo root.'))
  495. group.add_option('--resume', action='store_true', default=False,
  496. help='Skip stages already successfully completed.')
  497. group.add_remote_option('--timeout', action='store', type='int', default=0,
  498. help=('Specify the maximum amount of time this job '
  499. 'can run for, at which point the build will be '
  500. 'aborted. If set to zero, then there is no '
  501. 'timeout.'))
  502. group.add_remote_option('--version', dest='force_version', default=None,
  503. help=('Used with manifest logic. Forces use of this '
  504. 'version rather than create or get latest. '
  505. 'Examples: 4815.0.0-rc1, 4815.1.2'))
  506. parser.add_option_group(group)
  507. #
  508. # Internal options.
  509. #
  510. group = CustomGroup(
  511. parser,
  512. 'Internal Chromium OS Build Team Options',
  513. 'Caution: these are for meant for the Chromium OS build team only')
  514. group.add_remote_option('--archive-base', type='gs_path',
  515. help=('Base GS URL (gs://<bucket_name>/<path>) to '
  516. 'upload archive artifacts to'))
  517. group.add_remote_option(
  518. '--cq-gerrit-query', dest='cq_gerrit_override', default=None,
  519. help=('If given, this gerrit query will be used to find what patches to '
  520. "test, rather than the normal 'CommitQueue>=1 AND Verified=1 AND "
  521. "CodeReview=2' query it defaults to. Use with care- note "
  522. 'additionally this setting only has an effect if the buildbot '
  523. "target is a cq target, and we're in buildbot mode."))
  524. group.add_option('--pass-through', dest='pass_through_args', action='append',
  525. type='string', default=[])
  526. group.add_remote_option('--pre-cq', action='store_true', default=False,
  527. help='Mark CLs as tested by the PreCQ on success.')
  528. group.add_option('--reexec-api-version', dest='output_api_version',
  529. action='store_true', default=False,
  530. help=('Used for handling forwards/backwards compatibility '
  531. 'with --resume and --bootstrap'))
  532. group.add_option('--remote-trybot', dest='remote_trybot',
  533. action='store_true', default=False,
  534. help='Indicates this is running on a remote trybot machine')
  535. group.add_remote_option('--remote-patches', action='extend', default=[],
  536. help=('Patches uploaded by the trybot client when '
  537. 'run using the -p option'))
  538. # Note the default here needs to be hardcoded to 3; that is the last version
  539. # that lacked this functionality.
  540. group.add_option('--remote-version', default=3, type=int, action='store',
  541. help=('Used for compatibility checks w/tryjobs running in '
  542. 'older chromite instances'))
  543. group.add_option('--sourceroot', type='path', default=constants.SOURCE_ROOT)
  544. group.add_remote_option('--test-bootstrap', action='store_true',
  545. default=False,
  546. help=('Causes cbuildbot to bootstrap itself twice, '
  547. 'in the sequence A->B->C: A(unpatched) patches '
  548. 'and bootstraps B; B patches and bootstraps C'))
  549. group.add_remote_option('--validation_pool', default=None,
  550. help=('Path to a pickled validation pool. Intended '
  551. 'for use only with the commit queue.'))
  552. group.add_remote_option('--metadata_dump', default=None,
  553. help=('Path to a json dumped metadata file. This '
  554. 'will be used as the initial metadata.'))
  555. group.add_remote_option('--master-build-id', default=None, type=int,
  556. api=constants.REEXEC_API_MASTER_BUILD_ID,
  557. help=('cidb build id of the master build to this '
  558. 'slave build.'))
  559. group.add_remote_option('--mock-tree-status', dest='mock_tree_status',
  560. default=None, action='store',
  561. help=('Override the tree status value that would be '
  562. 'returned from the the actual tree. Example '
  563. 'values: open, closed, throttled. When used '
  564. 'in conjunction with --debug, the tree status '
  565. 'will not be ignored as it usually is in a '
  566. '--debug run.'))
  567. group.add_remote_option(
  568. '--mock-slave-status', dest='mock_slave_status', default=None,
  569. action='store', metavar='MOCK_SLAVE_STATUS_PICKLE_FILE',
  570. help=('Override the result of the _FetchSlaveStatuses method of '
  571. 'MasterSlaveSyncCompletionStage, by specifying a file with a '
  572. 'pickle of the result to be returned.'))
  573. parser.add_option_group(group)
  574. #
  575. # Debug options
  576. #
  577. # Temporary hack; in place till --dry-run replaces --debug.
  578. # pylint: disable=W0212
  579. group = parser.debug_group
  580. debug = [x for x in group.option_list if x._long_opts == ['--debug']][0]
  581. debug.help += ' Currently functions as --dry-run in addition.'
  582. debug.pass_through = True
  583. group.add_option('--notee', action='store_false', dest='tee', default=True,
  584. help=('Disable logging and internal tee process. Primarily '
  585. 'used for debugging cbuildbot itself.'))
  586. return parser
  587. def _FinishParsing(options, args):
  588. """Perform some parsing tasks that need to take place after optparse.
  589. This function needs to be easily testable! Keep it free of
  590. environment-dependent code. Put more detailed usage validation in
  591. _PostParseCheck().
  592. Args:
  593. options: The options object returned by optparse
  594. args: The args object returned by optparse
  595. """
  596. # Populate options.pass_through_args.
  597. accepted, _ = commandline.FilteringParser.FilterArgs(
  598. options.parsed_args, lambda x: x.opt_inst.pass_through)
  599. options.pass_through_args.extend(accepted)
  600. if options.chrome_root:
  601. if options.chrome_rev != constants.CHROME_REV_LOCAL:
  602. cros_build_lib.Die('Chrome rev must be %s if chrome_root is set.' %
  603. constants.CHROME_REV_LOCAL)
  604. elif options.chrome_rev == constants.CHROME_REV_LOCAL:
  605. cros_build_lib.Die('Chrome root must be set if chrome_rev is %s.' %
  606. constants.CHROME_REV_LOCAL)
  607. if options.chrome_version:
  608. if options.chrome_rev != constants.CHROME_REV_SPEC:
  609. cros_build_lib.Die('Chrome rev must be %s if chrome_version is set.' %
  610. constants.CHROME_REV_SPEC)
  611. elif options.chrome_rev == constants.CHROME_REV_SPEC:
  612. cros_build_lib.Die(
  613. 'Chrome rev must not be %s if chrome_version is not set.'
  614. % constants.CHROME_REV_SPEC)
  615. patches = bool(options.gerrit_patches or options.local_patches or
  616. options.rietveld_patches)
  617. if options.remote:
  618. if options.local:
  619. cros_build_lib.Die('Cannot specify both --remote and --local')
  620. # options.channels is a convenient way to detect payloads builds.
  621. if not options.buildbot and not options.channels and not patches:
  622. prompt = ('No patches were provided; are you sure you want to just '
  623. 'run a remote build of %s?' % (
  624. options.branch if options.branch else 'ToT'))
  625. if not cros_build_lib.BooleanPrompt(prompt=prompt, default=False):
  626. cros_build_lib.Die('Must provide patches when running with --remote.')
  627. # --debug needs to be explicitly passed through for remote invocations.
  628. release_mode_with_patches = (options.buildbot and patches and
  629. '--debug' not in options.pass_through_args)
  630. else:
  631. if len(args) > 1:
  632. cros_build_lib.Die('Multiple configs not supported if not running with '
  633. '--remote. Got %r', args)
  634. if options.slaves:
  635. cros_build_lib.Die('Cannot use --slaves if not running with --remote.')
  636. release_mode_with_patches = (options.buildbot and patches and
  637. not options.debug)
  638. # When running in release mode, make sure we are running with checked-in code.
  639. # We want checked-in cbuildbot/scripts to prevent errors, and we want to build
  640. # a release image with checked-in code for CrOS packages.
  641. if release_mode_with_patches:
  642. cros_build_lib.Die(
  643. 'Cannot provide patches when running with --buildbot!')
  644. if options.buildbot and options.remote_trybot:
  645. cros_build_lib.Die(
  646. '--buildbot and --remote-trybot cannot be used together.')
  647. # Record whether --debug was set explicitly vs. it was inferred.
  648. options.debug_forced = False
  649. if options.debug:
  650. options.debug_forced = True
  651. if not options.debug:
  652. # We don't set debug by default for
  653. # 1. --buildbot invocations.
  654. # 2. --remote invocations, because it needs to push changes to the tryjob
  655. # repo.
  656. options.debug = not options.buildbot and not options.remote
  657. # Record the configs targeted.
  658. options.build_targets = args[:]
  659. if constants.BRANCH_UTIL_CONFIG in options.build_targets:
  660. if options.remote:
  661. cros_build_lib.Die(
  662. 'Running %s as a remote tryjob is not yet supported.',
  663. constants.BRANCH_UTIL_CONFIG)
  664. if len(options.build_targets) > 1:
  665. cros_build_lib.Die(
  666. 'Cannot run %s with any other configs.',
  667. constants.BRANCH_UTIL_CONFIG)
  668. if not options.branch_name:
  669. cros_build_lib.Die(
  670. 'Must specify --branch-name with the %s config.',
  671. constants.BRANCH_UTIL_CONFIG)
  672. if options.branch and options.branch != options.branch_name:
  673. cros_build_lib.Die(
  674. 'If --branch is specified with the %s config, it must'
  675. ' have the same value as --branch-name.',
  676. constants.BRANCH_UTIL_CONFIG)
  677. exclusive_opts = {'--version': options.force_version,
  678. '--delete-branch': options.delete_branch,
  679. '--rename-to': options.rename_to}
  680. if 1 != sum(1 for x in exclusive_opts.values() if x):
  681. cros_build_lib.Die('When using the %s config, you must'
  682. ' specifiy one and only one of the following'
  683. ' options: %s.', constants.BRANCH_UTIL_CONFIG,
  684. ', '.join(exclusive_opts.keys()))
  685. # When deleting or renaming a branch, the --branch and --nobootstrap
  686. # options are implied.
  687. if options.delete_branch or options.rename_to:
  688. if not options.branch:
  689. logging.info('Automatically enabling sync to branch %s for this %s '
  690. 'flow.', options.branch_name,
  691. constants.BRANCH_UTIL_CONFIG)
  692. options.branch = options.branch_name
  693. if options.bootstrap:
  694. logging.info('Automatically disabling bootstrap step for this %s flow.',
  695. constants.BRANCH_UTIL_CONFIG)
  696. options.bootstrap = False
  697. elif any([options.delete_branch, options.rename_to, options.branch_name]):
  698. cros_build_lib.Die(
  699. 'Cannot specify --delete-branch, --rename-to or --branch-name when not '
  700. 'running the %s config', constants.BRANCH_UTIL_CONFIG)
  701. # pylint: disable=W0613
  702. def _PostParseCheck(parser, options, args):
  703. """Perform some usage validation after we've parsed the arguments
  704. Args:
  705. parser: Option parser that was used to parse arguments.
  706. options: The options returned by optparse.
  707. args: The args returned by optparse.
  708. """
  709. if not options.branch:
  710. options.branch = git.GetChromiteTrackingBranch()
  711. if not repository.IsARepoRoot(options.sourceroot):
  712. if options.local_patches:
  713. raise Exception('Could not find repo checkout at %s!'
  714. % options.sourceroot)
  715. # Because the default cache dir depends on other options, FindCacheDir
  716. # always returns None, and we setup the default here.
  717. if options.cache_dir is None:
  718. # Note, options.sourceroot is set regardless of the path
  719. # actually existing.
  720. if options.buildroot is not None:
  721. options.cache_dir = os.path.join(options.buildroot, '.cache')
  722. elif os.path.exists(options.sourceroot):
  723. options.cache_dir = os.path.join(options.sourceroot, '.cache')
  724. else:
  725. options.cache_dir = parser.FindCacheDir(parser, options)
  726. options.cache_dir = os.path.abspath(options.cache_dir)
  727. parser.ConfigureCacheDir(options.cache_dir)
  728. osutils.SafeMakedirsNonRoot(options.cache_dir)
  729. if options.local_patches:
  730. options.local_patches = _CheckLocalPatches(
  731. options.sourceroot, options.local_patches)
  732. default = os.environ.get('CBUILDBOT_DEFAULT_MODE')
  733. if (default and not any([options.local, options.buildbot,
  734. options.remote, options.remote_trybot])):
  735. logging.info('CBUILDBOT_DEFAULT_MODE=%s env var detected, using it.'
  736. % default)
  737. default = default.lower()
  738. if default == 'local':
  739. options.local = True
  740. elif default == 'remote':
  741. options.remote = True
  742. elif default == 'buildbot':
  743. options.buildbot = True
  744. else:
  745. cros_build_lib.Die("CBUILDBOT_DEFAULT_MODE value %s isn't supported. "
  746. % default)
  747. # Ensure that all args are legitimate config targets.
  748. invalid_targets = []
  749. for arg in args:
  750. build_config = _GetConfig(arg)
  751. if not build_config:
  752. invalid_targets.append(arg)
  753. logging.error('No such configuraton target: "%s".', arg)
  754. continue
  755. is_payloads_build = build_config.build_type == constants.PAYLOADS_TYPE
  756. if options.channels and not is_payloads_build:
  757. cros_build_lib.Die('--channel must only be used with a payload config,'
  758. ' not target (%s).' % arg)
  759. if not options.channels and is_payloads_build:
  760. cros_build_lib.Die('payload configs (%s) require --channel to do anything'
  761. ' useful.' % arg)
  762. # The --version option is not compatible with an external target unless the
  763. # --buildbot option is specified. More correctly, only "paladin versions"
  764. # will work with external targets, and those are only used with --buildbot.
  765. # If --buildbot is specified, then user should know what they are doing and
  766. # only specify a version that will work. See crbug.com/311648.
  767. if (options.force_version and
  768. not (options.buildbot or build_config.internal)):
  769. cros_build_lib.Die('Cannot specify --version without --buildbot for an'
  770. ' external target (%s).' % arg)
  771. if invalid_targets:
  772. cros_build_lib.Die('One or more invalid configuration targets specified. '
  773. 'You can check the available configs by running '
  774. '`cbuildbot --list --all`')
  775. def _ParseCommandLine(parser, argv):
  776. """Completely parse the commandline arguments"""
  777. (options, args) = parser.parse_args(argv)
  778. # Strip out null arguments.
  779. # TODO(rcui): Remove when buildbot is fixed
  780. args = [arg for arg in args if arg]
  781. # A couple options, like --list, trigger a quick exit.
  782. if options.output_api_version:
  783. print(constants.REEXEC_API_VERSION)
  784. sys.exit(0)
  785. if options.list:
  786. if args:
  787. cros_build_lib.Die('No arguments expected with the --list options.')
  788. _PrintValidConfigs(options.print_all)
  789. sys.exit(0)
  790. if not args:
  791. parser.error('Invalid usage: no configuration targets provided.'
  792. 'Use -h to see usage. Use -l to list supported configs.')
  793. _FinishParsing(options, args)
  794. return options, args
  795. def _SetupConnections(options, build_config):
  796. """Set up CIDB and graphite connections using the appropriate Setup call.
  797. Args:
  798. options: Command line options structure.
  799. build_config: Config object for this build.
  800. """
  801. # TODO(akeshet): This is a temporary workaround to make sure that the cidb
  802. # is not used on waterfalls that the db schema does not support (in particular
  803. # the chromeos.chrome waterfall).
  804. # See crbug.com/406940
  805. waterfall = os.environ.get('BUILDBOT_MASTERNAME', '')
  806. if not waterfall in constants.CIDB_KNOWN_WATERFALLS:
  807. graphite.StatsFactory.SetupMock()
  808. graphite.ESMetadataFactory.SetupReadOnly()
  809. cidb.CIDBConnectionFactory.SetupNoCidb()
  810. return
  811. # TODO(akeshet): Clean up this code once we have better defined flags to
  812. # specify on-or-off waterfall and on-or-off production runs of cbuildbot.
  813. # See crbug.com/331417
  814. # --buildbot runs should use the production services, unless the --debug flag
  815. # is also present in which case they should use the debug cidb and not emit
  816. # stats.
  817. if options.buildbot:
  818. if options.debug:
  819. graphite.StatsFactory.SetupDebug()
  820. graphite.ESMetadataFactory.SetupReadOnly()
  821. cidb.CIDBConnectionFactory.SetupDebugCidb()
  822. return
  823. else:
  824. graphite.StatsFactory.SetupProd()
  825. graphite.ESMetadataFactory.SetupProd()
  826. cidb.CIDBConnectionFactory.SetupProdCidb()
  827. return
  828. # --remote-trybot runs should use the debug database and not emit stats.
  829. # With the exception of pre-cq builds, which should use the production
  830. # database and emit stats.
  831. if options.remote_trybot:
  832. if build_config['pre_cq']:
  833. graphite.StatsFactory.SetupProd()
  834. graphite.ESMetadataFactory.SetupProd()
  835. cidb.CIDBConnectionFactory.SetupProdCidb()
  836. return
  837. else:
  838. graphite.StatsFactory.SetupDebug()
  839. graphite.ESMetadataFactory.SetupReadOnly()
  840. cidb.CIDBConnectionFactory.SetupDebugCidb()
  841. return
  842. # If neither --buildbot nor --remote-trybot flag was used, don't use the
  843. # database or emit stats.
  844. cidb.CIDBConnectionFactory.SetupNoCidb()
  845. graphite.StatsFactory.SetupMock()
  846. graphite.ESMetadataFactory.SetupReadOnly()
  847. # TODO(build): This function is too damn long.
  848. def main(argv):
  849. # Turn on strict sudo checks.
  850. cros_build_lib.STRICT_SUDO = True
  851. # Set umask to 022 so files created by buildbot are readable.
  852. os.umask(0o22)
  853. parser = _CreateParser()
  854. (options, args) = _ParseCommandLine(parser, argv)
  855. _PostParseCheck(parser, options, args)
  856. cros_build_lib.AssertOutsideChroot()
  857. if options.remote:
  858. logging.getLogger().setLevel(logging.WARNING)
  859. # Verify configs are valid.
  860. # If hwtest flag is enabled, post a warning that HWTest step may fail if the
  861. # specified board is not a released platform or it is a generic overlay.
  862. for bot in args:
  863. build_config = _GetConfig(bot)
  864. if options.hwtest:
  865. logging.warning(
  866. 'If %s is not a released platform or it is a generic overlay, '
  867. 'the HWTest step will most likely not run; please ask the lab '
  868. 'team for help if this is unexpected.' % build_config['boards'])
  869. # Verify gerrit patches are valid.
  870. print('Verifying patches...')
  871. patch_pool = trybot_patch_pool.TrybotPatchPool.FromOptions(
  872. gerrit_patches=options.gerrit_patches,
  873. local_patches=options.local_patches,
  874. sourceroot=options.sourceroot,
  875. remote_patches=options.remote_patches)
  876. # --debug need to be explicitly passed through for remote invocations.
  877. if options.buildbot and '--debug' not in options.pass_through_args:
  878. _ConfirmRemoteBuildbotRun()
  879. print('Submitting tryjob...')
  880. tryjob = remote_try.RemoteTryJob(options, args, patch_pool.local_patches)
  881. tryjob.Submit(testjob=options.test_tryjob, dryrun=False)
  882. print('Tryjob submitted!')
  883. print(('Go to %s to view the status of your job.'
  884. % tryjob.GetTrybotWaterfallLink()))
  885. sys.exit(0)
  886. elif (not options.buildbot and not options.remote_trybot
  887. and not options.resume and not options.local):
  888. cros_build_lib.Die('Please use --remote or --local to run trybots')
  889. # Only one config arg is allowed in this mode, which was confirmed earlier.
  890. bot_id = args[-1]
  891. build_config = _GetConfig(bot_id)
  892. # TODO: Re-enable this block when reference_repo support handles this
  893. # properly. (see chromium:330775)
  894. # if options.reference_repo is None:
  895. # repo_path = os.path.join(options.sourceroot, '.repo')
  896. # # If we're being run from a repo checkout, reuse the repo's git pool to
  897. # # cut down on sync time.
  898. # if os.path.exists(repo_path):
  899. # options.reference_repo = options.sourceroot
  900. if options.reference_repo:
  901. if not os.path.exists(options.reference_repo):
  902. parser.error('Reference path %s does not exist'
  903. % (options.reference_repo,))
  904. elif not os.path.exists(os.path.join(options.reference_repo, '.repo')):
  905. parser.error('Reference path %s does not look to be the base of a '
  906. 'repo checkout; no .repo exists in the root.'
  907. % (options.reference_repo,))
  908. if (options.buildbot or options.remote_trybot) and not options.resume:
  909. if not options.cgroups:
  910. parser.error('Options --buildbot/--remote-trybot and --nocgroups cannot '
  911. 'be used together. Cgroup support is required for '
  912. 'buildbot/remote-trybot mode.')
  913. if not cgroups.Cgroup.IsSupported():
  914. parser.error('Option --buildbot/--remote-trybot was given, but this '
  915. 'system does not support cgroups. Failing.')
  916. missing = osutils.FindMissingBinaries(_BUILDBOT_REQUIRED_BINARIES)
  917. if missing:
  918. parser.error('Option --buildbot/--remote-trybot requires the following '
  919. "binaries which couldn't be found in $PATH: %s"
  920. % (', '.join(missing)))
  921. if options.reference_repo:
  922. options.reference_repo = os.path.abspath(options.reference_repo)
  923. if not options.buildroot:
  924. if options.buildbot:
  925. parser.error('Please specify a buildroot with the --buildroot option.')
  926. options.buildroot = _DetermineDefaultBuildRoot(options.sourceroot,
  927. build_config['internal'])
  928. # We use a marker file in the buildroot to indicate the user has
  929. # consented to using this directory.
  930. if not os.path.exists(repository.GetTrybotMarkerPath(options.buildroot)):
  931. _ConfirmBuildRoot(options.buildroot)
  932. # Sanity check of buildroot- specifically that it's not pointing into the
  933. # midst of an existing repo since git-repo doesn't support nesting.
  934. if (not repository.IsARepoRoot(options.buildroot) and
  935. git.FindRepoDir(options.buildroot)):
  936. parser.error('Configured buildroot %s points into a repository checkout, '
  937. 'rather than the root of it. This is not supported.'
  938. % options.buildroot)
  939. if not options.log_dir:
  940. options.log_dir = os.path.join(options.buildroot, _DEFAULT_LOG_DIR)
  941. log_file = None
  942. if options.tee:
  943. log_file = os.path.join(options.log_dir, _BUILDBOT_LOG_FILE)
  944. osutils.SafeMakedirs(options.log_dir)
  945. _BackupPreviousLog(log_file)
  946. with cros_build_lib.ContextManagerStack() as stack:
  947. # TODO(ferringb): update this once
  948. # https://chromium-review.googlesource.com/25359
  949. # is landed- it's sensitive to the manifest-versions cache path.
  950. options.preserve_paths = set(['manifest-versions', '.cache',
  951. 'manifest-versions-internal',
  952. 'chromite-bootstrap'])
  953. if log_file is not None:
  954. # We don't want the critical section to try to clean up the tee process,
  955. # so we run Tee (forked off) outside of it. This prevents a deadlock
  956. # because the Tee process only exits when its pipe is closed, and the
  957. # critical section accidentally holds on to that file handle.
  958. stack.Add(tee.Tee, log_file)
  959. options.preserve_paths.add(_DEFAULT_LOG_DIR)
  960. critical_section = stack.Add(cleanup.EnforcedCleanupSection)
  961. stack.Add(sudo.SudoKeepAlive)
  962. if not options.resume:
  963. # If we're in resume mode, use our parents tempdir rather than
  964. # nesting another layer.
  965. stack.Add(osutils.TempDir, prefix='cbuildbot-tmp', set_global=True)
  966. logging.debug('Cbuildbot tempdir is %r.', os.environ.get('TMP'))
  967. if options.cgroups:
  968. stack.Add(cgroups.SimpleContainChildren, 'cbuildbot')
  969. # Mark everything between EnforcedCleanupSection and here as having to
  970. # be rolled back via the contextmanager cleanup handlers. This
  971. # ensures that sudo bits cannot outlive cbuildbot, that anything
  972. # cgroups would kill gets killed, etc.
  973. stack.Add(critical_section.ForkWatchdog)
  974. if not options.buildbot:
  975. build_config = cbuildbot_config.OverrideConfigForTrybot(
  976. build_config, options)
  977. if options.mock_tree_status is not None:
  978. stack.Add(mock.patch.object, tree_status, '_GetStatus',
  979. return_value=options.mock_tree_status)
  980. if options.mock_slave_status is not None:
  981. with open(options.mock_slave_status, 'r') as f:
  982. mock_statuses = pickle.load(f)
  983. for key, value in mock_statuses.iteritems():
  984. mock_statuses[key] = manifest_version.BuilderStatus(**value)
  985. stack.Add(mock.patch.object,
  986. completion_stages.MasterSlaveSyncCompletionStage,
  987. '_FetchSlaveStatuses',
  988. return_value=mock_statuses)
  989. _SetupConnections(options, build_config)
  990. retry_stats.SetupStats()
  991. # For master-slave builds: Update slave's timeout using master's published
  992. # deadline.
  993. if options.buildbot and options.master_build_id is not None:
  994. slave_timeout = None
  995. if cidb.CIDBConnectionFactory.IsCIDBSetup():
  996. cidb_handle = cidb.CIDBConnectionFactory.GetCIDBConnectionForBuilder()
  997. if cidb_handle:
  998. slave_timeout = cidb_handle.GetTimeToDeadline(options.master_build_id)
  999. if slave_timeout is not None:
  1000. # Cut me some slack. We artificially add a a small time here to the
  1001. # slave_timeout because '0' is handled specially, and because we don't
  1002. # want to timeout while trying to set things up.
  1003. slave_timeout = slave_timeout + 20
  1004. if options.timeout == 0 or slave_timeout < options.timeout:
  1005. logging.info('Updating slave build timeout to %d seconds enforced '
  1006. 'by the master', slave_timeout)
  1007. options.timeout = slave_timeout
  1008. else:
  1009. logging.warning('Could not get master deadline for master-slave build. '
  1010. 'Can not set slave timeout.')
  1011. if options.timeout > 0:
  1012. stack.Add(timeout_util.FatalTimeout, options.timeout)
  1013. _RunBuildStagesWrapper(options, build_config)