blob: a28367843b48106c66ac2104ad3830d07b36d620 [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',
94 default=self.default_isolate_map,
95 help='path to isolate map file '
96 '(default is %(default)s)')
dpranked0c138b2016-04-13 18:28:4797 subp.add_argument('-g', '--goma-dir',
98 help='path to goma directory')
agrieve41d21a72016-04-14 18:02:2699 subp.add_argument('--android-version-code',
Dirk Pranked181a1a2017-12-14 01:47:11100 help='Sets GN arg android_default_version_code')
agrieve41d21a72016-04-14 18:02:26101 subp.add_argument('--android-version-name',
Dirk Pranked181a1a2017-12-14 01:47:11102 help='Sets GN arg android_default_version_name')
dprankefe4602312015-04-08 16:20:35103 subp.add_argument('-n', '--dryrun', action='store_true',
104 help='Do a dry run (i.e., do nothing, just print '
105 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:40106 subp.add_argument('-v', '--verbose', action='store_true',
107 help='verbose logging')
dprankefe4602312015-04-08 16:20:35108
109 parser = argparse.ArgumentParser(prog='mb')
110 subps = parser.add_subparsers()
111
112 subp = subps.add_parser('analyze',
113 help='analyze whether changes to a set of files '
114 'will cause a set of binaries to be rebuilt.')
115 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:25116 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35117 help='path build was generated into.')
118 subp.add_argument('input_path', nargs=1,
119 help='path to a file containing the input arguments '
120 'as a JSON object.')
121 subp.add_argument('output_path', nargs=1,
122 help='path to a file containing the output arguments '
123 'as a JSON object.')
124 subp.set_defaults(func=self.CmdAnalyze)
125
dprankef37aebb92016-09-23 01:14:49126 subp = subps.add_parser('export',
127 help='print out the expanded configuration for'
128 'each builder as a JSON object')
129 subp.add_argument('-f', '--config-file', metavar='PATH',
130 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50131 help='path to config file (default is %(default)s)')
dprankef37aebb92016-09-23 01:14:49132 subp.add_argument('-g', '--goma-dir',
133 help='path to goma directory')
134 subp.set_defaults(func=self.CmdExport)
135
dprankefe4602312015-04-08 16:20:35136 subp = subps.add_parser('gen',
137 help='generate a new set of build files')
138 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39139 subp.add_argument('--swarming-targets-file',
140 help='save runtime dependencies for targets listed '
141 'in file.')
dpranked8113582015-06-05 20:08:25142 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35143 help='path to generate build into')
144 subp.set_defaults(func=self.CmdGen)
145
dpranke751516a2015-10-03 01:11:34146 subp = subps.add_parser('isolate',
147 help='generate the .isolate files for a given'
148 'binary')
149 AddCommonOptions(subp)
150 subp.add_argument('path', nargs=1,
151 help='path build was generated into')
152 subp.add_argument('target', nargs=1,
153 help='ninja target to generate the isolate for')
154 subp.set_defaults(func=self.CmdIsolate)
155
dprankefe4602312015-04-08 16:20:35156 subp = subps.add_parser('lookup',
157 help='look up the command for a given config or '
158 'builder')
159 AddCommonOptions(subp)
160 subp.set_defaults(func=self.CmdLookup)
161
dpranke030d7a6d2016-03-26 17:23:50162 subp = subps.add_parser(
163 'run',
164 help='build and run the isolated version of a '
165 'binary',
166 formatter_class=argparse.RawDescriptionHelpFormatter)
167 subp.description = (
168 'Build, isolate, and run the given binary with the command line\n'
169 'listed in the isolate. You may pass extra arguments after the\n'
170 'target; use "--" if the extra arguments need to include switches.\n'
171 '\n'
172 'Examples:\n'
173 '\n'
174 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
175 ' //out/Default content_browsertests\n'
176 '\n'
177 ' % tools/mb/mb.py run out/Default content_browsertests\n'
178 '\n'
179 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
180 ' --test-launcher-retry-limit=0'
181 '\n'
182 )
dpranke751516a2015-10-03 01:11:34183 AddCommonOptions(subp)
184 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
185 help='Number of jobs to pass to ninja')
186 subp.add_argument('--no-build', dest='build', default=True,
187 action='store_false',
188 help='Do not build, just isolate and run')
189 subp.add_argument('path', nargs=1,
dpranke030d7a6d2016-03-26 17:23:50190 help=('path to generate build into (or use).'
191 ' This can be either a regular path or a '
192 'GN-style source-relative path like '
193 '//out/Default.'))
Dirk Pranke8cb6aa782017-12-16 02:31:33194 subp.add_argument('-s', '--swarmed', action='store_true',
195 help='Run under swarming with the default dimensions')
196 subp.add_argument('-d', '--dimension', default=[], action='append', nargs=2,
197 dest='dimensions', metavar='FOO bar',
198 help='dimension to filter on')
199 subp.add_argument('--no-default-dimensions', action='store_false',
200 dest='default_dimensions', default=True,
201 help='Do not automatically add dimensions to the task')
dpranke751516a2015-10-03 01:11:34202 subp.add_argument('target', nargs=1,
203 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50204 subp.add_argument('extra_args', nargs='*',
205 help=('extra args to pass to the isolate to run. Use '
206 '"--" as the first arg if you need to pass '
207 'switches'))
dpranke751516a2015-10-03 01:11:34208 subp.set_defaults(func=self.CmdRun)
209
dprankefe4602312015-04-08 16:20:35210 subp = subps.add_parser('validate',
211 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17212 subp.add_argument('-f', '--config-file', metavar='PATH',
213 default=self.default_config,
kjellander902bcb62016-10-26 06:20:50214 help='path to config file (default is %(default)s)')
dprankefe4602312015-04-08 16:20:35215 subp.set_defaults(func=self.CmdValidate)
216
Peter Collingbourne4dfb64a2017-08-12 01:00:55217 subp = subps.add_parser('gerrit-buildbucket-config',
218 help='Print buildbucket.config for gerrit '
219 '(see MB user guide)')
220 subp.add_argument('-f', '--config-file', metavar='PATH',
221 default=self.default_config,
222 help='path to config file (default is %(default)s)')
223 subp.set_defaults(func=self.CmdBuildbucket)
224
dprankefe4602312015-04-08 16:20:35225 subp = subps.add_parser('help',
226 help='Get help on a subcommand.')
227 subp.add_argument(nargs='?', action='store', dest='subcommand',
228 help='The command to get help for.')
229 subp.set_defaults(func=self.CmdHelp)
230
231 self.args = parser.parse_args(argv)
232
dprankeb2be10a2016-02-22 17:11:00233 def DumpInputFiles(self):
234
dprankef7b7eb7a2016-03-28 22:42:59235 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00236 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59237 self.Print("\n# To recreate the file passed to %s:" % arg_name)
dprankecb4a2e242016-09-19 01:13:14238 self.Print("%% cat > %s <<EOF" % path)
dprankeb2be10a2016-02-22 17:11:00239 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59240 self.Print(contents)
241 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00242
dprankef7b7eb7a2016-03-28 22:42:59243 if getattr(self.args, 'input_path', None):
244 DumpContentsOfFilePassedTo(
245 'argv[0] (input_path)', self.args.input_path[0])
246 if getattr(self.args, 'swarming_targets_file', None):
247 DumpContentsOfFilePassedTo(
248 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00249
dprankefe4602312015-04-08 16:20:35250 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34251 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11252 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35253
dprankef37aebb92016-09-23 01:14:49254 def CmdExport(self):
255 self.ReadConfigFile()
256 obj = {}
257 for master, builders in self.masters.items():
258 obj[master] = {}
259 for builder in builders:
260 config = self.masters[master][builder]
261 if not config:
262 continue
263
shenghuazhang804b21542016-10-11 02:06:49264 if isinstance(config, dict):
265 args = {k: self.FlattenConfig(v)['gn_args']
266 for k, v in config.items()}
dprankef37aebb92016-09-23 01:14:49267 elif config.startswith('//'):
268 args = config
269 else:
270 args = self.FlattenConfig(config)['gn_args']
271 if 'error' in args:
272 continue
273
274 obj[master][builder] = args
275
276 # Dump object and trim trailing whitespace.
277 s = '\n'.join(l.rstrip() for l in
278 json.dumps(obj, sort_keys=True, indent=2).splitlines())
279 self.Print(s)
280 return 0
281
dprankefe4602312015-04-08 16:20:35282 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34283 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11284 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35285
286 def CmdHelp(self):
287 if self.args.subcommand:
288 self.ParseArgs([self.args.subcommand, '--help'])
289 else:
290 self.ParseArgs(['--help'])
291
dpranke751516a2015-10-03 01:11:34292 def CmdIsolate(self):
293 vals = self.GetConfig()
294 if not vals:
295 return 1
Dirk Pranked181a1a2017-12-14 01:47:11296 return self.RunGNIsolate(vals)
dpranke751516a2015-10-03 01:11:34297
298 def CmdLookup(self):
299 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11300 cmd = self.GNCmd('gen', '_path_')
301 gn_args = self.GNArgs(vals)
302 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
303 env = None
dpranke751516a2015-10-03 01:11:34304
305 self.PrintCmd(cmd, env)
306 return 0
307
308 def CmdRun(self):
309 vals = self.GetConfig()
310 if not vals:
311 return 1
312
313 build_dir = self.args.path[0]
314 target = self.args.target[0]
315
Dirk Pranked181a1a2017-12-14 01:47:11316 if self.args.build:
317 ret = self.Build(target)
dpranke751516a2015-10-03 01:11:34318 if ret:
319 return ret
Dirk Pranked181a1a2017-12-14 01:47:11320 ret = self.RunGNIsolate(vals)
321 if ret:
322 return ret
dpranke751516a2015-10-03 01:11:34323
Dirk Pranke8cb6aa782017-12-16 02:31:33324 if self.args.swarmed:
325 return self._RunUnderSwarming(build_dir, target)
326 else:
327 return self._RunLocallyIsolated(build_dir, target)
328
329 def _RunUnderSwarming(self, build_dir, target):
330 # TODO(dpranke): Look up the information for the target in
331 # the //testing/buildbot.json file, if possible, so that we
332 # can determine the isolate target, command line, and additional
333 # swarming parameters, if possible.
334 #
335 # TODO(dpranke): Also, add support for sharding and merging results.
336 dimensions = []
337 for k, v in self._DefaultDimensions() + self.args.dimensions:
338 dimensions += ['-d', k, v]
339
340 cmd = [
341 self.executable,
342 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
343 'archive',
344 '-s',
345 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
346 '-I', 'isolateserver.appspot.com',
347 ]
348 ret, out, _ = self.Run(cmd, force_verbose=False)
349 if ret:
350 return ret
351
352 isolated_hash = out.splitlines()[0].split()[0]
353 cmd = [
354 self.executable,
355 self.PathJoin('tools', 'swarming_client', 'swarming.py'),
356 'run',
357 '-s', isolated_hash,
358 '-I', 'isolateserver.appspot.com',
359 '-S', 'chromium-swarm.appspot.com',
360 ] + dimensions
361 if self.args.extra_args:
362 cmd += ['--'] + self.args.extra_args
363 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
364 return ret
365
366 def _RunLocallyIsolated(self, build_dir, target):
dpranke030d7a6d2016-03-26 17:23:50367 cmd = [
dpranke751516a2015-10-03 01:11:34368 self.executable,
369 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
370 'run',
371 '-s',
dpranke030d7a6d2016-03-26 17:23:50372 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
Dirk Pranke8cb6aa782017-12-16 02:31:33373 ]
dpranke030d7a6d2016-03-26 17:23:50374 if self.args.extra_args:
Dirk Pranke8cb6aa782017-12-16 02:31:33375 cmd += ['--'] + self.args.extra_args
376 ret, _, _ = self.Run(cmd, force_verbose=True, buffer_output=False)
dpranke751516a2015-10-03 01:11:34377 return ret
378
Dirk Pranke8cb6aa782017-12-16 02:31:33379 def _DefaultDimensions(self):
380 if not self.args.default_dimensions:
381 return []
382
383 # This code is naive and just picks reasonable defaults per platform.
384 if self.platform == 'darwin':
385 os_dim = ('os', 'Mac-10.12')
386 elif self.platform.startswith('linux'):
387 os_dim = ('os', 'Ubuntu-14.04')
388 elif self.platform == 'win32':
389 os_dim = ('os', 'Windows-10-14393')
390 else:
391 raise MBErr('unrecognized platform string "%s"' % self.platform)
392
393 return [('pool', 'Chrome'),
394 ('cpu', 'x86-64'),
395 os_dim]
396
Peter Collingbourne4dfb64a2017-08-12 01:00:55397 def CmdBuildbucket(self):
398 self.ReadConfigFile()
399
400 self.Print('# This file was generated using '
401 '"tools/mb/mb.py gerrit-buildbucket-config".')
402
403 for luci_tryserver in sorted(self.luci_tryservers):
404 self.Print('[bucket "luci.%s"]' % luci_tryserver)
405 for bot in sorted(self.luci_tryservers[luci_tryserver]):
406 self.Print('\tbuilder = %s' % bot)
407
408 for master in sorted(self.masters):
409 if master.startswith('tryserver.'):
410 self.Print('[bucket "master.%s"]' % master)
411 for bot in sorted(self.masters[master]):
412 self.Print('\tbuilder = %s' % bot)
413
414 return 0
415
dpranke0cafc162016-03-19 00:41:10416 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35417 errs = []
418
419 # Read the file to make sure it parses.
420 self.ReadConfigFile()
421
dpranke3be00142016-03-17 22:46:04422 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35423 all_configs = {}
dprankefe4602312015-04-08 16:20:35424 for master in self.masters:
dpranke3be00142016-03-17 22:46:04425 for config in self.masters[master].values():
shenghuazhang804b21542016-10-11 02:06:49426 if isinstance(config, dict):
427 for c in config.values():
dprankeb9380a12016-07-21 21:44:09428 all_configs[c] = master
429 else:
430 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35431
dpranke9dd5e252016-04-14 04:23:09432 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35433 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09434 if config.startswith('//'):
435 if not self.Exists(self.ToAbsPath(config)):
436 errs.append('Unknown args file "%s" referenced from "%s".' %
437 (config, loc))
438 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35439 errs.append('Unknown config "%s" referenced from "%s".' %
440 (config, loc))
441
442 # Check that every actual config is actually referenced.
443 for config in self.configs:
444 if not config in all_configs:
445 errs.append('Unused config "%s".' % config)
446
447 # Figure out the whole list of mixins, and check that every mixin
448 # listed by a config or another mixin actually exists.
449 referenced_mixins = set()
450 for config, mixins in self.configs.items():
451 for mixin in mixins:
452 if not mixin in self.mixins:
453 errs.append('Unknown mixin "%s" referenced by config "%s".' %
454 (mixin, config))
455 referenced_mixins.add(mixin)
456
457 for mixin in self.mixins:
458 for sub_mixin in self.mixins[mixin].get('mixins', []):
459 if not sub_mixin in self.mixins:
460 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
461 (sub_mixin, mixin))
462 referenced_mixins.add(sub_mixin)
463
464 # Check that every mixin defined is actually referenced somewhere.
465 for mixin in self.mixins:
466 if not mixin in referenced_mixins:
467 errs.append('Unreferenced mixin "%s".' % mixin)
468
dpranke255085e2016-03-16 05:23:59469 # If we're checking the Chromium config, check that the 'chromium' bots
470 # which build public artifacts do not include the chrome_with_codecs mixin.
471 if self.args.config_file == self.default_config:
472 if 'chromium' in self.masters:
473 for builder in self.masters['chromium']:
474 config = self.masters['chromium'][builder]
475 def RecurseMixins(current_mixin):
476 if current_mixin == 'chrome_with_codecs':
477 errs.append('Public artifact builder "%s" can not contain the '
478 '"chrome_with_codecs" mixin.' % builder)
479 return
480 if not 'mixins' in self.mixins[current_mixin]:
481 return
482 for mixin in self.mixins[current_mixin]['mixins']:
483 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41484
dpranke255085e2016-03-16 05:23:59485 for mixin in self.configs[config]:
486 RecurseMixins(mixin)
487 else:
488 errs.append('Missing "chromium" master. Please update this '
489 'proprietary codecs check with the name of the master '
490 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41491
dprankefe4602312015-04-08 16:20:35492 if errs:
dpranke4323c80632015-08-10 22:53:54493 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17494 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35495
dpranke0cafc162016-03-19 00:41:10496 if print_ok:
497 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35498 return 0
499
dprankefe4602312015-04-08 16:20:35500 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34501 build_dir = self.args.path[0]
502
dprankef37aebb92016-09-23 01:14:49503 vals = self.DefaultVals()
dpranke751516a2015-10-03 01:11:34504 if self.args.builder or self.args.master or self.args.config:
505 vals = self.Lookup()
Dirk Pranked181a1a2017-12-14 01:47:11506 # Re-run gn gen in order to ensure the config is consistent with the
507 # build dir.
508 self.RunGNGen(vals)
dpranke751516a2015-10-03 01:11:34509 return vals
510
Dirk Pranked181a1a2017-12-14 01:47:11511 toolchain_path = self.PathJoin(self.ToAbsPath(build_dir),
512 'toolchain.ninja')
513 if not self.Exists(toolchain_path):
514 self.Print('Must either specify a path to an existing GN build dir '
515 'or pass in a -m/-b pair or a -c flag to specify the '
516 'configuration')
517 return {}
dpranke751516a2015-10-03 01:11:34518
Dirk Pranked181a1a2017-12-14 01:47:11519 vals['gn_args'] = self.GNArgsFromDir(build_dir)
dpranke751516a2015-10-03 01:11:34520 return vals
521
dprankef37aebb92016-09-23 01:14:49522 def GNArgsFromDir(self, build_dir):
brucedawsonecc0c1cd2016-06-02 18:24:58523 args_contents = ""
524 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
525 if self.Exists(gn_args_path):
526 args_contents = self.ReadFile(gn_args_path)
dpranke751516a2015-10-03 01:11:34527 gn_args = []
528 for l in args_contents.splitlines():
529 fields = l.split(' ')
530 name = fields[0]
531 val = ' '.join(fields[2:])
532 gn_args.append('%s=%s' % (name, val))
533
dprankef37aebb92016-09-23 01:14:49534 return ' '.join(gn_args)
dpranke751516a2015-10-03 01:11:34535
536 def Lookup(self):
dprankef37aebb92016-09-23 01:14:49537 vals = self.ReadIOSBotConfig()
dprankee0f486f2015-11-19 23:42:00538 if not vals:
539 self.ReadConfigFile()
540 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09541 if config.startswith('//'):
542 if not self.Exists(self.ToAbsPath(config)):
543 raise MBErr('args file "%s" not found' % config)
dprankef37aebb92016-09-23 01:14:49544 vals = self.DefaultVals()
545 vals['args_file'] = config
dpranke9dd5e252016-04-14 04:23:09546 else:
547 if not config in self.configs:
548 raise MBErr('Config "%s" not found in %s' %
549 (config, self.args.config_file))
550 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34551 return vals
dprankefe4602312015-04-08 16:20:35552
dprankef37aebb92016-09-23 01:14:49553 def ReadIOSBotConfig(self):
dprankee0f486f2015-11-19 23:42:00554 if not self.args.master or not self.args.builder:
555 return {}
556 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
557 self.args.master, self.args.builder + '.json')
558 if not self.Exists(path):
559 return {}
560
561 contents = json.loads(self.ReadFile(path))
dprankee0f486f2015-11-19 23:42:00562 gn_args = ' '.join(contents.get('gn_args', []))
563
dprankef37aebb92016-09-23 01:14:49564 vals = self.DefaultVals()
565 vals['gn_args'] = gn_args
dprankef37aebb92016-09-23 01:14:49566 return vals
dprankee0f486f2015-11-19 23:42:00567
dprankefe4602312015-04-08 16:20:35568 def ReadConfigFile(self):
569 if not self.Exists(self.args.config_file):
570 raise MBErr('config file not found at %s' % self.args.config_file)
571
572 try:
573 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
574 except SyntaxError as e:
575 raise MBErr('Failed to parse config file "%s": %s' %
576 (self.args.config_file, e))
577
dprankefe4602312015-04-08 16:20:35578 self.configs = contents['configs']
Peter Collingbourne4dfb64a2017-08-12 01:00:55579 self.luci_tryservers = contents.get('luci_tryservers', {})
dprankefe4602312015-04-08 16:20:35580 self.masters = contents['masters']
581 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35582
dprankecb4a2e242016-09-19 01:13:14583 def ReadIsolateMap(self):
kjellander902bcb62016-10-26 06:20:50584 if not self.Exists(self.args.isolate_map_file):
585 raise MBErr('isolate map file not found at %s' %
586 self.args.isolate_map_file)
587 try:
588 return ast.literal_eval(self.ReadFile(self.args.isolate_map_file))
589 except SyntaxError as e:
590 raise MBErr('Failed to parse isolate map file "%s": %s' %
591 (self.args.isolate_map_file, e))
dprankecb4a2e242016-09-19 01:13:14592
dprankefe4602312015-04-08 16:20:35593 def ConfigFromArgs(self):
594 if self.args.config:
595 if self.args.master or self.args.builder:
596 raise MBErr('Can not specific both -c/--config and -m/--master or '
597 '-b/--builder')
598
599 return self.args.config
600
601 if not self.args.master or not self.args.builder:
602 raise MBErr('Must specify either -c/--config or '
603 '(-m/--master and -b/--builder)')
604
605 if not self.args.master in self.masters:
606 raise MBErr('Master name "%s" not found in "%s"' %
607 (self.args.master, self.args.config_file))
608
609 if not self.args.builder in self.masters[self.args.master]:
610 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
611 (self.args.builder, self.args.master, self.args.config_file))
612
dprankeb9380a12016-07-21 21:44:09613 config = self.masters[self.args.master][self.args.builder]
shenghuazhang804b21542016-10-11 02:06:49614 if isinstance(config, dict):
dprankeb9380a12016-07-21 21:44:09615 if self.args.phase is None:
616 raise MBErr('Must specify a build --phase for %s on %s' %
617 (self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49618 phase = str(self.args.phase)
619 if phase not in config:
620 raise MBErr('Phase %s doesn\'t exist for %s on %s' %
dprankeb9380a12016-07-21 21:44:09621 (phase, self.args.builder, self.args.master))
shenghuazhang804b21542016-10-11 02:06:49622 return config[phase]
dprankeb9380a12016-07-21 21:44:09623
624 if self.args.phase is not None:
625 raise MBErr('Must not specify a build --phase for %s on %s' %
626 (self.args.builder, self.args.master))
627 return config
dprankefe4602312015-04-08 16:20:35628
629 def FlattenConfig(self, config):
630 mixins = self.configs[config]
dprankef37aebb92016-09-23 01:14:49631 vals = self.DefaultVals()
dprankefe4602312015-04-08 16:20:35632
633 visited = []
634 self.FlattenMixins(mixins, vals, visited)
635 return vals
636
dprankef37aebb92016-09-23 01:14:49637 def DefaultVals(self):
638 return {
639 'args_file': '',
640 'cros_passthrough': False,
641 'gn_args': '',
dprankef37aebb92016-09-23 01:14:49642 }
643
dprankefe4602312015-04-08 16:20:35644 def FlattenMixins(self, mixins, vals, visited):
645 for m in mixins:
646 if m not in self.mixins:
647 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22648
dprankefe4602312015-04-08 16:20:35649 visited.append(m)
650
651 mixin_vals = self.mixins[m]
dpranke73ed0d62016-04-25 19:18:34652
653 if 'cros_passthrough' in mixin_vals:
654 vals['cros_passthrough'] = mixin_vals['cros_passthrough']
Dirk Pranke6b99f072017-04-05 00:58:30655 if 'args_file' in mixin_vals:
656 if vals['args_file']:
657 raise MBErr('args_file specified multiple times in mixins '
658 'for %s on %s' % (self.args.builder, self.args.master))
659 vals['args_file'] = mixin_vals['args_file']
dprankefe4602312015-04-08 16:20:35660 if 'gn_args' in mixin_vals:
661 if vals['gn_args']:
662 vals['gn_args'] += ' ' + mixin_vals['gn_args']
663 else:
664 vals['gn_args'] = mixin_vals['gn_args']
dpranke73ed0d62016-04-25 19:18:34665
dprankefe4602312015-04-08 16:20:35666 if 'mixins' in mixin_vals:
667 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
668 return vals
669
Dirk Prankea3727f92017-07-17 17:30:33670 def RunGNGen(self, vals, compute_grit_inputs_for_analyze=False):
dpranke751516a2015-10-03 01:11:34671 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50672
dprankeeca4a782016-04-14 01:42:38673 cmd = self.GNCmd('gen', build_dir, '--check')
674 gn_args = self.GNArgs(vals)
Dirk Prankea3727f92017-07-17 17:30:33675 if compute_grit_inputs_for_analyze:
676 gn_args += ' compute_grit_inputs_for_analyze=true'
dprankeeca4a782016-04-14 01:42:38677
678 # Since GN hasn't run yet, the build directory may not even exist.
679 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
680
681 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54682 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39683
684 swarming_targets = []
dpranke751516a2015-10-03 01:11:34685 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39686 # We need GN to generate the list of runtime dependencies for
687 # the compile targets listed (one per line) in the file so
dprankecb4a2e242016-09-19 01:13:14688 # we can run them via swarming. We use gn_isolate_map.pyl to convert
dpranke74559b52015-06-10 21:20:39689 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00690 path = self.args.swarming_targets_file
691 if not self.Exists(path):
692 self.WriteFailureAndRaise('"%s" does not exist' % path,
693 output_path=None)
694 contents = self.ReadFile(path)
695 swarming_targets = set(contents.splitlines())
dprankeb2be10a2016-02-22 17:11:00696
dprankecb4a2e242016-09-19 01:13:14697 isolate_map = self.ReadIsolateMap()
698 err, labels = self.MapTargetsToLabels(isolate_map, swarming_targets)
dprankeb2be10a2016-02-22 17:11:00699 if err:
dprankecb4a2e242016-09-19 01:13:14700 raise MBErr(err)
dpranke74559b52015-06-10 21:20:39701
dpranke751516a2015-10-03 01:11:34702 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dprankecb4a2e242016-09-19 01:13:14703 self.WriteFile(gn_runtime_deps_path, '\n'.join(labels) + '\n')
dpranke74559b52015-06-10 21:20:39704 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
705
dprankefe4602312015-04-08 16:20:35706 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40707 if ret:
708 # If `gn gen` failed, we should exit early rather than trying to
709 # generate isolates. Run() will have already logged any error output.
710 self.Print('GN gen failed: %d' % ret)
711 return ret
dpranke74559b52015-06-10 21:20:39712
jbudoricke3c4f95e2016-04-28 23:17:38713 android = 'target_os="android"' in vals['gn_args']
dpranke74559b52015-06-10 21:20:39714 for target in swarming_targets:
jbudoricke3c4f95e2016-04-28 23:17:38715 if android:
716 # Android targets may be either android_apk or executable. The former
jbudorick91c8a6012016-01-29 23:20:02717 # will result in runtime_deps associated with the stamp file, while the
718 # latter will result in runtime_deps associated with the executable.
dprankecb4a2e242016-09-19 01:13:14719 label = isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02720 runtime_deps_targets = [
dprankecb4a2e242016-09-19 01:13:14721 target + '.runtime_deps',
dpranke48ccf8f2016-03-28 23:58:28722 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
dprankecb4a2e242016-09-19 01:13:14723 elif (isolate_map[target]['type'] == 'script' or
724 isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11725 # For script targets, the build target is usually a group,
726 # for which gn generates the runtime_deps next to the stamp file
eyaich82d5ac942016-11-03 12:13:49727 # for the label, which lives under the obj/ directory, but it may
728 # also be an executable.
dprankecb4a2e242016-09-19 01:13:14729 label = isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28730 runtime_deps_targets = [
731 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
eyaich82d5ac942016-11-03 12:13:49732 if self.platform == 'win32':
733 runtime_deps_targets += [ target + '.exe.runtime_deps' ]
734 else:
735 runtime_deps_targets += [ target + '.runtime_deps' ]
dpranke48ccf8f2016-03-28 23:58:28736 elif self.platform == 'win32':
737 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52738 else:
dpranke48ccf8f2016-03-28 23:58:28739 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02740
dpranke48ccf8f2016-03-28 23:58:28741 for r in runtime_deps_targets:
742 runtime_deps_path = self.ToAbsPath(build_dir, r)
743 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02744 break
745 else:
dpranke48ccf8f2016-03-28 23:58:28746 raise MBErr('did not generate any of %s' %
747 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39748
dprankecb4a2e242016-09-19 01:13:14749 command, extra_files = self.GetIsolateCommand(target, vals)
dpranked5b2b9432015-06-23 16:55:30750
dpranke48ccf8f2016-03-28 23:58:28751 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30752
dpranke751516a2015-10-03 01:11:34753 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
754 extra_files)
dpranked5b2b9432015-06-23 16:55:30755
dpranke751516a2015-10-03 01:11:34756 return 0
757
758 def RunGNIsolate(self, vals):
dprankecb4a2e242016-09-19 01:13:14759 target = self.args.target[0]
760 isolate_map = self.ReadIsolateMap()
761 err, labels = self.MapTargetsToLabels(isolate_map, [target])
762 if err:
763 raise MBErr(err)
764 label = labels[0]
dpranke751516a2015-10-03 01:11:34765
766 build_dir = self.args.path[0]
dprankecb4a2e242016-09-19 01:13:14767 command, extra_files = self.GetIsolateCommand(target, vals)
dpranke751516a2015-10-03 01:11:34768
dprankeeca4a782016-04-14 01:42:38769 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20770 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34771 if ret:
dpranke030d7a6d2016-03-26 17:23:50772 if out:
773 self.Print(out)
dpranke751516a2015-10-03 01:11:34774 return ret
775
776 runtime_deps = out.splitlines()
777
778 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
779 extra_files)
780
781 ret, _, _ = self.Run([
782 self.executable,
783 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
784 'check',
785 '-i',
786 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
787 '-s',
788 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
789 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30790
dprankefe4602312015-04-08 16:20:35791 return ret
792
dpranke751516a2015-10-03 01:11:34793 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
794 extra_files):
795 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
796 self.WriteFile(isolate_path,
797 pprint.pformat({
798 'variables': {
799 'command': command,
800 'files': sorted(runtime_deps + extra_files),
801 }
802 }) + '\n')
803
804 self.WriteJSON(
805 {
806 'args': [
807 '--isolated',
808 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
809 '--isolate',
810 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
811 ],
812 'dir': self.chromium_src_dir,
813 'version': 1,
814 },
815 isolate_path + 'd.gen.json',
816 )
817
dprankecb4a2e242016-09-19 01:13:14818 def MapTargetsToLabels(self, isolate_map, targets):
819 labels = []
820 err = ''
821
dprankecb4a2e242016-09-19 01:13:14822 for target in targets:
823 if target == 'all':
824 labels.append(target)
825 elif target.startswith('//'):
826 labels.append(target)
827 else:
828 if target in isolate_map:
thakis024d6f32017-05-16 23:21:42829 if isolate_map[target]['type'] == 'unknown':
dprankecb4a2e242016-09-19 01:13:14830 err += ('test target "%s" type is unknown\n' % target)
831 else:
thakis024d6f32017-05-16 23:21:42832 labels.append(isolate_map[target]['label'])
dprankecb4a2e242016-09-19 01:13:14833 else:
834 err += ('target "%s" not found in '
835 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
836
837 return err, labels
838
dprankeeca4a782016-04-14 01:42:38839 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51840 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20841 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51842 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20843 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51844 else:
dpranke40da0202016-02-13 05:05:20845 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38846
dpranke40da0202016-02-13 05:05:20847 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranke10118bf2016-09-16 23:16:08848 return [gn_path, subcommand, path] + list(args)
dpranke9aba8b212016-09-16 22:52:52849
dprankecb4a2e242016-09-19 01:13:14850
dprankeeca4a782016-04-14 01:42:38851 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34852 if vals['cros_passthrough']:
853 if not 'GN_ARGS' in os.environ:
854 raise MBErr('MB is expecting GN_ARGS to be in the environment')
855 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16856 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30857 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34858 gn_args)
859 else:
860 gn_args = vals['gn_args']
861
dpranked0c138b2016-04-13 18:28:47862 if self.args.goma_dir:
863 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38864
agrieve41d21a72016-04-14 18:02:26865 android_version_code = self.args.android_version_code
866 if android_version_code:
867 gn_args += ' android_default_version_code="%s"' % android_version_code
868
869 android_version_name = self.args.android_version_name
870 if android_version_name:
871 gn_args += ' android_default_version_name="%s"' % android_version_name
872
dprankeeca4a782016-04-14 01:42:38873 # Canonicalize the arg string into a sorted, newline-separated list
874 # of key-value pairs, and de-dup the keys if need be so that only
875 # the last instance of each arg is listed.
876 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
877
dpranke9dd5e252016-04-14 04:23:09878 args_file = vals.get('args_file', None)
879 if args_file:
880 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38881 return gn_args
dprankefe4602312015-04-08 16:20:35882
dprankecb4a2e242016-09-19 01:13:14883 def GetIsolateCommand(self, target, vals):
kylechar50abf5a2016-11-29 16:03:07884 isolate_map = self.ReadIsolateMap()
885
Scott Graham3be4b4162017-09-12 00:41:41886 is_android = 'target_os="android"' in vals['gn_args']
887 is_fuchsia = 'target_os="fuchsia"' in vals['gn_args']
jbudoricke8428732016-02-02 02:17:06888
kylechar39705682017-01-19 14:37:23889 # This should be true if tests with type='windowed_test_launcher' are
890 # expected to run using xvfb. For example, Linux Desktop, X11 CrOS and
msisovaea52732017-03-21 08:08:08891 # Ozone CrOS builds. Note that one Ozone build can be used to run differen
892 # backends. Currently, tests are executed for the headless and X11 backends
893 # and both can run under Xvfb.
894 # TODO(tonikitoo,msisov,fwang): Find a way to run tests for the Wayland
895 # backend.
Scott Graham3be4b4162017-09-12 00:41:41896 use_xvfb = self.platform == 'linux2' and not is_android and not is_fuchsia
dpranked8113582015-06-05 20:08:25897
898 asan = 'is_asan=true' in vals['gn_args']
899 msan = 'is_msan=true' in vals['gn_args']
900 tsan = 'is_tsan=true' in vals['gn_args']
pcc46233c22017-06-20 22:11:41901 cfi_diag = 'use_cfi_diag=true' in vals['gn_args']
dpranked8113582015-06-05 20:08:25902
dprankecb4a2e242016-09-19 01:13:14903 test_type = isolate_map[target]['type']
dprankefe0d35e2016-02-05 02:43:59904
dprankecb4a2e242016-09-19 01:13:14905 executable = isolate_map[target].get('executable', target)
dprankefe0d35e2016-02-05 02:43:59906 executable_suffix = '.exe' if self.platform == 'win32' else ''
907
dprankea55584f12015-07-22 00:52:47908 cmdline = []
Andrii Shyshkalovc158e0102018-01-10 05:52:00909 extra_files = [
910 '../../.vpython',
911 '../../testing/test_env.py',
912 ]
dpranked8113582015-06-05 20:08:25913
dprankecb4a2e242016-09-19 01:13:14914 if test_type == 'nontest':
915 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
916 output_path=None)
917
Scott Graham3be4b4162017-09-12 00:41:41918 if is_android and test_type != "script":
bpastenee428ea92017-02-17 02:20:32919 cmdline = [
John Budorickfb97a852017-12-20 20:10:19920 '../../testing/test_env.py',
hzl9b15df52017-03-23 23:43:04921 '../../build/android/test_wrapper/logdog_wrapper.py',
922 '--target', target,
hzl9ae14452017-04-04 23:38:02923 '--logdog-bin-cmd', '../../bin/logdog_butler',
hzlfc66094f2017-05-18 00:50:48924 '--store-tombstones']
Scott Graham3be4b4162017-09-12 00:41:41925 elif is_fuchsia and test_type != 'script':
John Budorickfb97a852017-12-20 20:10:19926 cmdline = [
927 '../../testing/test_env.py',
928 os.path.join('bin', 'run_%s' % target),
929 ]
kylechar39705682017-01-19 14:37:23930 elif use_xvfb and test_type == 'windowed_test_launcher':
Andrii Shyshkalovc158e0102018-01-10 05:52:00931 extra_files.append('../../testing/xvfb.py')
dprankea55584f12015-07-22 00:52:47932 cmdline = [
dprankefe0d35e2016-02-05 02:43:59933 '../../testing/xvfb.py',
dprankefe0d35e2016-02-05 02:43:59934 './' + str(executable) + executable_suffix,
935 '--brave-new-test-launcher',
936 '--test-launcher-bot-mode',
937 '--asan=%d' % asan,
938 '--msan=%d' % msan,
939 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41940 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47941 ]
942 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
dprankea55584f12015-07-22 00:52:47943 cmdline = [
944 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:59945 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:25946 '--brave-new-test-launcher',
947 '--test-launcher-bot-mode',
948 '--asan=%d' % asan,
949 '--msan=%d' % msan,
950 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41951 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47952 ]
dpranke6abd8652015-08-28 03:21:11953 elif test_type == 'script':
dpranke6abd8652015-08-28 03:21:11954 cmdline = [
955 '../../testing/test_env.py',
dprankecb4a2e242016-09-19 01:13:14956 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:59957 ]
dprankea55584f12015-07-22 00:52:47958 elif test_type in ('raw'):
dprankea55584f12015-07-22 00:52:47959 cmdline = [
960 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:59961 ]
dpranked8113582015-06-05 20:08:25962
dprankea55584f12015-07-22 00:52:47963 else:
964 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
965 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25966
dprankecb4a2e242016-09-19 01:13:14967 cmdline += isolate_map[target].get('args', [])
dprankefe0d35e2016-02-05 02:43:59968
dpranked8113582015-06-05 20:08:25969 return cmdline, extra_files
970
dpranke74559b52015-06-10 21:20:39971 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33972 return self.PathJoin(self.chromium_src_dir,
973 self.ToSrcRelPath(build_path),
974 *comps)
dpranked8113582015-06-05 20:08:25975
dprankeee5b51f62015-04-09 00:03:22976 def ToSrcRelPath(self, path):
977 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:50978 if path.startswith('//'):
979 return path[2:].replace('/', self.sep)
980 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:35981
Dirk Pranke0fd41bcd2015-06-19 00:05:50982 def RunGNAnalyze(self, vals):
dprankecb4a2e242016-09-19 01:13:14983 # Analyze runs before 'gn gen' now, so we need to run gn gen
Dirk Pranke0fd41bcd2015-06-19 00:05:50984 # in order to ensure that we have a build directory.
Dirk Prankea3727f92017-07-17 17:30:33985 ret = self.RunGNGen(vals, compute_grit_inputs_for_analyze=True)
Dirk Pranke0fd41bcd2015-06-19 00:05:50986 if ret:
987 return ret
988
dprankecb4a2e242016-09-19 01:13:14989 build_path = self.args.path[0]
990 input_path = self.args.input_path[0]
991 gn_input_path = input_path + '.gn'
992 output_path = self.args.output_path[0]
993 gn_output_path = output_path + '.gn'
994
dpranke7837fc362015-11-19 03:54:16995 inp = self.ReadInputJSON(['files', 'test_targets',
996 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32997 if self.args.verbose:
998 self.Print()
999 self.Print('analyze input:')
1000 self.PrintJSON(inp)
1001 self.Print()
1002
dpranke76734662015-04-16 02:17:501003
dpranke7c5f614d2015-07-22 23:43:391004 # This shouldn't normally happen, but could due to unusual race conditions,
1005 # like a try job that gets scheduled before a patch lands but runs after
1006 # the patch has landed.
1007 if not inp['files']:
1008 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161009 self.WriteJSON({
1010 'status': 'No dependency',
1011 'compile_targets': [],
1012 'test_targets': [],
1013 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391014 return 0
1015
dprankecb4a2e242016-09-19 01:13:141016 gn_inp = {}
dprankeb7b183f2017-04-24 23:50:161017 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
dprankef61de2f2015-05-14 04:09:561018
dprankecb4a2e242016-09-19 01:13:141019 isolate_map = self.ReadIsolateMap()
1020 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1021 isolate_map, inp['additional_compile_targets'])
dprankecb4a2e242016-09-19 01:13:141022 if err:
1023 raise MBErr(err)
1024
1025 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1026 isolate_map, inp['test_targets'])
dprankecb4a2e242016-09-19 01:13:141027 if err:
1028 raise MBErr(err)
1029 labels_to_targets = {}
1030 for i, label in enumerate(gn_inp['test_targets']):
1031 labels_to_targets[label] = inp['test_targets'][i]
1032
dprankef61de2f2015-05-14 04:09:561033 try:
dprankecb4a2e242016-09-19 01:13:141034 self.WriteJSON(gn_inp, gn_input_path)
1035 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1036 ret, _, _ = self.Run(cmd, force_verbose=True)
1037 if ret:
1038 return ret
dpranke067d0142015-05-14 22:52:451039
dprankecb4a2e242016-09-19 01:13:141040 gn_outp_str = self.ReadFile(gn_output_path)
1041 try:
1042 gn_outp = json.loads(gn_outp_str)
1043 except Exception as e:
1044 self.Print("Failed to parse the JSON string GN returned: %s\n%s"
1045 % (repr(gn_outp_str), str(e)))
1046 raise
1047
1048 outp = {}
1049 if 'status' in gn_outp:
1050 outp['status'] = gn_outp['status']
1051 if 'error' in gn_outp:
1052 outp['error'] = gn_outp['error']
1053 if 'invalid_targets' in gn_outp:
1054 outp['invalid_targets'] = gn_outp['invalid_targets']
1055 if 'compile_targets' in gn_outp:
Dirk Pranke45165072017-11-08 04:57:491056 all_input_compile_targets = sorted(
1057 set(inp['test_targets'] + inp['additional_compile_targets']))
1058
1059 # If we're building 'all', we can throw away the rest of the targets
1060 # since they're redundant.
dpranke385a3102016-09-20 22:04:081061 if 'all' in gn_outp['compile_targets']:
1062 outp['compile_targets'] = ['all']
1063 else:
Dirk Pranke45165072017-11-08 04:57:491064 outp['compile_targets'] = gn_outp['compile_targets']
1065
1066 # crbug.com/736215: When GN returns targets back, for targets in
1067 # the default toolchain, GN will have generated a phony ninja
1068 # target matching the label, and so we can safely (and easily)
1069 # transform any GN label into the matching ninja target. For
1070 # targets in other toolchains, though, GN doesn't generate the
1071 # phony targets, and we don't know how to turn the labels into
1072 # compile targets. In this case, we also conservatively give up
1073 # and build everything. Probably the right thing to do here is
1074 # to have GN return the compile targets directly.
1075 if any("(" in target for target in outp['compile_targets']):
1076 self.Print('WARNING: targets with non-default toolchains were '
1077 'found, building everything instead.')
1078 outp['compile_targets'] = all_input_compile_targets
1079 else:
dpranke385a3102016-09-20 22:04:081080 outp['compile_targets'] = [
Dirk Pranke45165072017-11-08 04:57:491081 label.replace('//', '') for label in outp['compile_targets']]
1082
1083 # Windows has a maximum command line length of 8k; even Linux
1084 # maxes out at 128k; if analyze returns a *really long* list of
1085 # targets, we just give up and conservatively build everything instead.
1086 # Probably the right thing here is for ninja to support response
1087 # files as input on the command line
1088 # (see https://github.com/ninja-build/ninja/issues/1355).
1089 if len(' '.join(outp['compile_targets'])) > 7*1024:
1090 self.Print('WARNING: Too many compile targets were affected.')
1091 self.Print('WARNING: Building everything instead to avoid '
1092 'command-line length issues.')
1093 outp['compile_targets'] = all_input_compile_targets
1094
1095
dprankecb4a2e242016-09-19 01:13:141096 if 'test_targets' in gn_outp:
1097 outp['test_targets'] = [
1098 labels_to_targets[label] for label in gn_outp['test_targets']]
1099
1100 if self.args.verbose:
1101 self.Print()
1102 self.Print('analyze output:')
1103 self.PrintJSON(outp)
1104 self.Print()
1105
1106 self.WriteJSON(outp, output_path)
1107
dprankef61de2f2015-05-14 04:09:561108 finally:
dprankecb4a2e242016-09-19 01:13:141109 if self.Exists(gn_input_path):
1110 self.RemoveFile(gn_input_path)
1111 if self.Exists(gn_output_path):
1112 self.RemoveFile(gn_output_path)
dprankefe4602312015-04-08 16:20:351113
1114 return 0
1115
dpranked8113582015-06-05 20:08:251116 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351117 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321118 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351119 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321120 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351121
1122 try:
1123 inp = json.loads(self.ReadFile(path))
1124 except Exception as e:
1125 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321126 (path, e), output_path)
dpranked8113582015-06-05 20:08:251127
1128 for k in required_keys:
1129 if not k in inp:
1130 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1131 output_path)
dprankefe4602312015-04-08 16:20:351132
1133 return inp
1134
dpranked5b2b9432015-06-23 16:55:301135 def WriteFailureAndRaise(self, msg, output_path):
1136 if output_path:
dprankee0547cd2015-09-15 01:27:401137 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351138 raise MBErr(msg)
1139
dprankee0547cd2015-09-15 01:27:401140 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321141 try:
dprankee0547cd2015-09-15 01:27:401142 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1143 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321144 except Exception as e:
1145 raise MBErr('Error %s writing to the output path "%s"' %
1146 (e, path))
dprankefe4602312015-04-08 16:20:351147
aneeshmde50f472016-04-01 01:13:101148 def CheckCompile(self, master, builder):
1149 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1150 url = urllib2.quote(url_template.format(master=master, builder=builder),
1151 safe=':/()?=')
1152 try:
1153 builds = json.loads(self.Fetch(url))
1154 except Exception as e:
1155 return str(e)
1156 successes = sorted(
1157 [int(x) for x in builds.keys() if "text" in builds[x] and
1158 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1159 reverse=True)
1160 if not successes:
1161 return "no successful builds"
1162 build = builds[str(successes[0])]
1163 step_names = set([step["name"] for step in build["steps"]])
1164 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1165 if compile_indicators & step_names:
1166 return "compiles"
1167 return "does not compile"
1168
dpranke3cec199c2015-09-22 23:29:021169 def PrintCmd(self, cmd, env):
1170 if self.platform == 'win32':
1171 env_prefix = 'set '
1172 env_quoter = QuoteForSet
1173 shell_quoter = QuoteForCmd
1174 else:
1175 env_prefix = ''
1176 env_quoter = pipes.quote
1177 shell_quoter = pipes.quote
1178
1179 def print_env(var):
1180 if env and var in env:
1181 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1182
dprankeec079262016-06-07 02:21:201183 print_env('LLVM_FORCE_HEAD_REVISION')
dpranke3cec199c2015-09-22 23:29:021184
dpranke8c2cfd32015-09-17 20:12:331185 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351186 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021187 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351188
dprankecda00332015-04-11 04:18:321189 def PrintJSON(self, obj):
1190 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1191
dpranke751516a2015-10-03 01:11:341192 def Build(self, target):
1193 build_dir = self.ToSrcRelPath(self.args.path[0])
1194 ninja_cmd = ['ninja', '-C', build_dir]
1195 if self.args.jobs:
1196 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1197 ninja_cmd.append(target)
1198 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1199 return ret
1200
1201 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351202 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401203 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021204 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351205 if self.args.dryrun:
1206 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401207
dpranke751516a2015-10-03 01:11:341208 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401209 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341210 if ret:
1211 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351212 if out:
dprankeee5b51f62015-04-09 00:03:221213 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351214 if err:
dprankeee5b51f62015-04-09 00:03:221215 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351216 return ret, out, err
1217
dpranke751516a2015-10-03 01:11:341218 def Call(self, cmd, env=None, buffer_output=True):
1219 if buffer_output:
1220 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1221 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1222 env=env)
1223 out, err = p.communicate()
1224 else:
1225 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1226 env=env)
1227 p.wait()
1228 out = err = ''
dprankefe4602312015-04-08 16:20:351229 return p.returncode, out, err
1230
1231 def ExpandUser(self, path):
1232 # This function largely exists so it can be overridden for testing.
1233 return os.path.expanduser(path)
1234
1235 def Exists(self, path):
1236 # This function largely exists so it can be overridden for testing.
1237 return os.path.exists(path)
1238
dpranke867bcf4a2016-03-14 22:28:321239 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501240 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321241 f = urllib2.urlopen(url)
1242 contents = f.read()
1243 f.close()
1244 return contents
1245
dprankec3441d12015-06-23 23:01:351246 def MaybeMakeDirectory(self, path):
1247 try:
1248 os.makedirs(path)
1249 except OSError, e:
1250 if e.errno != errno.EEXIST:
1251 raise
1252
dpranke8c2cfd32015-09-17 20:12:331253 def PathJoin(self, *comps):
1254 # This function largely exists so it can be overriden for testing.
1255 return os.path.join(*comps)
1256
dpranke030d7a6d2016-03-26 17:23:501257 def Print(self, *args, **kwargs):
1258 # This function largely exists so it can be overridden for testing.
1259 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101260 if kwargs.get('stream', sys.stdout) == sys.stdout:
1261 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501262
dprankefe4602312015-04-08 16:20:351263 def ReadFile(self, path):
1264 # This function largely exists so it can be overriden for testing.
1265 with open(path) as fp:
1266 return fp.read()
1267
dpranke030d7a6d2016-03-26 17:23:501268 def RelPath(self, path, start='.'):
1269 # This function largely exists so it can be overriden for testing.
1270 return os.path.relpath(path, start)
1271
dprankef61de2f2015-05-14 04:09:561272 def RemoveFile(self, path):
1273 # This function largely exists so it can be overriden for testing.
1274 os.remove(path)
1275
dprankec161aa92015-09-14 20:21:131276 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331277 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131278 # In other places in chromium, we often have to retry this command
1279 # because we're worried about other processes still holding on to
1280 # file handles, but when MB is invoked, it will be early enough in the
1281 # build that their should be no other processes to interfere. We
1282 # can change this if need be.
1283 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1284 else:
1285 shutil.rmtree(abs_path, ignore_errors=True)
1286
dprankef61de2f2015-05-14 04:09:561287 def TempFile(self, mode='w'):
1288 # This function largely exists so it can be overriden for testing.
1289 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1290
dprankee0547cd2015-09-15 01:27:401291 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351292 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401293 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301294 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351295 with open(path, 'w') as fp:
1296 return fp.write(contents)
1297
dprankef61de2f2015-05-14 04:09:561298
dprankefe4602312015-04-08 16:20:351299class MBErr(Exception):
1300 pass
1301
1302
dpranke3cec199c2015-09-22 23:29:021303# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1304# details of this next section, which handles escaping command lines
1305# so that they can be copied and pasted into a cmd window.
1306UNSAFE_FOR_SET = set('^<>&|')
1307UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1308ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1309
1310
1311def QuoteForSet(arg):
1312 if any(a in UNSAFE_FOR_SET for a in arg):
1313 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1314 return arg
1315
1316
1317def QuoteForCmd(arg):
1318 # First, escape the arg so that CommandLineToArgvW will parse it properly.
dpranke3cec199c2015-09-22 23:29:021319 if arg == '' or ' ' in arg or '"' in arg:
1320 quote_re = re.compile(r'(\\*)"')
1321 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1322
1323 # Then check to see if the arg contains any metacharacters other than
1324 # double quotes; if it does, quote everything (including the double
1325 # quotes) for safety.
1326 if any(a in UNSAFE_FOR_CMD for a in arg):
1327 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1328 return arg
1329
1330
dprankefe4602312015-04-08 16:20:351331if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591332 sys.exit(main(sys.argv[1:]))