blob: 7d41da84df06a382d680dfc1481f253d4a5f7212 [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
Dirk Pranke8cb6aa782017-12-16 02:31:33363 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.
386 if self.platform == 'darwin':
387 os_dim = ('os', 'Mac-10.12')
388 elif self.platform.startswith('linux'):
389 os_dim = ('os', 'Ubuntu-14.04')
390 elif self.platform == 'win32':
391 os_dim = ('os', 'Windows-10-14393')
392 else:
393 raise MBErr('unrecognized platform string "%s"' % self.platform)
394
395 return [('pool', 'Chrome'),
396 ('cpu', 'x86-64'),
397 os_dim]
398
Peter Collingbourne4dfb64a2017-08-12 01:00:55399 def CmdBuildbucket(self):
400 self.ReadConfigFile()
401
402 self.Print('# This file was generated using '
403 '"tools/mb/mb.py gerrit-buildbucket-config".')
404
405 for luci_tryserver in sorted(self.luci_tryservers):
406 self.Print('[bucket "luci.%s"]' % luci_tryserver)
407 for bot in sorted(self.luci_tryservers[luci_tryserver]):
408 self.Print('\tbuilder = %s' % bot)
409
410 for master in sorted(self.masters):
411 if master.startswith('tryserver.'):
412 self.Print('[bucket "master.%s"]' % master)
413 for bot in sorted(self.masters[master]):
414 self.Print('\tbuilder = %s' % bot)
415
416 return 0
417
dpranke0cafc162016-03-19 00:41:10418 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35419 errs = []
420
421 # Read the file to make sure it parses.
422 self.ReadConfigFile()
423
dpranke3be00142016-03-17 22:46:04424 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35425 all_configs = {}
dprankefe4602312015-04-08 16:20:35426 for master in self.masters:
dpranke3be00142016-03-17 22:46:04427 for config in self.masters[master].values():
shenghuazhang804b21542016-10-11 02:06:49428 if isinstance(config, dict):
429 for c in config.values():
dprankeb9380a12016-07-21 21:44:09430 all_configs[c] = master
431 else:
432 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35433
dpranke9dd5e252016-04-14 04:23:09434 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35435 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09436 if config.startswith('//'):
437 if not self.Exists(self.ToAbsPath(config)):
438 errs.append('Unknown args file "%s" referenced from "%s".' %
439 (config, loc))
440 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35441 errs.append('Unknown config "%s" referenced from "%s".' %
442 (config, loc))
443
444 # Check that every actual config is actually referenced.
445 for config in self.configs:
446 if not config in all_configs:
447 errs.append('Unused config "%s".' % config)
448
449 # Figure out the whole list of mixins, and check that every mixin
450 # listed by a config or another mixin actually exists.
451 referenced_mixins = set()
452 for config, mixins in self.configs.items():
453 for mixin in mixins:
454 if not mixin in self.mixins:
455 errs.append('Unknown mixin "%s" referenced by config "%s".' %
456 (mixin, config))
457 referenced_mixins.add(mixin)
458
459 for mixin in self.mixins:
460 for sub_mixin in self.mixins[mixin].get('mixins', []):
461 if not sub_mixin in self.mixins:
462 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
463 (sub_mixin, mixin))
464 referenced_mixins.add(sub_mixin)
465
466 # Check that every mixin defined is actually referenced somewhere.
467 for mixin in self.mixins:
468 if not mixin in referenced_mixins:
469 errs.append('Unreferenced mixin "%s".' % mixin)
470
dpranke255085e2016-03-16 05:23:59471 # If we're checking the Chromium config, check that the 'chromium' bots
472 # which build public artifacts do not include the chrome_with_codecs mixin.
473 if self.args.config_file == self.default_config:
474 if 'chromium' in self.masters:
475 for builder in self.masters['chromium']:
476 config = self.masters['chromium'][builder]
477 def RecurseMixins(current_mixin):
478 if current_mixin == 'chrome_with_codecs':
479 errs.append('Public artifact builder "%s" can not contain the '
480 '"chrome_with_codecs" mixin.' % builder)
481 return
482 if not 'mixins' in self.mixins[current_mixin]:
483 return
484 for mixin in self.mixins[current_mixin]['mixins']:
485 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41486
dpranke255085e2016-03-16 05:23:59487 for mixin in self.configs[config]:
488 RecurseMixins(mixin)
489 else:
490 errs.append('Missing "chromium" master. Please update this '
491 'proprietary codecs check with the name of the master '
492 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41493
dprankefe4602312015-04-08 16:20:35494 if errs:
dpranke4323c80632015-08-10 22:53:54495 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17496 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35497
dpranke0cafc162016-03-19 00:41:10498 if print_ok:
499 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35500 return 0
501
502 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34503 build_dir = self.args.path[0]
504
dprankef37aebb92016-09-23 01:14:49505 vals = self.DefaultVals()
dpranke751516a2015-10-03 01:11:34506 if self.args.builder or self.args.master or self.args.config:
507 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11508 # Re-run gn gen in order to ensure the config is consistent with the
509 # build dir.
510 self.RunGNGen(vals)
dpranke751516a2015-10-03 01:11:34511 return vals
512
Dirk Pranked181a1a2017-12-14 01:47:11513 toolchain_path = self.PathJoin(self.ToAbsPath(build_dir),
514 'toolchain.ninja')
515 if not self.Exists(toolchain_path):
516 self.Print('Must either specify a path to an existing GN build dir '
517 'or pass in a -m/-b pair or a -c flag to specify the '
518 'configuration')
519 return {}
dpranke751516a2015-10-03 01:11:34520
Dirk Pranked181a1a2017-12-14 01:47:11521 vals['gn_args'] = self.GNArgsFromDir(build_dir)
dpranke751516a2015-10-03 01:11:34522 return vals
523
dprankef37aebb92016-09-23 01:14:49524 def GNArgsFromDir(self, build_dir):
brucedawsonecc0c1cd2016-06-02 18:24:58525 args_contents = ""
526 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
527 if self.Exists(gn_args_path):
528 args_contents = self.ReadFile(gn_args_path)
dpranke751516a2015-10-03 01:11:34529 gn_args = []
530 for l in args_contents.splitlines():
531 fields = l.split(' ')
532 name = fields[0]
533 val = ' '.join(fields[2:])
534 gn_args.append('%s=%s' % (name, val))
535
dprankef37aebb92016-09-23 01:14:49536 return ' '.join(gn_args)
dpranke751516a2015-10-03 01:11:34537
538 def Lookup(self):
dprankef37aebb92016-09-23 01:14:49539 vals = self.ReadIOSBotConfig()
dprankee0f486f2015-11-19 23:42:00540 if not vals:
541 self.ReadConfigFile()
542 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09543 if config.startswith('//'):
544 if not self.Exists(self.ToAbsPath(config)):
545 raise MBErr('args file "%s" not found' % config)
dprankef37aebb92016-09-23 01:14:49546 vals = self.DefaultVals()
547 vals['args_file'] = config
dpranke9dd5e252016-04-14 04:23:09548 else:
549 if not config in self.configs:
550 raise MBErr('Config "%s" not found in %s' %
551 (config, self.args.config_file))
552 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34553 return vals
dprankefe4602312015-04-08 16:20:35554
dprankef37aebb92016-09-23 01:14:49555 def ReadIOSBotConfig(self):
dprankee0f486f2015-11-19 23:42:00556 if not self.args.master or not self.args.builder:
557 return {}
558 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
559 self.args.master, self.args.builder + '.json')
560 if not self.Exists(path):
561 return {}
562
563 contents = json.loads(self.ReadFile(path))
dprankee0f486f2015-11-19 23:42:00564 gn_args = ' '.join(contents.get('gn_args', []))
565
dprankef37aebb92016-09-23 01:14:49566 vals = self.DefaultVals()
567 vals['gn_args'] = gn_args
dprankef37aebb92016-09-23 01:14:49568 return vals
dprankee0f486f2015-11-19 23:42:00569
dprankefe4602312015-04-08 16:20:35570 def ReadConfigFile(self):
571 if not self.Exists(self.args.config_file):
572 raise MBErr('config file not found at %s' % self.args.config_file)
573
574 try:
575 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
576 except SyntaxError as e:
577 raise MBErr('Failed to parse config file "%s": %s' %
578 (self.args.config_file, e))
579
dprankefe4602312015-04-08 16:20:35580 self.configs = contents['configs']
Peter Collingbourne4dfb64a2017-08-12 01:00:55581 self.luci_tryservers = contents.get('luci_tryservers', {})
dprankefe4602312015-04-08 16:20:35582 self.masters = contents['masters']
583 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35584
dprankecb4a2e242016-09-19 01:13:14585 def ReadIsolateMap(self):
Zhiling Huang66958462018-02-03 00:28:20586 if not self.args.isolate_map_files:
587 self.args.isolate_map_files = [self.default_isolate_map]
588
589 for f in self.args.isolate_map_files:
590 if not self.Exists(f):
591 raise MBErr('isolate map file not found at %s' % f)
592 isolate_maps = {}
593 for isolate_map in self.args.isolate_map_files:
594 try:
595 isolate_map = ast.literal_eval(self.ReadFile(isolate_map))
596 duplicates = set(isolate_map).intersection(isolate_maps)
597 if duplicates:
598 raise MBErr(
599 'Duplicate targets in isolate map files: %s.' %
600 ', '.join(duplicates))
601 isolate_maps.update(isolate_map)
602 except SyntaxError as e:
603 raise MBErr(
604 'Failed to parse isolate map file "%s": %s' % (isolate_map, e))
605 return isolate_maps
dprankecb4a2e242016-09-19 01:13:14606
dprankefe4602312015-04-08 16:20:35607 def ConfigFromArgs(self):
608 if self.args.config:
609 if self.args.master or self.args.builder:
610 raise MBErr('Can not specific both -c/--config and -m/--master or '
611 '-b/--builder')
612
613 return self.args.config
614
615 if not self.args.master or not self.args.builder:
616 raise MBErr('Must specify either -c/--config or '
617 '(-m/--master and -b/--builder)')
618
619 if not self.args.master in self.masters:
620 raise MBErr('Master name "%s" not found in "%s"' %
621 (self.args.master, self.args.config_file))
622
623 if not self.args.builder in self.masters[self.args.master]:
624 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
625 (self.args.builder, self.args.master, self.args.config_file))
626
dprankeb9380a12016-07-21 21:44:09627 config = self.masters[self.args.master][self.args.builder]
shenghuazhang804b21542016-10-11 02:06:49628 if isinstance(config, dict):
dprankeb9380a12016-07-21 21:44:09629 if self.args.phase is None:
630 raise MBErr('Must specify a build --phase for %s on %s' %
631 (self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49632 phase = str(self.args.phase)
633 if phase not in config:
634 raise MBErr('Phase %s doesn\'t exist for %s on %s' %
dprankeb9380a12016-07-21 21:44:09635 (phase, self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49636 return config[phase]
dprankeb9380a12016-07-21 21:44:09637
638 if self.args.phase is not None:
639 raise MBErr('Must not specify a build --phase for %s on %s' %
640 (self.args.builder, self.args.master))
641 return config
dprankefe4602312015-04-08 16:20:35642
643 def FlattenConfig(self, config):
644 mixins = self.configs[config]
dprankef37aebb92016-09-23 01:14:49645 vals = self.DefaultVals()
dprankefe4602312015-04-08 16:20:35646
647 visited = []
648 self.FlattenMixins(mixins, vals, visited)
649 return vals
650
dprankef37aebb92016-09-23 01:14:49651 def DefaultVals(self):
652 return {
653 'args_file': '',
654 'cros_passthrough': False,
655 'gn_args': '',
dprankef37aebb92016-09-23 01:14:49656 }
657
dprankefe4602312015-04-08 16:20:35658 def FlattenMixins(self, mixins, vals, visited):
659 for m in mixins:
660 if m not in self.mixins:
661 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22662
dprankefe4602312015-04-08 16:20:35663 visited.append(m)
664
665 mixin_vals = self.mixins[m]
dpranke73ed0d62016-04-25 19:18:34666
667 if 'cros_passthrough' in mixin_vals:
668 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
Dirk Pranke6b99f072017-04-05 00:58:30669 if 'args_file' in mixin_vals:
670 if vals['args_file']:
671 raise MBErr('args_file specified multiple times in mixins '
672 'for %s on %s' % (self.args.builder, self.args.master))
673 vals['args_file'] = mixin_vals['args_file']
dprankefe4602312015-04-08 16:20:35674 if 'gn_args' in mixin_vals:
675 if vals['gn_args']:
676 vals['gn_args'] += ' ' + mixin_vals['gn_args']
677 else:
678 vals['gn_args'] = mixin_vals['gn_args']
dpranke73ed0d62016-04-25 19:18:34679
dprankefe4602312015-04-08 16:20:35680 if 'mixins' in mixin_vals:
681 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
682 return vals
683
Dirk Prankea3727f92017-07-17 17:30:33684 def RunGNGen(self, vals, compute_grit_inputs_for_analyze=False):
dpranke751516a2015-10-03 01:11:34685 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50686
dprankeeca4a782016-04-14 01:42:38687 cmd = self.GNCmd('gen', build_dir, '--check')
688 gn_args = self.GNArgs(vals)
Dirk Prankea3727f92017-07-17 17:30:33689 if compute_grit_inputs_for_analyze:
690 gn_args += ' compute_grit_inputs_for_analyze=true'
dprankeeca4a782016-04-14 01:42:38691
692 # Since GN hasn't run yet, the build directory may not even exist.
693 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
694
695 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54696 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39697
698 swarming_targets = []
dpranke751516a2015-10-03 01:11:34699 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39700 # We need GN to generate the list of runtime dependencies for
701 # the compile targets listed (one per line) in the file so
dprankecb4a2e242016-09-19 01:13:14702 # we can run them via swarming. We use gn_isolate_map.pyl to convert
dpranke74559b52015-06-10 21:20:39703 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00704 path = self.args.swarming_targets_file
705 if not self.Exists(path):
706 self.WriteFailureAndRaise('"%s" does not exist' % path,
707 output_path=None)
708 contents = self.ReadFile(path)
709 swarming_targets = set(contents.splitlines())
dprankeb2be10a2016-02-22 17:11:00710
dprankecb4a2e242016-09-19 01:13:14711 isolate_map = self.ReadIsolateMap()
712 err, labels = self.MapTargetsToLabels(isolate_map, swarming_targets)
dprankeb2be10a2016-02-22 17:11:00713 if err:
dprankecb4a2e242016-09-19 01:13:14714 raise MBErr(err)
dpranke74559b52015-06-10 21:20:39715
dpranke751516a2015-10-03 01:11:34716 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankecb4a2e242016-09-19 01:13:14717 self.WriteFile(gn_runtime_deps_path, '\n'.join(labels) + '\n')
dpranke74559b52015-06-10 21:20:39718 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
719
dprankefe4602312015-04-08 16:20:35720 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40721 if ret:
722 # If `gn gen` failed, we should exit early rather than trying to
723 # generate isolates. Run() will have already logged any error output.
724 self.Print('GN gen failed: %d' % ret)
725 return ret
dpranke74559b52015-06-10 21:20:39726
jbudoricke3c4f95e2016-04-28 23:17:38727 android = 'target_os="android"' in vals['gn_args']
Kevin Marshallf35fa5f2018-01-29 19:24:42728 fuchsia = 'target_os="fuchsia"' in vals['gn_args']
Nico Weberd94b71a2018-02-22 22:00:30729 win = self.platform == 'win32' or 'target_os="win"' in vals['gn_args']
dpranke74559b52015-06-10 21:20:39730 for target in swarming_targets:
jbudoricke3c4f95e2016-04-28 23:17:38731 if android:
732 # Android targets may be either android_apk or executable. The former
jbudorick91c8a6012016-01-29 23:20:02733 # will result in runtime_deps associated with the stamp file, while the
734 # latter will result in runtime_deps associated with the executable.
dprankecb4a2e242016-09-19 01:13:14735 label = isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02736 runtime_deps_targets = [
dprankecb4a2e242016-09-19 01:13:14737 target + '.runtime_deps',
dpranke48ccf8f2016-03-28 23:58:28738 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
Kevin Marshallf35fa5f2018-01-29 19:24:42739 elif fuchsia:
740 # Only emit a runtime deps file for the group() target on Fuchsia.
741 label = isolate_map[target]['label']
742 runtime_deps_targets = [
743 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
dprankecb4a2e242016-09-19 01:13:14744 elif (isolate_map[target]['type'] == 'script' or
745 isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11746 # For script targets, the build target is usually a group,
747 # for which gn generates the runtime_deps next to the stamp file
eyaich82d5ac942016-11-03 12:13:49748 # for the label, which lives under the obj/ directory, but it may
749 # also be an executable.
dprankecb4a2e242016-09-19 01:13:14750 label = isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28751 runtime_deps_targets = [
752 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
Nico Weberd94b71a2018-02-22 22:00:30753 if win:
eyaich82d5ac942016-11-03 12:13:49754 runtime_deps_targets += [ target + '.exe.runtime_deps' ]
755 else:
756 runtime_deps_targets += [ target + '.runtime_deps' ]
Nico Weberd94b71a2018-02-22 22:00:30757 elif win:
dpranke48ccf8f2016-03-28 23:58:28758 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52759 else:
dpranke48ccf8f2016-03-28 23:58:28760 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02761
dpranke48ccf8f2016-03-28 23:58:28762 for r in runtime_deps_targets:
763 runtime_deps_path = self.ToAbsPath(build_dir, r)
764 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02765 break
766 else:
dpranke48ccf8f2016-03-28 23:58:28767 raise MBErr('did not generate any of %s' %
768 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39769
dprankecb4a2e242016-09-19 01:13:14770 command, extra_files = self.GetIsolateCommand(target, vals)
dpranked5b2b9432015-06-23 16:55:30771
dpranke48ccf8f2016-03-28 23:58:28772 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30773
dpranke751516a2015-10-03 01:11:34774 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
775 extra_files)
dpranked5b2b9432015-06-23 16:55:30776
dpranke751516a2015-10-03 01:11:34777 return 0
778
779 def RunGNIsolate(self, vals):
dprankecb4a2e242016-09-19 01:13:14780 target = self.args.target[0]
781 isolate_map = self.ReadIsolateMap()
782 err, labels = self.MapTargetsToLabels(isolate_map, [target])
783 if err:
784 raise MBErr(err)
785 label = labels[0]
dpranke751516a2015-10-03 01:11:34786
787 build_dir = self.args.path[0]
dprankecb4a2e242016-09-19 01:13:14788 command, extra_files = self.GetIsolateCommand(target, vals)
dpranke751516a2015-10-03 01:11:34789
dprankeeca4a782016-04-14 01:42:38790 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20791 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34792 if ret:
dpranke030d7a6d2016-03-26 17:23:50793 if out:
794 self.Print(out)
dpranke751516a2015-10-03 01:11:34795 return ret
796
797 runtime_deps = out.splitlines()
798
799 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
800 extra_files)
801
802 ret, _, _ = self.Run([
803 self.executable,
804 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
805 'check',
806 '-i',
807 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
808 '-s',
809 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
810 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30811
dprankefe4602312015-04-08 16:20:35812 return ret
813
dpranke751516a2015-10-03 01:11:34814 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
815 extra_files):
816 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
817 self.WriteFile(isolate_path,
818 pprint.pformat({
819 'variables': {
820 'command': command,
821 'files': sorted(runtime_deps + extra_files),
822 }
823 }) + '\n')
824
825 self.WriteJSON(
826 {
827 'args': [
828 '--isolated',
829 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
830 '--isolate',
831 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
832 ],
833 'dir': self.chromium_src_dir,
834 'version': 1,
835 },
836 isolate_path + 'd.gen.json',
837 )
838
dprankecb4a2e242016-09-19 01:13:14839 def MapTargetsToLabels(self, isolate_map, targets):
840 labels = []
841 err = ''
842
dprankecb4a2e242016-09-19 01:13:14843 for target in targets:
844 if target == 'all':
845 labels.append(target)
846 elif target.startswith('//'):
847 labels.append(target)
848 else:
849 if target in isolate_map:
thakis024d6f32017-05-16 23:21:42850 if isolate_map[target]['type'] == 'unknown':
dprankecb4a2e242016-09-19 01:13:14851 err += ('test target "%s" type is unknown\n' % target)
852 else:
thakis024d6f32017-05-16 23:21:42853 labels.append(isolate_map[target]['label'])
dprankecb4a2e242016-09-19 01:13:14854 else:
855 err += ('target "%s" not found in '
856 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
857
858 return err, labels
859
dprankeeca4a782016-04-14 01:42:38860 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51861 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20862 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51863 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20864 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51865 else:
dpranke40da0202016-02-13 05:05:20866 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38867
dpranke40da0202016-02-13 05:05:20868 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranke10118bf2016-09-16 23:16:08869 return [gn_path, subcommand, path] + list(args)
dpranke9aba8b212016-09-16 22:52:52870
dprankecb4a2e242016-09-19 01:13:14871
dprankeeca4a782016-04-14 01:42:38872 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34873 if vals['cros_passthrough']:
874 if not 'GN_ARGS' in os.environ:
875 raise MBErr('MB is expecting GN_ARGS to be in the environment')
876 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16877 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30878 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34879 gn_args)
880 else:
881 gn_args = vals['gn_args']
882
dpranked0c138b2016-04-13 18:28:47883 if self.args.goma_dir:
884 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38885
agrieve41d21a72016-04-14 18:02:26886 android_version_code = self.args.android_version_code
887 if android_version_code:
888 gn_args += ' android_default_version_code="%s"' % android_version_code
889
890 android_version_name = self.args.android_version_name
891 if android_version_name:
892 gn_args += ' android_default_version_name="%s"' % android_version_name
893
dprankeeca4a782016-04-14 01:42:38894 # Canonicalize the arg string into a sorted, newline-separated list
895 # of key-value pairs, and de-dup the keys if need be so that only
896 # the last instance of each arg is listed.
897 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
898
dpranke9dd5e252016-04-14 04:23:09899 args_file = vals.get('args_file', None)
900 if args_file:
901 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38902 return gn_args
dprankefe4602312015-04-08 16:20:35903
dprankecb4a2e242016-09-19 01:13:14904 def GetIsolateCommand(self, target, vals):
kylechar50abf5a2016-11-29 16:03:07905 isolate_map = self.ReadIsolateMap()
906
Scott Graham3be4b4162017-09-12 00:41:41907 is_android = 'target_os="android"' in vals['gn_args']
908 is_fuchsia = 'target_os="fuchsia"' in vals['gn_args']
Nico Weberd94b71a2018-02-22 22:00:30909 is_win = self.platform == 'win32' or 'target_os="win"' in vals['gn_args']
jbudoricke8428732016-02-02 02:17:06910
kylechar39705682017-01-19 14:37:23911 # This should be true if tests with type='windowed_test_launcher' are
912 # expected to run using xvfb. For example, Linux Desktop, X11 CrOS and
msisovaea52732017-03-21 08:08:08913 # Ozone CrOS builds. Note that one Ozone build can be used to run differen
914 # backends. Currently, tests are executed for the headless and X11 backends
915 # and both can run under Xvfb.
916 # TODO(tonikitoo,msisov,fwang): Find a way to run tests for the Wayland
917 # backend.
Scott Graham3be4b4162017-09-12 00:41:41918 use_xvfb = self.platform == 'linux2' and not is_android and not is_fuchsia
dpranked8113582015-06-05 20:08:25919
920 asan = 'is_asan=true' in vals['gn_args']
921 msan = 'is_msan=true' in vals['gn_args']
922 tsan = 'is_tsan=true' in vals['gn_args']
pcc46233c22017-06-20 22:11:41923 cfi_diag = 'use_cfi_diag=true' in vals['gn_args']
dpranked8113582015-06-05 20:08:25924
dprankecb4a2e242016-09-19 01:13:14925 test_type = isolate_map[target]['type']
dprankefe0d35e2016-02-05 02:43:59926
dprankecb4a2e242016-09-19 01:13:14927 executable = isolate_map[target].get('executable', target)
Nico Weberd94b71a2018-02-22 22:00:30928 executable_suffix = '.exe' if is_win else ''
dprankefe0d35e2016-02-05 02:43:59929
dprankea55584f12015-07-22 00:52:47930 cmdline = []
Andrii Shyshkalovc158e0102018-01-10 05:52:00931 extra_files = [
932 '../../.vpython',
933 '../../testing/test_env.py',
934 ]
dpranked8113582015-06-05 20:08:25935
dprankecb4a2e242016-09-19 01:13:14936 if test_type == 'nontest':
937 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
938 output_path=None)
939
Scott Graham3be4b4162017-09-12 00:41:41940 if is_android and test_type != "script":
bpastenee428ea92017-02-17 02:20:32941 cmdline = [
John Budorickfb97a852017-12-20 20:10:19942 '../../testing/test_env.py',
hzl9b15df52017-03-23 23:43:04943 '../../build/android/test_wrapper/logdog_wrapper.py',
944 '--target', target,
hzl9ae14452017-04-04 23:38:02945 '--logdog-bin-cmd', '../../bin/logdog_butler',
hzlfc66094f2017-05-18 00:50:48946 '--store-tombstones']
Scott Graham3be4b4162017-09-12 00:41:41947 elif is_fuchsia and test_type != 'script':
John Budorickfb97a852017-12-20 20:10:19948 cmdline = [
949 '../../testing/test_env.py',
950 os.path.join('bin', 'run_%s' % target),
951 ]
kylechar39705682017-01-19 14:37:23952 elif use_xvfb and test_type == 'windowed_test_launcher':
Andrii Shyshkalovc158e0102018-01-10 05:52:00953 extra_files.append('../../testing/xvfb.py')
dprankea55584f12015-07-22 00:52:47954 cmdline = [
dprankefe0d35e2016-02-05 02:43:59955 '../../testing/xvfb.py',
dprankefe0d35e2016-02-05 02:43:59956 './' + str(executable) + executable_suffix,
957 '--brave-new-test-launcher',
958 '--test-launcher-bot-mode',
959 '--asan=%d' % asan,
960 '--msan=%d' % msan,
961 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41962 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47963 ]
964 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
dprankea55584f12015-07-22 00:52:47965 cmdline = [
966 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:59967 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:25968 '--brave-new-test-launcher',
969 '--test-launcher-bot-mode',
970 '--asan=%d' % asan,
971 '--msan=%d' % msan,
972 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41973 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47974 ]
dpranke6abd8652015-08-28 03:21:11975 elif test_type == 'script':
dpranke6abd8652015-08-28 03:21:11976 cmdline = [
977 '../../testing/test_env.py',
dprankecb4a2e242016-09-19 01:13:14978 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:59979 ]
dprankea55584f12015-07-22 00:52:47980 elif test_type in ('raw'):
dprankea55584f12015-07-22 00:52:47981 cmdline = [
982 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:59983 ]
dpranked8113582015-06-05 20:08:25984
dprankea55584f12015-07-22 00:52:47985 else:
986 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
987 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25988
dprankecb4a2e242016-09-19 01:13:14989 cmdline += isolate_map[target].get('args', [])
dprankefe0d35e2016-02-05 02:43:59990
dpranked8113582015-06-05 20:08:25991 return cmdline, extra_files
992
dpranke74559b52015-06-10 21:20:39993 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33994 return self.PathJoin(self.chromium_src_dir,
995 self.ToSrcRelPath(build_path),
996 *comps)
dpranked8113582015-06-05 20:08:25997
dprankeee5b51f62015-04-09 00:03:22998 def ToSrcRelPath(self, path):
999 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501000 if path.startswith('//'):
1001 return path[2:].replace('/', self.sep)
1002 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351003
Dirk Pranke0fd41bcd2015-06-19 00:05:501004 def RunGNAnalyze(self, vals):
dprankecb4a2e242016-09-19 01:13:141005 # Analyze runs before 'gn gen' now, so we need to run gn gen
Dirk Pranke0fd41bcd2015-06-19 00:05:501006 # in order to ensure that we have a build directory.
Dirk Prankea3727f92017-07-17 17:30:331007 ret = self.RunGNGen(vals, compute_grit_inputs_for_analyze=True)
Dirk Pranke0fd41bcd2015-06-19 00:05:501008 if ret:
1009 return ret
1010
dprankecb4a2e242016-09-19 01:13:141011 build_path = self.args.path[0]
1012 input_path = self.args.input_path[0]
1013 gn_input_path = input_path + '.gn'
1014 output_path = self.args.output_path[0]
1015 gn_output_path = output_path + '.gn'
1016
dpranke7837fc362015-11-19 03:54:161017 inp = self.ReadInputJSON(['files', 'test_targets',
1018 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321019 if self.args.verbose:
1020 self.Print()
1021 self.Print('analyze input:')
1022 self.PrintJSON(inp)
1023 self.Print()
1024
dpranke76734662015-04-16 02:17:501025
dpranke7c5f614d2015-07-22 23:43:391026 # This shouldn't normally happen, but could due to unusual race conditions,
1027 # like a try job that gets scheduled before a patch lands but runs after
1028 # the patch has landed.
1029 if not inp['files']:
1030 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161031 self.WriteJSON({
1032 'status': 'No dependency',
1033 'compile_targets': [],
1034 'test_targets': [],
1035 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391036 return 0
1037
dprankecb4a2e242016-09-19 01:13:141038 gn_inp = {}
dprankeb7b183f2017-04-24 23:50:161039 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
dprankef61de2f2015-05-14 04:09:561040
dprankecb4a2e242016-09-19 01:13:141041 isolate_map = self.ReadIsolateMap()
1042 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1043 isolate_map, inp['additional_compile_targets'])
1044 if err:
1045 raise MBErr(err)
1046
1047 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1048 isolate_map, inp['test_targets'])
1049 if err:
1050 raise MBErr(err)
1051 labels_to_targets = {}
1052 for i, label in enumerate(gn_inp['test_targets']):
1053 labels_to_targets[label] = inp['test_targets'][i]
1054
dprankef61de2f2015-05-14 04:09:561055 try:
dprankecb4a2e242016-09-19 01:13:141056 self.WriteJSON(gn_inp, gn_input_path)
1057 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1058 ret, _, _ = self.Run(cmd, force_verbose=True)
1059 if ret:
1060 return ret
dpranke067d0142015-05-14 22:52:451061
dprankecb4a2e242016-09-19 01:13:141062 gn_outp_str = self.ReadFile(gn_output_path)
1063 try:
1064 gn_outp = json.loads(gn_outp_str)
1065 except Exception as e:
1066 self.Print("Failed to parse the JSON string GN returned: %s\n%s"
1067 % (repr(gn_outp_str), str(e)))
1068 raise
1069
1070 outp = {}
1071 if 'status' in gn_outp:
1072 outp['status'] = gn_outp['status']
1073 if 'error' in gn_outp:
1074 outp['error'] = gn_outp['error']
1075 if 'invalid_targets' in gn_outp:
1076 outp['invalid_targets'] = gn_outp['invalid_targets']
1077 if 'compile_targets' in gn_outp:
Dirk Pranke45165072017-11-08 04:57:491078 all_input_compile_targets = sorted(
1079 set(inp['test_targets'] + inp['additional_compile_targets']))
1080
1081 # If we're building 'all', we can throw away the rest of the targets
1082 # since they're redundant.
dpranke385a3102016-09-20 22:04:081083 if 'all' in gn_outp['compile_targets']:
1084 outp['compile_targets'] = ['all']
1085 else:
Dirk Pranke45165072017-11-08 04:57:491086 outp['compile_targets'] = gn_outp['compile_targets']
1087
1088 # crbug.com/736215: When GN returns targets back, for targets in
1089 # the default toolchain, GN will have generated a phony ninja
1090 # target matching the label, and so we can safely (and easily)
1091 # transform any GN label into the matching ninja target. For
1092 # targets in other toolchains, though, GN doesn't generate the
1093 # phony targets, and we don't know how to turn the labels into
1094 # compile targets. In this case, we also conservatively give up
1095 # and build everything. Probably the right thing to do here is
1096 # to have GN return the compile targets directly.
1097 if any("(" in target for target in outp['compile_targets']):
1098 self.Print('WARNING: targets with non-default toolchains were '
1099 'found, building everything instead.')
1100 outp['compile_targets'] = all_input_compile_targets
1101 else:
dpranke385a3102016-09-20 22:04:081102 outp['compile_targets'] = [
Dirk Pranke45165072017-11-08 04:57:491103 label.replace('//', '') for label in outp['compile_targets']]
1104
1105 # Windows has a maximum command line length of 8k; even Linux
1106 # maxes out at 128k; if analyze returns a *really long* list of
1107 # targets, we just give up and conservatively build everything instead.
1108 # Probably the right thing here is for ninja to support response
1109 # files as input on the command line
1110 # (see https://github.com/ninja-build/ninja/issues/1355).
1111 if len(' '.join(outp['compile_targets'])) > 7*1024:
1112 self.Print('WARNING: Too many compile targets were affected.')
1113 self.Print('WARNING: Building everything instead to avoid '
1114 'command-line length issues.')
1115 outp['compile_targets'] = all_input_compile_targets
1116
1117
dprankecb4a2e242016-09-19 01:13:141118 if 'test_targets' in gn_outp:
1119 outp['test_targets'] = [
1120 labels_to_targets[label] for label in gn_outp['test_targets']]
1121
1122 if self.args.verbose:
1123 self.Print()
1124 self.Print('analyze output:')
1125 self.PrintJSON(outp)
1126 self.Print()
1127
1128 self.WriteJSON(outp, output_path)
1129
dprankef61de2f2015-05-14 04:09:561130 finally:
dprankecb4a2e242016-09-19 01:13:141131 if self.Exists(gn_input_path):
1132 self.RemoveFile(gn_input_path)
1133 if self.Exists(gn_output_path):
1134 self.RemoveFile(gn_output_path)
dprankefe4602312015-04-08 16:20:351135
1136 return 0
1137
dpranked8113582015-06-05 20:08:251138 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351139 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321140 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351141 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321142 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351143
1144 try:
1145 inp = json.loads(self.ReadFile(path))
1146 except Exception as e:
1147 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321148 (path, e), output_path)
dpranked8113582015-06-05 20:08:251149
1150 for k in required_keys:
1151 if not k in inp:
1152 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1153 output_path)
dprankefe4602312015-04-08 16:20:351154
1155 return inp
1156
dpranked5b2b9432015-06-23 16:55:301157 def WriteFailureAndRaise(self, msg, output_path):
1158 if output_path:
dprankee0547cd2015-09-15 01:27:401159 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351160 raise MBErr(msg)
1161
dprankee0547cd2015-09-15 01:27:401162 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321163 try:
dprankee0547cd2015-09-15 01:27:401164 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1165 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321166 except Exception as e:
1167 raise MBErr('Error %s writing to the output path "%s"' %
1168 (e, path))
dprankefe4602312015-04-08 16:20:351169
aneeshmde50f472016-04-01 01:13:101170 def CheckCompile(self, master, builder):
1171 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1172 url = urllib2.quote(url_template.format(master=master, builder=builder),
1173 safe=':/()?=')
1174 try:
1175 builds = json.loads(self.Fetch(url))
1176 except Exception as e:
1177 return str(e)
1178 successes = sorted(
1179 [int(x) for x in builds.keys() if "text" in builds[x] and
1180 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1181 reverse=True)
1182 if not successes:
1183 return "no successful builds"
1184 build = builds[str(successes[0])]
1185 step_names = set([step["name"] for step in build["steps"]])
1186 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1187 if compile_indicators & step_names:
1188 return "compiles"
1189 return "does not compile"
1190
dpranke3cec199c2015-09-22 23:29:021191 def PrintCmd(self, cmd, env):
1192 if self.platform == 'win32':
1193 env_prefix = 'set '
1194 env_quoter = QuoteForSet
1195 shell_quoter = QuoteForCmd
1196 else:
1197 env_prefix = ''
1198 env_quoter = pipes.quote
1199 shell_quoter = pipes.quote
1200
1201 def print_env(var):
1202 if env and var in env:
1203 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1204
dprankeec079262016-06-07 02:21:201205 print_env('LLVM_FORCE_HEAD_REVISION')
dpranke3cec199c2015-09-22 23:29:021206
dpranke8c2cfd32015-09-17 20:12:331207 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351208 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021209 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351210
dprankecda00332015-04-11 04:18:321211 def PrintJSON(self, obj):
1212 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1213
dpranke751516a2015-10-03 01:11:341214 def Build(self, target):
1215 build_dir = self.ToSrcRelPath(self.args.path[0])
1216 ninja_cmd = ['ninja', '-C', build_dir]
1217 if self.args.jobs:
1218 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1219 ninja_cmd.append(target)
1220 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1221 return ret
1222
1223 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351224 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401225 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021226 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351227 if self.args.dryrun:
1228 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401229
dpranke751516a2015-10-03 01:11:341230 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401231 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341232 if ret:
1233 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351234 if out:
dprankeee5b51f62015-04-09 00:03:221235 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351236 if err:
dprankeee5b51f62015-04-09 00:03:221237 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351238 return ret, out, err
1239
dpranke751516a2015-10-03 01:11:341240 def Call(self, cmd, env=None, buffer_output=True):
1241 if buffer_output:
1242 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1243 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1244 env=env)
1245 out, err = p.communicate()
1246 else:
1247 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1248 env=env)
1249 p.wait()
1250 out = err = ''
dprankefe4602312015-04-08 16:20:351251 return p.returncode, out, err
1252
1253 def ExpandUser(self, path):
1254 # This function largely exists so it can be overridden for testing.
1255 return os.path.expanduser(path)
1256
1257 def Exists(self, path):
1258 # This function largely exists so it can be overridden for testing.
1259 return os.path.exists(path)
1260
dpranke867bcf4a2016-03-14 22:28:321261 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501262 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321263 f = urllib2.urlopen(url)
1264 contents = f.read()
1265 f.close()
1266 return contents
1267
dprankec3441d12015-06-23 23:01:351268 def MaybeMakeDirectory(self, path):
1269 try:
1270 os.makedirs(path)
1271 except OSError, e:
1272 if e.errno != errno.EEXIST:
1273 raise
1274
dpranke8c2cfd32015-09-17 20:12:331275 def PathJoin(self, *comps):
1276 # This function largely exists so it can be overriden for testing.
1277 return os.path.join(*comps)
1278
dpranke030d7a6d2016-03-26 17:23:501279 def Print(self, *args, **kwargs):
1280 # This function largely exists so it can be overridden for testing.
1281 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101282 if kwargs.get('stream', sys.stdout) == sys.stdout:
1283 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501284
dprankefe4602312015-04-08 16:20:351285 def ReadFile(self, path):
1286 # This function largely exists so it can be overriden for testing.
1287 with open(path) as fp:
1288 return fp.read()
1289
dpranke030d7a6d2016-03-26 17:23:501290 def RelPath(self, path, start='.'):
1291 # This function largely exists so it can be overriden for testing.
1292 return os.path.relpath(path, start)
1293
dprankef61de2f2015-05-14 04:09:561294 def RemoveFile(self, path):
1295 # This function largely exists so it can be overriden for testing.
1296 os.remove(path)
1297
dprankec161aa92015-09-14 20:21:131298 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331299 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131300 # In other places in chromium, we often have to retry this command
1301 # because we're worried about other processes still holding on to
1302 # file handles, but when MB is invoked, it will be early enough in the
1303 # build that their should be no other processes to interfere. We
1304 # can change this if need be.
1305 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1306 else:
1307 shutil.rmtree(abs_path, ignore_errors=True)
1308
dprankef61de2f2015-05-14 04:09:561309 def TempFile(self, mode='w'):
1310 # This function largely exists so it can be overriden for testing.
1311 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1312
dprankee0547cd2015-09-15 01:27:401313 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351314 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401315 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301316 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351317 with open(path, 'w') as fp:
1318 return fp.write(contents)
1319
dprankef61de2f2015-05-14 04:09:561320
dprankefe4602312015-04-08 16:20:351321class MBErr(Exception):
1322 pass
1323
1324
dpranke3cec199c2015-09-22 23:29:021325# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1326# details of this next section, which handles escaping command lines
1327# so that they can be copied and pasted into a cmd window.
1328UNSAFE_FOR_SET = set('^<>&|')
1329UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1330ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1331
1332
1333def QuoteForSet(arg):
1334 if any(a in UNSAFE_FOR_SET for a in arg):
1335 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1336 return arg
1337
1338
1339def QuoteForCmd(arg):
1340 # First, escape the arg so that CommandLineToArgvW will parse it properly.
dpranke3cec199c2015-09-22 23:29:021341 if arg == '' or ' ' in arg or '"' in arg:
1342 quote_re = re.compile(r'(\\*)"')
1343 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1344
1345 # Then check to see if the arg contains any metacharacters other than
1346 # double quotes; if it does, quote everything (including the double
1347 # quotes) for safety.
1348 if any(a in UNSAFE_FOR_CMD for a in arg):
1349 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1350 return arg
1351
1352
dprankefe4602312015-04-08 16:20:351353if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591354 sys.exit(main(sys.argv[1:]))