blob: e4ce1a113c8e9d0411cb26450c71de7fdf04bdb0 [file] [log] [blame]
dprankefe4602312015-04-08 16:20:351#!/usr/bin/env python
2# Copyright 2015 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
Dirk Pranke8cb6aa782017-12-16 02:31:336"""MB - the Meta-Build wrapper around GN.
dprankefe4602312015-04-08 16:20:357
Dirk Pranked181a1a2017-12-14 01:47:118MB is a wrapper script for GN that can be used to generate build files
dprankefe4602312015-04-08 16:20:359for sets of canned configurations and analyze them.
10"""
11
12from __future__ import print_function
13
14import argparse
15import ast
dprankec3441d12015-06-23 23:01:3516import errno
dprankefe4602312015-04-08 16:20:3517import json
18import os
dpranke68d1cb182015-09-17 23:30:0019import pipes
Dirk Pranke8cb6aa782017-12-16 02:31:3320import platform
dpranked8113582015-06-05 20:08:2521import pprint
dpranke3cec199c2015-09-22 23:29:0222import re
dprankefe4602312015-04-08 16:20:3523import shutil
24import sys
25import subprocess
dprankef61de2f2015-05-14 04:09:5626import tempfile
dprankebbe6d4672016-04-19 06:56:5727import traceback
dpranke867bcf4a2016-03-14 22:28:3228import urllib2
29
30from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3531
dprankeeca4a782016-04-14 01:42:3832CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
33 os.path.abspath(__file__))))
34sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path
35
36import gn_helpers
37
38
dprankefe4602312015-04-08 16:20:3539def main(args):
dprankeee5b51f62015-04-09 00:03:2240 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5941 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3542
43
44class MetaBuildWrapper(object):
45 def __init__(self):
dprankeeca4a782016-04-14 01:42:3846 self.chromium_src_dir = CHROMIUM_SRC_DIR
47 self.default_config = os.path.join(self.chromium_src_dir, 'tools', 'mb',
48 'mb_config.pyl')
kjellander902bcb62016-10-26 06:20:5049 self.default_isolate_map = os.path.join(self.chromium_src_dir, 'testing',
50 'buildbot', 'gn_isolate_map.pyl')
dpranke8c2cfd32015-09-17 20:12:3351 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5152 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3353 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3554 self.args = argparse.Namespace()
55 self.configs = {}
Peter Collingbourne4dfb64a2017-08-12 01:00:5556 self.luci_tryservers = {}
dprankefe4602312015-04-08 16:20:3557 self.masters = {}
58 self.mixins = {}
dprankefe4602312015-04-08 16:20:3559
dpranke255085e2016-03-16 05:23:5960 def Main(self, args):
61 self.ParseArgs(args)
62 try:
63 ret = self.args.func()
64 if ret:
65 self.DumpInputFiles()
66 return ret
67 except KeyboardInterrupt:
dprankecb4a2e242016-09-19 01:13:1468 self.Print('interrupted, exiting')
dpranke255085e2016-03-16 05:23:5969 return 130
dprankebbe6d4672016-04-19 06:56:5770 except Exception:
dpranke255085e2016-03-16 05:23:5971 self.DumpInputFiles()
dprankebbe6d4672016-04-19 06:56:5772 s = traceback.format_exc()
73 for l in s.splitlines():
74 self.Print(l)
dpranke255085e2016-03-16 05:23:5975 return 1
76
dprankefe4602312015-04-08 16:20:3577 def ParseArgs(self, argv):
78 def AddCommonOptions(subp):
79 subp.add_argument('-b', '--builder',
80 help='builder name to look up config from')
81 subp.add_argument('-m', '--master',
82 help='master name to look up config from')
83 subp.add_argument('-c', '--config',
84 help='configuration to analyze')
shenghuazhang804b21542016-10-11 02:06:4985 subp.add_argument('--phase',
86 help='optional phase name (used when builders '
87 'do multiple compiles with different '
88 'arguments in a single build)')
dprankefe4602312015-04-08 16:20:3589 subp.add_argument('-f', '--config-file', metavar='PATH',
90 default=self.default_config,
91 help='path to config file '
kjellander902bcb62016-10-26 06:20:5092 '(default is %(default)s)')
93 subp.add_argument('-i', '--isolate-map-file', metavar='PATH',
kjellander902bcb62016-10-26 06:20:5094 help='path to isolate map file '
Zhiling Huang66958462018-02-03 00:28:2095 '(default is %(default)s)',
96 default=[],
97 action='append',
98 dest='isolate_map_files')
dpranked0c138b2016-04-13 18:28:4799 subp.add_argument('-g', '--goma-dir',
100 help='path to goma directory')
agrieve41d21a72016-04-14 18:02:26101 subp.add_argument('--android-version-code',
Dirk Pranked181a1a2017-12-14 01:47:11102 help='Sets GN arg android_default_version_code')
agrieve41d21a72016-04-14 18:02:26103 subp.add_argument('--android-version-name',
Dirk Pranked181a1a2017-12-14 01:47:11104 help='Sets GN arg android_default_version_name')
dprankefe4602312015-04-08 16:20:35105 subp.add_argument('-n', '--dryrun', action='store_true',
106 help='Do a dry run (i.e., do nothing, just print '
107 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:40108 subp.add_argument('-v', '--verbose', action='store_true',
109 help='verbose logging')
dprankefe4602312015-04-08 16:20:35110
111 parser = argparse.ArgumentParser(prog='mb')
112 subps = parser.add_subparsers()
113
114 subp = subps.add_parser('analyze',
115 help='analyze whether changes to a set of files '
116 'will cause a set of binaries to be rebuilt.')
117 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:25118 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35119 help='path build was generated into.')
120 subp.add_argument('input_path', nargs=1,
121 help='path to a file containing the input arguments '
122 'as a JSON object.')
123 subp.add_argument('output_path', nargs=1,
124 help='path to a file containing the output arguments '
125 'as a JSON object.')
126 subp.set_defaults(func=self.CmdAnalyze)
127
dprankef37aebb92016-09-23 01:14:49128 subp = subps.add_parser('export',
129 help='print out the expanded configuration for'
130 'each builder as a JSON object')
131 subp.add_argument('-f', '--config-file', metavar='PATH',
132 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50133 help='path to config file (default is %(default)s)')
dprankef37aebb92016-09-23 01:14:49134 subp.add_argument('-g', '--goma-dir',
135 help='path to goma directory')
136 subp.set_defaults(func=self.CmdExport)
137
dprankefe4602312015-04-08 16:20:35138 subp = subps.add_parser('gen',
139 help='generate a new set of build files')
140 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39141 subp.add_argument('--swarming-targets-file',
142 help='save runtime dependencies for targets listed '
143 'in file.')
dpranked8113582015-06-05 20:08:25144 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35145 help='path to generate build into')
146 subp.set_defaults(func=self.CmdGen)
147
dpranke751516a2015-10-03 01:11:34148 subp = subps.add_parser('isolate',
149 help='generate the .isolate files for a given'
150 'binary')
151 AddCommonOptions(subp)
152 subp.add_argument('path', nargs=1,
153 help='path build was generated into')
154 subp.add_argument('target', nargs=1,
155 help='ninja target to generate the isolate for')
156 subp.set_defaults(func=self.CmdIsolate)
157
dprankefe4602312015-04-08 16:20:35158 subp = subps.add_parser('lookup',
159 help='look up the command for a given config or '
160 'builder')
161 AddCommonOptions(subp)
162 subp.set_defaults(func=self.CmdLookup)
163
dpranke030d7a6d2016-03-26 17:23:50164 subp = subps.add_parser(
165 'run',
166 help='build and run the isolated version of a '
167 'binary',
168 formatter_class=argparse.RawDescriptionHelpFormatter)
169 subp.description = (
170 'Build, isolate, and run the given binary with the command line\n'
171 'listed in the isolate. You may pass extra arguments after the\n'
172 'target; use "--" if the extra arguments need to include switches.\n'
173 '\n'
174 'Examples:\n'
175 '\n'
176 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
177 ' //out/Default content_browsertests\n'
178 '\n'
179 ' % tools/mb/mb.py run out/Default content_browsertests\n'
180 '\n'
181 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
182 ' --test-launcher-retry-limit=0'
183 '\n'
184 )
dpranke751516a2015-10-03 01:11:34185 AddCommonOptions(subp)
186 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
187 help='Number of jobs to pass to ninja')
188 subp.add_argument('--no-build', dest='build', default=True,
189 action='store_false',
190 help='Do not build, just isolate and run')
191 subp.add_argument('path', nargs=1,
dpranke030d7a6d2016-03-26 17:23:50192 help=('path to generate build into (or use).'
193 ' This can be either a regular path or a '
194 'GN-style source-relative path like '
195 '//out/Default.'))
Dirk Pranke8cb6aa782017-12-16 02:31:33196 subp.add_argument('-s', '--swarmed', action='store_true',
197 help='Run under swarming with the default dimensions')
198 subp.add_argument('-d', '--dimension', default=[], action='append', nargs=2,
199 dest='dimensions', metavar='FOO bar',
200 help='dimension to filter on')
201 subp.add_argument('--no-default-dimensions', action='store_false',
202 dest='default_dimensions', default=True,
203 help='Do not automatically add dimensions to the task')
dpranke751516a2015-10-03 01:11:34204 subp.add_argument('target', nargs=1,
205 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50206 subp.add_argument('extra_args', nargs='*',
207 help=('extra args to pass to the isolate to run. Use '
208 '"--" as the first arg if you need to pass '
209 'switches'))
dpranke751516a2015-10-03 01:11:34210 subp.set_defaults(func=self.CmdRun)
211
dprankefe4602312015-04-08 16:20:35212 subp = subps.add_parser('validate',
213 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17214 subp.add_argument('-f', '--config-file', metavar='PATH',
215 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50216 help='path to config file (default is %(default)s)')
dprankefe4602312015-04-08 16:20:35217 subp.set_defaults(func=self.CmdValidate)
218
Peter Collingbourne4dfb64a2017-08-12 01:00:55219 subp = subps.add_parser('gerrit-buildbucket-config',
220 help='Print buildbucket.config for gerrit '
221 '(see MB user guide)')
222 subp.add_argument('-f', '--config-file', metavar='PATH',
223 default=self.default_config,
224 help='path to config file (default is %(default)s)')
225 subp.set_defaults(func=self.CmdBuildbucket)
226
dprankefe4602312015-04-08 16:20:35227 subp = subps.add_parser('help',
228 help='Get help on a subcommand.')
229 subp.add_argument(nargs='?', action='store', dest='subcommand',
230 help='The command to get help for.')
231 subp.set_defaults(func=self.CmdHelp)
232
233 self.args = parser.parse_args(argv)
234
dprankeb2be10a2016-02-22 17:11:00235 def DumpInputFiles(self):
236
dprankef7b7eb7a2016-03-28 22:42:59237 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00238 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59239 self.Print("\n# To recreate the file passed to %s:" % arg_name)
dprankecb4a2e242016-09-19 01:13:14240 self.Print("%% cat > %s <<EOF" % path)
dprankeb2be10a2016-02-22 17:11:00241 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59242 self.Print(contents)
243 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00244
dprankef7b7eb7a2016-03-28 22:42:59245 if getattr(self.args, 'input_path', None):
246 DumpContentsOfFilePassedTo(
247 'argv[0] (input_path)', self.args.input_path[0])
248 if getattr(self.args, 'swarming_targets_file', None):
249 DumpContentsOfFilePassedTo(
250 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00251
dprankefe4602312015-04-08 16:20:35252 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34253 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11254 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35255
dprankef37aebb92016-09-23 01:14:49256 def CmdExport(self):
257 self.ReadConfigFile()
258 obj = {}
259 for master, builders in self.masters.items():
260 obj[master] = {}
261 for builder in builders:
262 config = self.masters[master][builder]
263 if not config:
264 continue
265
shenghuazhang804b21542016-10-11 02:06:49266 if isinstance(config, dict):
267 args = {k: self.FlattenConfig(v)['gn_args']
268 for k, v in config.items()}
dprankef37aebb92016-09-23 01:14:49269 elif config.startswith('//'):
270 args = config
271 else:
272 args = self.FlattenConfig(config)['gn_args']
273 if 'error' in args:
274 continue
275
276 obj[master][builder] = args
277
278 # Dump object and trim trailing whitespace.
279 s = '\n'.join(l.rstrip() for l in
280 json.dumps(obj, sort_keys=True, indent=2).splitlines())
281 self.Print(s)
282 return 0
283
dprankefe4602312015-04-08 16:20:35284 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34285 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11286 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35287
288 def CmdHelp(self):
289 if self.args.subcommand:
290 self.ParseArgs([self.args.subcommand, '--help'])
291 else:
292 self.ParseArgs(['--help'])
293
dpranke751516a2015-10-03 01:11:34294 def CmdIsolate(self):
295 vals = self.GetConfig()
296 if not vals:
297 return 1
Dirk Pranked181a1a2017-12-14 01:47:11298 return self.RunGNIsolate(vals)
dpranke751516a2015-10-03 01:11:34299
300 def CmdLookup(self):
301 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11302 cmd = self.GNCmd('gen', '_path_')
303 gn_args = self.GNArgs(vals)
304 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
305 env = None
dpranke751516a2015-10-03 01:11:34306
307 self.PrintCmd(cmd, env)
308 return 0
309
310 def CmdRun(self):
311 vals = self.GetConfig()
312 if not vals:
313 return 1
314
315 build_dir = self.args.path[0]
316 target = self.args.target[0]
317
Dirk Pranked181a1a2017-12-14 01:47:11318 if self.args.build:
319 ret = self.Build(target)
dpranke751516a2015-10-03 01:11:34320 if ret:
321 return ret
Dirk Pranked181a1a2017-12-14 01:47:11322 ret = self.RunGNIsolate(vals)
323 if ret:
324 return ret
dpranke751516a2015-10-03 01:11:34325
Dirk Pranke8cb6aa782017-12-16 02:31:33326 if self.args.swarmed:
327 return self._RunUnderSwarming(build_dir, target)
328 else:
329 return self._RunLocallyIsolated(build_dir, target)
330
331 def _RunUnderSwarming(self, build_dir, target):
332 # TODO(dpranke): Look up the information for the target in
333 # the //testing/buildbot.json file, if possible, so that we
334 # can determine the isolate target, command line, and additional
335 # swarming parameters, if possible.
336 #
337 # TODO(dpranke): Also, add support for sharding and merging results.
338 dimensions = []
339 for k, v in self._DefaultDimensions() + self.args.dimensions:
340 dimensions += ['-d', k, v]
341
342 cmd = [
343 self.executable,
344 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
345 'archive',
346 '-s',
347 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
348 '-I', 'isolateserver.appspot.com',
349 ]
350 ret, out, _ = self.Run(cmd, force_verbose=False)
351 if ret:
352 return ret
353
354 isolated_hash = out.splitlines()[0].split()[0]
355 cmd = [
356 self.executable,
357 self.PathJoin('tools', 'swarming_client', 'swarming.py'),
358 'run',
359 '-s', isolated_hash,
360 '-I', 'isolateserver.appspot.com',
361 '-S', 'chromium-swarm.appspot.com',
362 ] + dimensions
363 if self.args.extra_args:
364 cmd += ['--'] + self.args.extra_args
365 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
366 return ret
367
368 def _RunLocallyIsolated(self, build_dir, target):
dpranke030d7a6d2016-03-26 17:23:50369 cmd = [
dpranke751516a2015-10-03 01:11:34370 self.executable,
371 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
372 'run',
373 '-s',
dpranke030d7a6d2016-03-26 17:23:50374 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
Dirk Pranke8cb6aa782017-12-16 02:31:33375 ]
dpranke030d7a6d2016-03-26 17:23:50376 if self.args.extra_args:
Dirk Pranke8cb6aa782017-12-16 02:31:33377 cmd += ['--'] + self.args.extra_args
378 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
dpranke751516a2015-10-03 01:11:34379 return ret
380
Dirk Pranke8cb6aa782017-12-16 02:31:33381 def _DefaultDimensions(self):
382 if not self.args.default_dimensions:
383 return []
384
385 # This code is naive and just picks reasonable defaults per platform.
Nico Weberd94b71a2018-02-22 22:00:30386 # TODO(thakis): This assumes that host platform is the same as
387 # target platform.
Dirk Pranke8cb6aa782017-12-16 02:31:33388 if self.platform == 'darwin':
389 os_dim = ('os', 'Mac-10.12')
390 elif self.platform.startswith('linux'):
391 os_dim = ('os', 'Ubuntu-14.04')
392 elif self.platform == 'win32':
393 os_dim = ('os', 'Windows-10-14393')
394 else:
395 raise MBErr('unrecognized platform string "%s"' % self.platform)
396
397 return [('pool', 'Chrome'),
398 ('cpu', 'x86-64'),
399 os_dim]
400
Peter Collingbourne4dfb64a2017-08-12 01:00:55401 def CmdBuildbucket(self):
402 self.ReadConfigFile()
403
404 self.Print('# This file was generated using '
405 '"tools/mb/mb.py gerrit-buildbucket-config".')
406
407 for luci_tryserver in sorted(self.luci_tryservers):
408 self.Print('[bucket "luci.%s"]' % luci_tryserver)
409 for bot in sorted(self.luci_tryservers[luci_tryserver]):
410 self.Print('\tbuilder = %s' % bot)
411
412 for master in sorted(self.masters):
413 if master.startswith('tryserver.'):
414 self.Print('[bucket "master.%s"]' % master)
415 for bot in sorted(self.masters[master]):
416 self.Print('\tbuilder = %s' % bot)
417
418 return 0
419
dpranke0cafc162016-03-19 00:41:10420 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35421 errs = []
422
423 # Read the file to make sure it parses.
424 self.ReadConfigFile()
425
dpranke3be00142016-03-17 22:46:04426 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35427 all_configs = {}
dprankefe4602312015-04-08 16:20:35428 for master in self.masters:
dpranke3be00142016-03-17 22:46:04429 for config in self.masters[master].values():
shenghuazhang804b21542016-10-11 02:06:49430 if isinstance(config, dict):
431 for c in config.values():
dprankeb9380a12016-07-21 21:44:09432 all_configs[c] = master
433 else:
434 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35435
dpranke9dd5e252016-04-14 04:23:09436 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35437 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09438 if config.startswith('//'):
439 if not self.Exists(self.ToAbsPath(config)):
440 errs.append('Unknown args file "%s" referenced from "%s".' %
441 (config, loc))
442 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35443 errs.append('Unknown config "%s" referenced from "%s".' %
444 (config, loc))
445
446 # Check that every actual config is actually referenced.
447 for config in self.configs:
448 if not config in all_configs:
449 errs.append('Unused config "%s".' % config)
450
451 # Figure out the whole list of mixins, and check that every mixin
452 # listed by a config or another mixin actually exists.
453 referenced_mixins = set()
454 for config, mixins in self.configs.items():
455 for mixin in mixins:
456 if not mixin in self.mixins:
457 errs.append('Unknown mixin "%s" referenced by config "%s".' %
458 (mixin, config))
459 referenced_mixins.add(mixin)
460
461 for mixin in self.mixins:
462 for sub_mixin in self.mixins[mixin].get('mixins', []):
463 if not sub_mixin in self.mixins:
464 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
465 (sub_mixin, mixin))
466 referenced_mixins.add(sub_mixin)
467
468 # Check that every mixin defined is actually referenced somewhere.
469 for mixin in self.mixins:
470 if not mixin in referenced_mixins:
471 errs.append('Unreferenced mixin "%s".' % mixin)
472
dpranke255085e2016-03-16 05:23:59473 # If we're checking the Chromium config, check that the 'chromium' bots
474 # which build public artifacts do not include the chrome_with_codecs mixin.
475 if self.args.config_file == self.default_config:
476 if 'chromium' in self.masters:
477 for builder in self.masters['chromium']:
478 config = self.masters['chromium'][builder]
479 def RecurseMixins(current_mixin):
480 if current_mixin == 'chrome_with_codecs':
481 errs.append('Public artifact builder "%s" can not contain the '
482 '"chrome_with_codecs" mixin.' % builder)
483 return
484 if not 'mixins' in self.mixins[current_mixin]:
485 return
486 for mixin in self.mixins[current_mixin]['mixins']:
487 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41488
dpranke255085e2016-03-16 05:23:59489 for mixin in self.configs[config]:
490 RecurseMixins(mixin)
491 else:
492 errs.append('Missing "chromium" master. Please update this '
493 'proprietary codecs check with the name of the master '
494 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41495
dprankefe4602312015-04-08 16:20:35496 if errs:
dpranke4323c80632015-08-10 22:53:54497 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17498 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35499
dpranke0cafc162016-03-19 00:41:10500 if print_ok:
501 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35502 return 0
503
dprankefe4602312015-04-08 16:20:35504 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34505 build_dir = self.args.path[0]
506
dprankef37aebb92016-09-23 01:14:49507 vals = self.DefaultVals()
dpranke751516a2015-10-03 01:11:34508 if self.args.builder or self.args.master or self.args.config:
509 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11510 # Re-run gn gen in order to ensure the config is consistent with the
511 # build dir.
512 self.RunGNGen(vals)
dpranke751516a2015-10-03 01:11:34513 return vals
514
Dirk Pranked181a1a2017-12-14 01:47:11515 toolchain_path = self.PathJoin(self.ToAbsPath(build_dir),
516 'toolchain.ninja')
517 if not self.Exists(toolchain_path):
518 self.Print('Must either specify a path to an existing GN build dir '
519 'or pass in a -m/-b pair or a -c flag to specify the '
520 'configuration')
521 return {}
dpranke751516a2015-10-03 01:11:34522
Dirk Pranked181a1a2017-12-14 01:47:11523 vals['gn_args'] = self.GNArgsFromDir(build_dir)
dpranke751516a2015-10-03 01:11:34524 return vals
525
dprankef37aebb92016-09-23 01:14:49526 def GNArgsFromDir(self, build_dir):
brucedawsonecc0c1cd2016-06-02 18:24:58527 args_contents = ""
528 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
529 if self.Exists(gn_args_path):
530 args_contents = self.ReadFile(gn_args_path)
dpranke751516a2015-10-03 01:11:34531 gn_args = []
532 for l in args_contents.splitlines():
533 fields = l.split(' ')
534 name = fields[0]
535 val = ' '.join(fields[2:])
536 gn_args.append('%s=%s' % (name, val))
537
dprankef37aebb92016-09-23 01:14:49538 return ' '.join(gn_args)
dpranke751516a2015-10-03 01:11:34539
540 def Lookup(self):
dprankef37aebb92016-09-23 01:14:49541 vals = self.ReadIOSBotConfig()
dprankee0f486f2015-11-19 23:42:00542 if not vals:
543 self.ReadConfigFile()
544 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09545 if config.startswith('//'):
546 if not self.Exists(self.ToAbsPath(config)):
547 raise MBErr('args file "%s" not found' % config)
dprankef37aebb92016-09-23 01:14:49548 vals = self.DefaultVals()
549 vals['args_file'] = config
dpranke9dd5e252016-04-14 04:23:09550 else:
551 if not config in self.configs:
552 raise MBErr('Config "%s" not found in %s' %
553 (config, self.args.config_file))
554 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34555 return vals
dprankefe4602312015-04-08 16:20:35556
dprankef37aebb92016-09-23 01:14:49557 def ReadIOSBotConfig(self):
dprankee0f486f2015-11-19 23:42:00558 if not self.args.master or not self.args.builder:
559 return {}
560 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
561 self.args.master, self.args.builder + '.json')
562 if not self.Exists(path):
563 return {}
564
565 contents = json.loads(self.ReadFile(path))
dprankee0f486f2015-11-19 23:42:00566 gn_args = ' '.join(contents.get('gn_args', []))
567
dprankef37aebb92016-09-23 01:14:49568 vals = self.DefaultVals()
569 vals['gn_args'] = gn_args
dprankef37aebb92016-09-23 01:14:49570 return vals
dprankee0f486f2015-11-19 23:42:00571
dprankefe4602312015-04-08 16:20:35572 def ReadConfigFile(self):
573 if not self.Exists(self.args.config_file):
574 raise MBErr('config file not found at %s' % self.args.config_file)
575
576 try:
577 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
578 except SyntaxError as e:
579 raise MBErr('Failed to parse config file "%s": %s' %
580 (self.args.config_file, e))
581
dprankefe4602312015-04-08 16:20:35582 self.configs = contents['configs']
Peter Collingbourne4dfb64a2017-08-12 01:00:55583 self.luci_tryservers = contents.get('luci_tryservers', {})
dprankefe4602312015-04-08 16:20:35584 self.masters = contents['masters']
585 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35586
dprankecb4a2e242016-09-19 01:13:14587 def ReadIsolateMap(self):
Zhiling Huang66958462018-02-03 00:28:20588 if not self.args.isolate_map_files:
589 self.args.isolate_map_files = [self.default_isolate_map]
590
591 for f in self.args.isolate_map_files:
592 if not self.Exists(f):
593 raise MBErr('isolate map file not found at %s' % f)
594 isolate_maps = {}
595 for isolate_map in self.args.isolate_map_files:
596 try:
597 isolate_map = ast.literal_eval(self.ReadFile(isolate_map))
598 duplicates = set(isolate_map).intersection(isolate_maps)
599 if duplicates:
600 raise MBErr(
601 'Duplicate targets in isolate map files: %s.' %
602 ', '.join(duplicates))
603 isolate_maps.update(isolate_map)
604 except SyntaxError as e:
605 raise MBErr(
606 'Failed to parse isolate map file "%s": %s' % (isolate_map, e))
607 return isolate_maps
dprankecb4a2e242016-09-19 01:13:14608
dprankefe4602312015-04-08 16:20:35609 def ConfigFromArgs(self):
610 if self.args.config:
611 if self.args.master or self.args.builder:
612 raise MBErr('Can not specific both -c/--config and -m/--master or '
613 '-b/--builder')
614
615 return self.args.config
616
617 if not self.args.master or not self.args.builder:
618 raise MBErr('Must specify either -c/--config or '
619 '(-m/--master and -b/--builder)')
620
621 if not self.args.master in self.masters:
622 raise MBErr('Master name "%s" not found in "%s"' %
623 (self.args.master, self.args.config_file))
624
625 if not self.args.builder in self.masters[self.args.master]:
626 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
627 (self.args.builder, self.args.master, self.args.config_file))
628
dprankeb9380a12016-07-21 21:44:09629 config = self.masters[self.args.master][self.args.builder]
shenghuazhang804b21542016-10-11 02:06:49630 if isinstance(config, dict):
dprankeb9380a12016-07-21 21:44:09631 if self.args.phase is None:
632 raise MBErr('Must specify a build --phase for %s on %s' %
633 (self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49634 phase = str(self.args.phase)
635 if phase not in config:
636 raise MBErr('Phase %s doesn\'t exist for %s on %s' %
dprankeb9380a12016-07-21 21:44:09637 (phase, self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49638 return config[phase]
dprankeb9380a12016-07-21 21:44:09639
640 if self.args.phase is not None:
641 raise MBErr('Must not specify a build --phase for %s on %s' %
642 (self.args.builder, self.args.master))
643 return config
dprankefe4602312015-04-08 16:20:35644
645 def FlattenConfig(self, config):
646 mixins = self.configs[config]
dprankef37aebb92016-09-23 01:14:49647 vals = self.DefaultVals()
dprankefe4602312015-04-08 16:20:35648
649 visited = []
650 self.FlattenMixins(mixins, vals, visited)
651 return vals
652
dprankef37aebb92016-09-23 01:14:49653 def DefaultVals(self):
654 return {
655 'args_file': '',
656 'cros_passthrough': False,
657 'gn_args': '',
dprankef37aebb92016-09-23 01:14:49658 }
659
dprankefe4602312015-04-08 16:20:35660 def FlattenMixins(self, mixins, vals, visited):
661 for m in mixins:
662 if m not in self.mixins:
663 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22664
dprankefe4602312015-04-08 16:20:35665 visited.append(m)
666
667 mixin_vals = self.mixins[m]
dpranke73ed0d62016-04-25 19:18:34668
669 if 'cros_passthrough' in mixin_vals:
670 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
Dirk Pranke6b99f072017-04-05 00:58:30671 if 'args_file' in mixin_vals:
672 if vals['args_file']:
673 raise MBErr('args_file specified multiple times in mixins '
674 'for %s on %s' % (self.args.builder, self.args.master))
675 vals['args_file'] = mixin_vals['args_file']
dprankefe4602312015-04-08 16:20:35676 if 'gn_args' in mixin_vals:
677 if vals['gn_args']:
678 vals['gn_args'] += ' ' + mixin_vals['gn_args']
679 else:
680 vals['gn_args'] = mixin_vals['gn_args']
dpranke73ed0d62016-04-25 19:18:34681
dprankefe4602312015-04-08 16:20:35682 if 'mixins' in mixin_vals:
683 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
684 return vals
685
Dirk Prankea3727f92017-07-17 17:30:33686 def RunGNGen(self, vals, compute_grit_inputs_for_analyze=False):
dpranke751516a2015-10-03 01:11:34687 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50688
dprankeeca4a782016-04-14 01:42:38689 cmd = self.GNCmd('gen', build_dir, '--check')
690 gn_args = self.GNArgs(vals)
Dirk Prankea3727f92017-07-17 17:30:33691 if compute_grit_inputs_for_analyze:
692 gn_args += ' compute_grit_inputs_for_analyze=true'
dprankeeca4a782016-04-14 01:42:38693
694 # Since GN hasn't run yet, the build directory may not even exist.
695 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
696
697 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54698 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39699
700 swarming_targets = []
dpranke751516a2015-10-03 01:11:34701 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39702 # We need GN to generate the list of runtime dependencies for
703 # the compile targets listed (one per line) in the file so
dprankecb4a2e242016-09-19 01:13:14704 # we can run them via swarming. We use gn_isolate_map.pyl to convert
dpranke74559b52015-06-10 21:20:39705 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00706 path = self.args.swarming_targets_file
707 if not self.Exists(path):
708 self.WriteFailureAndRaise('"%s" does not exist' % path,
709 output_path=None)
710 contents = self.ReadFile(path)
711 swarming_targets = set(contents.splitlines())
dprankeb2be10a2016-02-22 17:11:00712
dprankecb4a2e242016-09-19 01:13:14713 isolate_map = self.ReadIsolateMap()
714 err, labels = self.MapTargetsToLabels(isolate_map, swarming_targets)
dprankeb2be10a2016-02-22 17:11:00715 if err:
dprankecb4a2e242016-09-19 01:13:14716 raise MBErr(err)
dpranke74559b52015-06-10 21:20:39717
dpranke751516a2015-10-03 01:11:34718 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankecb4a2e242016-09-19 01:13:14719 self.WriteFile(gn_runtime_deps_path, '\n'.join(labels) + '\n')
dpranke74559b52015-06-10 21:20:39720 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
721
dprankefe4602312015-04-08 16:20:35722 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40723 if ret:
724 # If `gn gen` failed, we should exit early rather than trying to
725 # generate isolates. Run() will have already logged any error output.
726 self.Print('GN gen failed: %d' % ret)
727 return ret
dpranke74559b52015-06-10 21:20:39728
jbudoricke3c4f95e2016-04-28 23:17:38729 android = 'target_os="android"' in vals['gn_args']
Kevin Marshallf35fa5f2018-01-29 19:24:42730 fuchsia = 'target_os="fuchsia"' in vals['gn_args']
Nico Weberd94b71a2018-02-22 22:00:30731 win = self.platform == 'win32' or 'target_os="win"' in vals['gn_args']
dpranke74559b52015-06-10 21:20:39732 for target in swarming_targets:
jbudoricke3c4f95e2016-04-28 23:17:38733 if android:
734 # Android targets may be either android_apk or executable. The former
jbudorick91c8a6012016-01-29 23:20:02735 # will result in runtime_deps associated with the stamp file, while the
736 # latter will result in runtime_deps associated with the executable.
dprankecb4a2e242016-09-19 01:13:14737 label = isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02738 runtime_deps_targets = [
dprankecb4a2e242016-09-19 01:13:14739 target + '.runtime_deps',
dpranke48ccf8f2016-03-28 23:58:28740 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
Kevin Marshallf35fa5f2018-01-29 19:24:42741 elif fuchsia:
742 # Only emit a runtime deps file for the group() target on Fuchsia.
743 label = isolate_map[target]['label']
744 runtime_deps_targets = [
745 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
dprankecb4a2e242016-09-19 01:13:14746 elif (isolate_map[target]['type'] == 'script' or
747 isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11748 # For script targets, the build target is usually a group,
749 # for which gn generates the runtime_deps next to the stamp file
eyaich82d5ac942016-11-03 12:13:49750 # for the label, which lives under the obj/ directory, but it may
751 # also be an executable.
dprankecb4a2e242016-09-19 01:13:14752 label = isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28753 runtime_deps_targets = [
754 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
Nico Weberd94b71a2018-02-22 22:00:30755 if win:
eyaich82d5ac942016-11-03 12:13:49756 runtime_deps_targets += [ target + '.exe.runtime_deps' ]
757 else:
758 runtime_deps_targets += [ target + '.runtime_deps' ]
Nico Weberd94b71a2018-02-22 22:00:30759 elif win:
dpranke48ccf8f2016-03-28 23:58:28760 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52761 else:
dpranke48ccf8f2016-03-28 23:58:28762 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02763
dpranke48ccf8f2016-03-28 23:58:28764 for r in runtime_deps_targets:
765 runtime_deps_path = self.ToAbsPath(build_dir, r)
766 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02767 break
768 else:
dpranke48ccf8f2016-03-28 23:58:28769 raise MBErr('did not generate any of %s' %
770 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39771
dprankecb4a2e242016-09-19 01:13:14772 command, extra_files = self.GetIsolateCommand(target, vals)
dpranked5b2b9432015-06-23 16:55:30773
dpranke48ccf8f2016-03-28 23:58:28774 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30775
dpranke751516a2015-10-03 01:11:34776 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
777 extra_files)
dpranked5b2b9432015-06-23 16:55:30778
dpranke751516a2015-10-03 01:11:34779 return 0
780
781 def RunGNIsolate(self, vals):
dprankecb4a2e242016-09-19 01:13:14782 target = self.args.target[0]
783 isolate_map = self.ReadIsolateMap()
784 err, labels = self.MapTargetsToLabels(isolate_map, [target])
785 if err:
786 raise MBErr(err)
787 label = labels[0]
dpranke751516a2015-10-03 01:11:34788
789 build_dir = self.args.path[0]
dprankecb4a2e242016-09-19 01:13:14790 command, extra_files = self.GetIsolateCommand(target, vals)
dpranke751516a2015-10-03 01:11:34791
dprankeeca4a782016-04-14 01:42:38792 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20793 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34794 if ret:
dpranke030d7a6d2016-03-26 17:23:50795 if out:
796 self.Print(out)
dpranke751516a2015-10-03 01:11:34797 return ret
798
799 runtime_deps = out.splitlines()
800
801 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
802 extra_files)
803
804 ret, _, _ = self.Run([
805 self.executable,
806 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
807 'check',
808 '-i',
809 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
810 '-s',
811 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
812 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30813
dprankefe4602312015-04-08 16:20:35814 return ret
815
dpranke751516a2015-10-03 01:11:34816 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
817 extra_files):
818 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
819 self.WriteFile(isolate_path,
820 pprint.pformat({
821 'variables': {
822 'command': command,
823 'files': sorted(runtime_deps + extra_files),
824 }
825 }) + '\n')
826
827 self.WriteJSON(
828 {
829 'args': [
830 '--isolated',
831 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
832 '--isolate',
833 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
834 ],
835 'dir': self.chromium_src_dir,
836 'version': 1,
837 },
838 isolate_path + 'd.gen.json',
839 )
840
dprankecb4a2e242016-09-19 01:13:14841 def MapTargetsToLabels(self, isolate_map, targets):
842 labels = []
843 err = ''
844
dprankecb4a2e242016-09-19 01:13:14845 for target in targets:
846 if target == 'all':
847 labels.append(target)
848 elif target.startswith('//'):
849 labels.append(target)
850 else:
851 if target in isolate_map:
thakis024d6f32017-05-16 23:21:42852 if isolate_map[target]['type'] == 'unknown':
dprankecb4a2e242016-09-19 01:13:14853 err += ('test target "%s" type is unknown\n' % target)
854 else:
thakis024d6f32017-05-16 23:21:42855 labels.append(isolate_map[target]['label'])
dprankecb4a2e242016-09-19 01:13:14856 else:
857 err += ('target "%s" not found in '
858 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
859
860 return err, labels
861
dprankeeca4a782016-04-14 01:42:38862 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51863 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20864 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51865 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20866 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51867 else:
dpranke40da0202016-02-13 05:05:20868 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38869
dpranke40da0202016-02-13 05:05:20870 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranke10118bf2016-09-16 23:16:08871 return [gn_path, subcommand, path] + list(args)
dpranke9aba8b212016-09-16 22:52:52872
dprankecb4a2e242016-09-19 01:13:14873
dprankeeca4a782016-04-14 01:42:38874 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34875 if vals['cros_passthrough']:
876 if not 'GN_ARGS' in os.environ:
877 raise MBErr('MB is expecting GN_ARGS to be in the environment')
878 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16879 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30880 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34881 gn_args)
882 else:
883 gn_args = vals['gn_args']
884
dpranked0c138b2016-04-13 18:28:47885 if self.args.goma_dir:
886 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38887
agrieve41d21a72016-04-14 18:02:26888 android_version_code = self.args.android_version_code
889 if android_version_code:
890 gn_args += ' android_default_version_code="%s"' % android_version_code
891
892 android_version_name = self.args.android_version_name
893 if android_version_name:
894 gn_args += ' android_default_version_name="%s"' % android_version_name
895
dprankeeca4a782016-04-14 01:42:38896 # Canonicalize the arg string into a sorted, newline-separated list
897 # of key-value pairs, and de-dup the keys if need be so that only
898 # the last instance of each arg is listed.
899 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
900
dpranke9dd5e252016-04-14 04:23:09901 args_file = vals.get('args_file', None)
902 if args_file:
903 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38904 return gn_args
dprankefe4602312015-04-08 16:20:35905
dprankecb4a2e242016-09-19 01:13:14906 def GetIsolateCommand(self, target, vals):
kylechar50abf5a2016-11-29 16:03:07907 isolate_map = self.ReadIsolateMap()
908
Scott Graham3be4b4162017-09-12 00:41:41909 is_android = 'target_os="android"' in vals['gn_args']
910 is_fuchsia = 'target_os="fuchsia"' in vals['gn_args']
Nico Weberd94b71a2018-02-22 22:00:30911 is_win = self.platform == 'win32' or 'target_os="win"' in vals['gn_args']
jbudoricke8428732016-02-02 02:17:06912
kylechar39705682017-01-19 14:37:23913 # This should be true if tests with type='windowed_test_launcher' are
914 # expected to run using xvfb. For example, Linux Desktop, X11 CrOS and
msisovaea52732017-03-21 08:08:08915 # Ozone CrOS builds. Note that one Ozone build can be used to run differen
916 # backends. Currently, tests are executed for the headless and X11 backends
917 # and both can run under Xvfb.
918 # TODO(tonikitoo,msisov,fwang): Find a way to run tests for the Wayland
919 # backend.
Scott Graham3be4b4162017-09-12 00:41:41920 use_xvfb = self.platform == 'linux2' and not is_android and not is_fuchsia
dpranked8113582015-06-05 20:08:25921
922 asan = 'is_asan=true' in vals['gn_args']
923 msan = 'is_msan=true' in vals['gn_args']
924 tsan = 'is_tsan=true' in vals['gn_args']
pcc46233c22017-06-20 22:11:41925 cfi_diag = 'use_cfi_diag=true' in vals['gn_args']
dpranked8113582015-06-05 20:08:25926
dprankecb4a2e242016-09-19 01:13:14927 test_type = isolate_map[target]['type']
dprankefe0d35e2016-02-05 02:43:59928
dprankecb4a2e242016-09-19 01:13:14929 executable = isolate_map[target].get('executable', target)
Nico Weberd94b71a2018-02-22 22:00:30930 executable_suffix = '.exe' if is_win else ''
dprankefe0d35e2016-02-05 02:43:59931
dprankea55584f12015-07-22 00:52:47932 cmdline = []
Andrii Shyshkalovc158e0102018-01-10 05:52:00933 extra_files = [
934 '../../.vpython',
935 '../../testing/test_env.py',
936 ]
dpranked8113582015-06-05 20:08:25937
dprankecb4a2e242016-09-19 01:13:14938 if test_type == 'nontest':
939 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
940 output_path=None)
941
Scott Graham3be4b4162017-09-12 00:41:41942 if is_android and test_type != "script":
bpastenee428ea92017-02-17 02:20:32943 cmdline = [
John Budorickfb97a852017-12-20 20:10:19944 '../../testing/test_env.py',
hzl9b15df52017-03-23 23:43:04945 '../../build/android/test_wrapper/logdog_wrapper.py',
946 '--target', target,
hzl9ae14452017-04-04 23:38:02947 '--logdog-bin-cmd', '../../bin/logdog_butler',
hzlfc66094f2017-05-18 00:50:48948 '--store-tombstones']
Scott Graham3be4b4162017-09-12 00:41:41949 elif is_fuchsia and test_type != 'script':
John Budorickfb97a852017-12-20 20:10:19950 cmdline = [
951 '../../testing/test_env.py',
952 os.path.join('bin', 'run_%s' % target),
953 ]
kylechar39705682017-01-19 14:37:23954 elif use_xvfb and test_type == 'windowed_test_launcher':
Andrii Shyshkalovc158e0102018-01-10 05:52:00955 extra_files.append('../../testing/xvfb.py')
dprankea55584f12015-07-22 00:52:47956 cmdline = [
dprankefe0d35e2016-02-05 02:43:59957 '../../testing/xvfb.py',
dprankefe0d35e2016-02-05 02:43:59958 './' + str(executable) + executable_suffix,
959 '--brave-new-test-launcher',
960 '--test-launcher-bot-mode',
961 '--asan=%d' % asan,
962 '--msan=%d' % msan,
963 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41964 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47965 ]
966 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
dprankea55584f12015-07-22 00:52:47967 cmdline = [
968 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:59969 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:25970 '--brave-new-test-launcher',
971 '--test-launcher-bot-mode',
972 '--asan=%d' % asan,
973 '--msan=%d' % msan,
974 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41975 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47976 ]
dpranke6abd8652015-08-28 03:21:11977 elif test_type == 'script':
dpranke6abd8652015-08-28 03:21:11978 cmdline = [
979 '../../testing/test_env.py',
dprankecb4a2e242016-09-19 01:13:14980 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:59981 ]
dprankea55584f12015-07-22 00:52:47982 elif test_type in ('raw'):
dprankea55584f12015-07-22 00:52:47983 cmdline = [
984 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:59985 ]
dpranked8113582015-06-05 20:08:25986
dprankea55584f12015-07-22 00:52:47987 else:
988 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
989 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25990
dprankecb4a2e242016-09-19 01:13:14991 cmdline += isolate_map[target].get('args', [])
dprankefe0d35e2016-02-05 02:43:59992
dpranked8113582015-06-05 20:08:25993 return cmdline, extra_files
994
dpranke74559b52015-06-10 21:20:39995 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33996 return self.PathJoin(self.chromium_src_dir,
997 self.ToSrcRelPath(build_path),
998 *comps)
dpranked8113582015-06-05 20:08:25999
dprankeee5b51f62015-04-09 00:03:221000 def ToSrcRelPath(self, path):
1001 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501002 if path.startswith('//'):
1003 return path[2:].replace('/', self.sep)
1004 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351005
Dirk Pranke0fd41bcd2015-06-19 00:05:501006 def RunGNAnalyze(self, vals):
dprankecb4a2e242016-09-19 01:13:141007 # Analyze runs before 'gn gen' now, so we need to run gn gen
Dirk Pranke0fd41bcd2015-06-19 00:05:501008 # in order to ensure that we have a build directory.
Dirk Prankea3727f92017-07-17 17:30:331009 ret = self.RunGNGen(vals, compute_grit_inputs_for_analyze=True)
Dirk Pranke0fd41bcd2015-06-19 00:05:501010 if ret:
1011 return ret
1012
dprankecb4a2e242016-09-19 01:13:141013 build_path = self.args.path[0]
1014 input_path = self.args.input_path[0]
1015 gn_input_path = input_path + '.gn'
1016 output_path = self.args.output_path[0]
1017 gn_output_path = output_path + '.gn'
1018
dpranke7837fc362015-11-19 03:54:161019 inp = self.ReadInputJSON(['files', 'test_targets',
1020 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321021 if self.args.verbose:
1022 self.Print()
1023 self.Print('analyze input:')
1024 self.PrintJSON(inp)
1025 self.Print()
1026
dpranke76734662015-04-16 02:17:501027
dpranke7c5f614d2015-07-22 23:43:391028 # This shouldn't normally happen, but could due to unusual race conditions,
1029 # like a try job that gets scheduled before a patch lands but runs after
1030 # the patch has landed.
1031 if not inp['files']:
1032 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161033 self.WriteJSON({
1034 'status': 'No dependency',
1035 'compile_targets': [],
1036 'test_targets': [],
1037 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391038 return 0
1039
dprankecb4a2e242016-09-19 01:13:141040 gn_inp = {}
dprankeb7b183f2017-04-24 23:50:161041 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
dprankef61de2f2015-05-14 04:09:561042
dprankecb4a2e242016-09-19 01:13:141043 isolate_map = self.ReadIsolateMap()
1044 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1045 isolate_map, inp['additional_compile_targets'])
dprankecb4a2e242016-09-19 01:13:141046 if err:
1047 raise MBErr(err)
1048
1049 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1050 isolate_map, inp['test_targets'])
dprankecb4a2e242016-09-19 01:13:141051 if err:
1052 raise MBErr(err)
1053 labels_to_targets = {}
1054 for i, label in enumerate(gn_inp['test_targets']):
1055 labels_to_targets[label] = inp['test_targets'][i]
1056
dprankef61de2f2015-05-14 04:09:561057 try:
dprankecb4a2e242016-09-19 01:13:141058 self.WriteJSON(gn_inp, gn_input_path)
1059 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1060 ret, _, _ = self.Run(cmd, force_verbose=True)
1061 if ret:
1062 return ret
dpranke067d0142015-05-14 22:52:451063
dprankecb4a2e242016-09-19 01:13:141064 gn_outp_str = self.ReadFile(gn_output_path)
1065 try:
1066 gn_outp = json.loads(gn_outp_str)
1067 except Exception as e:
1068 self.Print("Failed to parse the JSON string GN returned: %s\n%s"
1069 % (repr(gn_outp_str), str(e)))
1070 raise
1071
1072 outp = {}
1073 if 'status' in gn_outp:
1074 outp['status'] = gn_outp['status']
1075 if 'error' in gn_outp:
1076 outp['error'] = gn_outp['error']
1077 if 'invalid_targets' in gn_outp:
1078 outp['invalid_targets'] = gn_outp['invalid_targets']
1079 if 'compile_targets' in gn_outp:
Dirk Pranke45165072017-11-08 04:57:491080 all_input_compile_targets = sorted(
1081 set(inp['test_targets'] + inp['additional_compile_targets']))
1082
1083 # If we're building 'all', we can throw away the rest of the targets
1084 # since they're redundant.
dpranke385a3102016-09-20 22:04:081085 if 'all' in gn_outp['compile_targets']:
1086 outp['compile_targets'] = ['all']
1087 else:
Dirk Pranke45165072017-11-08 04:57:491088 outp['compile_targets'] = gn_outp['compile_targets']
1089
1090 # crbug.com/736215: When GN returns targets back, for targets in
1091 # the default toolchain, GN will have generated a phony ninja
1092 # target matching the label, and so we can safely (and easily)
1093 # transform any GN label into the matching ninja target. For
1094 # targets in other toolchains, though, GN doesn't generate the
1095 # phony targets, and we don't know how to turn the labels into
1096 # compile targets. In this case, we also conservatively give up
1097 # and build everything. Probably the right thing to do here is
1098 # to have GN return the compile targets directly.
1099 if any("(" in target for target in outp['compile_targets']):
1100 self.Print('WARNING: targets with non-default toolchains were '
1101 'found, building everything instead.')
1102 outp['compile_targets'] = all_input_compile_targets
1103 else:
dpranke385a3102016-09-20 22:04:081104 outp['compile_targets'] = [
Dirk Pranke45165072017-11-08 04:57:491105 label.replace('//', '') for label in outp['compile_targets']]
1106
1107 # Windows has a maximum command line length of 8k; even Linux
1108 # maxes out at 128k; if analyze returns a *really long* list of
1109 # targets, we just give up and conservatively build everything instead.
1110 # Probably the right thing here is for ninja to support response
1111 # files as input on the command line
1112 # (see https://github.com/ninja-build/ninja/issues/1355).
1113 if len(' '.join(outp['compile_targets'])) > 7*1024:
1114 self.Print('WARNING: Too many compile targets were affected.')
1115 self.Print('WARNING: Building everything instead to avoid '
1116 'command-line length issues.')
1117 outp['compile_targets'] = all_input_compile_targets
1118
1119
dprankecb4a2e242016-09-19 01:13:141120 if 'test_targets' in gn_outp:
1121 outp['test_targets'] = [
1122 labels_to_targets[label] for label in gn_outp['test_targets']]
1123
1124 if self.args.verbose:
1125 self.Print()
1126 self.Print('analyze output:')
1127 self.PrintJSON(outp)
1128 self.Print()
1129
1130 self.WriteJSON(outp, output_path)
1131
dprankef61de2f2015-05-14 04:09:561132 finally:
dprankecb4a2e242016-09-19 01:13:141133 if self.Exists(gn_input_path):
1134 self.RemoveFile(gn_input_path)
1135 if self.Exists(gn_output_path):
1136 self.RemoveFile(gn_output_path)
dprankefe4602312015-04-08 16:20:351137
1138 return 0
1139
dpranked8113582015-06-05 20:08:251140 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351141 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321142 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351143 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321144 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351145
1146 try:
1147 inp = json.loads(self.ReadFile(path))
1148 except Exception as e:
1149 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321150 (path, e), output_path)
dpranked8113582015-06-05 20:08:251151
1152 for k in required_keys:
1153 if not k in inp:
1154 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1155 output_path)
dprankefe4602312015-04-08 16:20:351156
1157 return inp
1158
dpranked5b2b9432015-06-23 16:55:301159 def WriteFailureAndRaise(self, msg, output_path):
1160 if output_path:
dprankee0547cd2015-09-15 01:27:401161 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351162 raise MBErr(msg)
1163
dprankee0547cd2015-09-15 01:27:401164 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321165 try:
dprankee0547cd2015-09-15 01:27:401166 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1167 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321168 except Exception as e:
1169 raise MBErr('Error %s writing to the output path "%s"' %
1170 (e, path))
dprankefe4602312015-04-08 16:20:351171
aneeshmde50f472016-04-01 01:13:101172 def CheckCompile(self, master, builder):
1173 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1174 url = urllib2.quote(url_template.format(master=master, builder=builder),
1175 safe=':/()?=')
1176 try:
1177 builds = json.loads(self.Fetch(url))
1178 except Exception as e:
1179 return str(e)
1180 successes = sorted(
1181 [int(x) for x in builds.keys() if "text" in builds[x] and
1182 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1183 reverse=True)
1184 if not successes:
1185 return "no successful builds"
1186 build = builds[str(successes[0])]
1187 step_names = set([step["name"] for step in build["steps"]])
1188 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1189 if compile_indicators & step_names:
1190 return "compiles"
1191 return "does not compile"
1192
dpranke3cec199c2015-09-22 23:29:021193 def PrintCmd(self, cmd, env):
1194 if self.platform == 'win32':
1195 env_prefix = 'set '
1196 env_quoter = QuoteForSet
1197 shell_quoter = QuoteForCmd
1198 else:
1199 env_prefix = ''
1200 env_quoter = pipes.quote
1201 shell_quoter = pipes.quote
1202
1203 def print_env(var):
1204 if env and var in env:
1205 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1206
dprankeec079262016-06-07 02:21:201207 print_env('LLVM_FORCE_HEAD_REVISION')
dpranke3cec199c2015-09-22 23:29:021208
dpranke8c2cfd32015-09-17 20:12:331209 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351210 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021211 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351212
dprankecda00332015-04-11 04:18:321213 def PrintJSON(self, obj):
1214 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1215
dpranke751516a2015-10-03 01:11:341216 def Build(self, target):
1217 build_dir = self.ToSrcRelPath(self.args.path[0])
1218 ninja_cmd = ['ninja', '-C', build_dir]
1219 if self.args.jobs:
1220 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1221 ninja_cmd.append(target)
1222 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1223 return ret
1224
1225 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351226 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401227 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021228 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351229 if self.args.dryrun:
1230 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401231
dpranke751516a2015-10-03 01:11:341232 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401233 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341234 if ret:
1235 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351236 if out:
dprankeee5b51f62015-04-09 00:03:221237 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351238 if err:
dprankeee5b51f62015-04-09 00:03:221239 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351240 return ret, out, err
1241
dpranke751516a2015-10-03 01:11:341242 def Call(self, cmd, env=None, buffer_output=True):
1243 if buffer_output:
1244 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1245 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1246 env=env)
1247 out, err = p.communicate()
1248 else:
1249 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1250 env=env)
1251 p.wait()
1252 out = err = ''
dprankefe4602312015-04-08 16:20:351253 return p.returncode, out, err
1254
1255 def ExpandUser(self, path):
1256 # This function largely exists so it can be overridden for testing.
1257 return os.path.expanduser(path)
1258
1259 def Exists(self, path):
1260 # This function largely exists so it can be overridden for testing.
1261 return os.path.exists(path)
1262
dpranke867bcf4a2016-03-14 22:28:321263 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501264 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321265 f = urllib2.urlopen(url)
1266 contents = f.read()
1267 f.close()
1268 return contents
1269
dprankec3441d12015-06-23 23:01:351270 def MaybeMakeDirectory(self, path):
1271 try:
1272 os.makedirs(path)
1273 except OSError, e:
1274 if e.errno != errno.EEXIST:
1275 raise
1276
dpranke8c2cfd32015-09-17 20:12:331277 def PathJoin(self, *comps):
1278 # This function largely exists so it can be overriden for testing.
1279 return os.path.join(*comps)
1280
dpranke030d7a6d2016-03-26 17:23:501281 def Print(self, *args, **kwargs):
1282 # This function largely exists so it can be overridden for testing.
1283 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101284 if kwargs.get('stream', sys.stdout) == sys.stdout:
1285 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501286
dprankefe4602312015-04-08 16:20:351287 def ReadFile(self, path):
1288 # This function largely exists so it can be overriden for testing.
1289 with open(path) as fp:
1290 return fp.read()
1291
dpranke030d7a6d2016-03-26 17:23:501292 def RelPath(self, path, start='.'):
1293 # This function largely exists so it can be overriden for testing.
1294 return os.path.relpath(path, start)
1295
dprankef61de2f2015-05-14 04:09:561296 def RemoveFile(self, path):
1297 # This function largely exists so it can be overriden for testing.
1298 os.remove(path)
1299
dprankec161aa92015-09-14 20:21:131300 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331301 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131302 # In other places in chromium, we often have to retry this command
1303 # because we're worried about other processes still holding on to
1304 # file handles, but when MB is invoked, it will be early enough in the
1305 # build that their should be no other processes to interfere. We
1306 # can change this if need be.
1307 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1308 else:
1309 shutil.rmtree(abs_path, ignore_errors=True)
1310
dprankef61de2f2015-05-14 04:09:561311 def TempFile(self, mode='w'):
1312 # This function largely exists so it can be overriden for testing.
1313 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1314
dprankee0547cd2015-09-15 01:27:401315 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351316 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401317 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301318 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351319 with open(path, 'w') as fp:
1320 return fp.write(contents)
1321
dprankef61de2f2015-05-14 04:09:561322
dprankefe4602312015-04-08 16:20:351323class MBErr(Exception):
1324 pass
1325
1326
dpranke3cec199c2015-09-22 23:29:021327# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1328# details of this next section, which handles escaping command lines
1329# so that they can be copied and pasted into a cmd window.
1330UNSAFE_FOR_SET = set('^<>&|')
1331UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1332ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1333
1334
1335def QuoteForSet(arg):
1336 if any(a in UNSAFE_FOR_SET for a in arg):
1337 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1338 return arg
1339
1340
1341def QuoteForCmd(arg):
1342 # First, escape the arg so that CommandLineToArgvW will parse it properly.
dpranke3cec199c2015-09-22 23:29:021343 if arg == '' or ' ' in arg or '"' in arg:
1344 quote_re = re.compile(r'(\\*)"')
1345 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1346
1347 # Then check to see if the arg contains any metacharacters other than
1348 # double quotes; if it does, quote everything (including the double
1349 # quotes) for safety.
1350 if any(a in UNSAFE_FOR_CMD for a in arg):
1351 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1352 return arg
1353
1354
dprankefe4602312015-04-08 16:20:351355if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591356 sys.exit(main(sys.argv[1:]))