blob: d6603d68b804be16149823779c30edf226a7a202 [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']
Kevin Marshallf35fa5f2018-01-29 19:24:42714 fuchsia = 'target_os="fuchsia"' in vals['gn_args']
dpranke74559b52015-06-10 21:20:39715 for target in swarming_targets:
jbudoricke3c4f95e2016-04-28 23:17:38716 if android:
717 # Android targets may be either android_apk or executable. The former
jbudorick91c8a6012016-01-29 23:20:02718 # will result in runtime_deps associated with the stamp file, while the
719 # latter will result in runtime_deps associated with the executable.
dprankecb4a2e242016-09-19 01:13:14720 label = isolate_map[target]['label']
jbudorick91c8a6012016-01-29 23:20:02721 runtime_deps_targets = [
dprankecb4a2e242016-09-19 01:13:14722 target + '.runtime_deps',
dpranke48ccf8f2016-03-28 23:58:28723 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
Kevin Marshallf35fa5f2018-01-29 19:24:42724 elif fuchsia:
725 # Only emit a runtime deps file for the group() target on Fuchsia.
726 label = isolate_map[target]['label']
727 runtime_deps_targets = [
728 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
dprankecb4a2e242016-09-19 01:13:14729 elif (isolate_map[target]['type'] == 'script' or
730 isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11731 # For script targets, the build target is usually a group,
732 # for which gn generates the runtime_deps next to the stamp file
eyaich82d5ac942016-11-03 12:13:49733 # for the label, which lives under the obj/ directory, but it may
734 # also be an executable.
dprankecb4a2e242016-09-19 01:13:14735 label = isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28736 runtime_deps_targets = [
737 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
eyaich82d5ac942016-11-03 12:13:49738 if self.platform == 'win32':
739 runtime_deps_targets += [ target + '.exe.runtime_deps' ]
740 else:
741 runtime_deps_targets += [ target + '.runtime_deps' ]
dpranke48ccf8f2016-03-28 23:58:28742 elif self.platform == 'win32':
743 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52744 else:
dpranke48ccf8f2016-03-28 23:58:28745 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02746
dpranke48ccf8f2016-03-28 23:58:28747 for r in runtime_deps_targets:
748 runtime_deps_path = self.ToAbsPath(build_dir, r)
749 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02750 break
751 else:
dpranke48ccf8f2016-03-28 23:58:28752 raise MBErr('did not generate any of %s' %
753 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39754
dprankecb4a2e242016-09-19 01:13:14755 command, extra_files = self.GetIsolateCommand(target, vals)
dpranked5b2b9432015-06-23 16:55:30756
dpranke48ccf8f2016-03-28 23:58:28757 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30758
dpranke751516a2015-10-03 01:11:34759 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
760 extra_files)
dpranked5b2b9432015-06-23 16:55:30761
dpranke751516a2015-10-03 01:11:34762 return 0
763
764 def RunGNIsolate(self, vals):
dprankecb4a2e242016-09-19 01:13:14765 target = self.args.target[0]
766 isolate_map = self.ReadIsolateMap()
767 err, labels = self.MapTargetsToLabels(isolate_map, [target])
768 if err:
769 raise MBErr(err)
770 label = labels[0]
dpranke751516a2015-10-03 01:11:34771
772 build_dir = self.args.path[0]
dprankecb4a2e242016-09-19 01:13:14773 command, extra_files = self.GetIsolateCommand(target, vals)
dpranke751516a2015-10-03 01:11:34774
dprankeeca4a782016-04-14 01:42:38775 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20776 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34777 if ret:
dpranke030d7a6d2016-03-26 17:23:50778 if out:
779 self.Print(out)
dpranke751516a2015-10-03 01:11:34780 return ret
781
782 runtime_deps = out.splitlines()
783
784 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
785 extra_files)
786
787 ret, _, _ = self.Run([
788 self.executable,
789 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
790 'check',
791 '-i',
792 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
793 '-s',
794 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
795 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30796
dprankefe4602312015-04-08 16:20:35797 return ret
798
dpranke751516a2015-10-03 01:11:34799 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
800 extra_files):
801 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
802 self.WriteFile(isolate_path,
803 pprint.pformat({
804 'variables': {
805 'command': command,
806 'files': sorted(runtime_deps + extra_files),
807 }
808 }) + '\n')
809
810 self.WriteJSON(
811 {
812 'args': [
813 '--isolated',
814 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
815 '--isolate',
816 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
817 ],
818 'dir': self.chromium_src_dir,
819 'version': 1,
820 },
821 isolate_path + 'd.gen.json',
822 )
823
dprankecb4a2e242016-09-19 01:13:14824 def MapTargetsToLabels(self, isolate_map, targets):
825 labels = []
826 err = ''
827
dprankecb4a2e242016-09-19 01:13:14828 for target in targets:
829 if target == 'all':
830 labels.append(target)
831 elif target.startswith('//'):
832 labels.append(target)
833 else:
834 if target in isolate_map:
thakis024d6f32017-05-16 23:21:42835 if isolate_map[target]['type'] == 'unknown':
dprankecb4a2e242016-09-19 01:13:14836 err += ('test target "%s" type is unknown\n' % target)
837 else:
thakis024d6f32017-05-16 23:21:42838 labels.append(isolate_map[target]['label'])
dprankecb4a2e242016-09-19 01:13:14839 else:
840 err += ('target "%s" not found in '
841 '//testing/buildbot/gn_isolate_map.pyl\n' % target)
842
843 return err, labels
844
dprankeeca4a782016-04-14 01:42:38845 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51846 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20847 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51848 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20849 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51850 else:
dpranke40da0202016-02-13 05:05:20851 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38852
dpranke40da0202016-02-13 05:05:20853 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranke10118bf2016-09-16 23:16:08854 return [gn_path, subcommand, path] + list(args)
dpranke9aba8b212016-09-16 22:52:52855
dprankecb4a2e242016-09-19 01:13:14856
dprankeeca4a782016-04-14 01:42:38857 def GNArgs(self, vals):
dpranke73ed0d62016-04-25 19:18:34858 if vals['cros_passthrough']:
859 if not 'GN_ARGS' in os.environ:
860 raise MBErr('MB is expecting GN_ARGS to be in the environment')
861 gn_args = os.environ['GN_ARGS']
dpranke40260182016-04-27 04:45:16862 if not re.search('target_os.*=.*"chromeos"', gn_args):
dpranke39f3be02016-04-27 04:07:30863 raise MBErr('GN_ARGS is missing target_os = "chromeos": (GN_ARGS=%s)' %
dpranke73ed0d62016-04-25 19:18:34864 gn_args)
865 else:
866 gn_args = vals['gn_args']
867
dpranked0c138b2016-04-13 18:28:47868 if self.args.goma_dir:
869 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38870
agrieve41d21a72016-04-14 18:02:26871 android_version_code = self.args.android_version_code
872 if android_version_code:
873 gn_args += ' android_default_version_code="%s"' % android_version_code
874
875 android_version_name = self.args.android_version_name
876 if android_version_name:
877 gn_args += ' android_default_version_name="%s"' % android_version_name
878
dprankeeca4a782016-04-14 01:42:38879 # Canonicalize the arg string into a sorted, newline-separated list
880 # of key-value pairs, and de-dup the keys if need be so that only
881 # the last instance of each arg is listed.
882 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
883
dpranke9dd5e252016-04-14 04:23:09884 args_file = vals.get('args_file', None)
885 if args_file:
886 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38887 return gn_args
dprankefe4602312015-04-08 16:20:35888
dprankecb4a2e242016-09-19 01:13:14889 def GetIsolateCommand(self, target, vals):
kylechar50abf5a2016-11-29 16:03:07890 isolate_map = self.ReadIsolateMap()
891
Scott Graham3be4b4162017-09-12 00:41:41892 is_android = 'target_os="android"' in vals['gn_args']
893 is_fuchsia = 'target_os="fuchsia"' in vals['gn_args']
jbudoricke8428732016-02-02 02:17:06894
kylechar39705682017-01-19 14:37:23895 # This should be true if tests with type='windowed_test_launcher' are
896 # expected to run using xvfb. For example, Linux Desktop, X11 CrOS and
msisovaea52732017-03-21 08:08:08897 # Ozone CrOS builds. Note that one Ozone build can be used to run differen
898 # backends. Currently, tests are executed for the headless and X11 backends
899 # and both can run under Xvfb.
900 # TODO(tonikitoo,msisov,fwang): Find a way to run tests for the Wayland
901 # backend.
Scott Graham3be4b4162017-09-12 00:41:41902 use_xvfb = self.platform == 'linux2' and not is_android and not is_fuchsia
dpranked8113582015-06-05 20:08:25903
904 asan = 'is_asan=true' in vals['gn_args']
905 msan = 'is_msan=true' in vals['gn_args']
906 tsan = 'is_tsan=true' in vals['gn_args']
pcc46233c22017-06-20 22:11:41907 cfi_diag = 'use_cfi_diag=true' in vals['gn_args']
dpranked8113582015-06-05 20:08:25908
dprankecb4a2e242016-09-19 01:13:14909 test_type = isolate_map[target]['type']
dprankefe0d35e2016-02-05 02:43:59910
dprankecb4a2e242016-09-19 01:13:14911 executable = isolate_map[target].get('executable', target)
dprankefe0d35e2016-02-05 02:43:59912 executable_suffix = '.exe' if self.platform == 'win32' else ''
913
dprankea55584f12015-07-22 00:52:47914 cmdline = []
Andrii Shyshkalovc158e0102018-01-10 05:52:00915 extra_files = [
916 '../../.vpython',
917 '../../testing/test_env.py',
918 ]
dpranked8113582015-06-05 20:08:25919
dprankecb4a2e242016-09-19 01:13:14920 if test_type == 'nontest':
921 self.WriteFailureAndRaise('We should not be isolating %s.' % target,
922 output_path=None)
923
Scott Graham3be4b4162017-09-12 00:41:41924 if is_android and test_type != "script":
bpastenee428ea92017-02-17 02:20:32925 cmdline = [
John Budorickfb97a852017-12-20 20:10:19926 '../../testing/test_env.py',
hzl9b15df52017-03-23 23:43:04927 '../../build/android/test_wrapper/logdog_wrapper.py',
928 '--target', target,
hzl9ae14452017-04-04 23:38:02929 '--logdog-bin-cmd', '../../bin/logdog_butler',
hzlfc66094f2017-05-18 00:50:48930 '--store-tombstones']
Scott Graham3be4b4162017-09-12 00:41:41931 elif is_fuchsia and test_type != 'script':
John Budorickfb97a852017-12-20 20:10:19932 cmdline = [
933 '../../testing/test_env.py',
934 os.path.join('bin', 'run_%s' % target),
935 ]
kylechar39705682017-01-19 14:37:23936 elif use_xvfb and test_type == 'windowed_test_launcher':
Andrii Shyshkalovc158e0102018-01-10 05:52:00937 extra_files.append('../../testing/xvfb.py')
dprankea55584f12015-07-22 00:52:47938 cmdline = [
dprankefe0d35e2016-02-05 02:43:59939 '../../testing/xvfb.py',
dprankefe0d35e2016-02-05 02:43:59940 './' + str(executable) + executable_suffix,
941 '--brave-new-test-launcher',
942 '--test-launcher-bot-mode',
943 '--asan=%d' % asan,
944 '--msan=%d' % msan,
945 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41946 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47947 ]
948 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
dprankea55584f12015-07-22 00:52:47949 cmdline = [
950 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:59951 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:25952 '--brave-new-test-launcher',
953 '--test-launcher-bot-mode',
954 '--asan=%d' % asan,
955 '--msan=%d' % msan,
956 '--tsan=%d' % tsan,
pcc46233c22017-06-20 22:11:41957 '--cfi-diag=%d' % cfi_diag,
dprankea55584f12015-07-22 00:52:47958 ]
dpranke6abd8652015-08-28 03:21:11959 elif test_type == 'script':
dpranke6abd8652015-08-28 03:21:11960 cmdline = [
961 '../../testing/test_env.py',
dprankecb4a2e242016-09-19 01:13:14962 '../../' + self.ToSrcRelPath(isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:59963 ]
dprankea55584f12015-07-22 00:52:47964 elif test_type in ('raw'):
dprankea55584f12015-07-22 00:52:47965 cmdline = [
966 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:59967 ]
dpranked8113582015-06-05 20:08:25968
dprankea55584f12015-07-22 00:52:47969 else:
970 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
971 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:25972
dprankecb4a2e242016-09-19 01:13:14973 cmdline += isolate_map[target].get('args', [])
dprankefe0d35e2016-02-05 02:43:59974
dpranked8113582015-06-05 20:08:25975 return cmdline, extra_files
976
dpranke74559b52015-06-10 21:20:39977 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:33978 return self.PathJoin(self.chromium_src_dir,
979 self.ToSrcRelPath(build_path),
980 *comps)
dpranked8113582015-06-05 20:08:25981
dprankeee5b51f62015-04-09 00:03:22982 def ToSrcRelPath(self, path):
983 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:50984 if path.startswith('//'):
985 return path[2:].replace('/', self.sep)
986 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:35987
Dirk Pranke0fd41bcd2015-06-19 00:05:50988 def RunGNAnalyze(self, vals):
dprankecb4a2e242016-09-19 01:13:14989 # Analyze runs before 'gn gen' now, so we need to run gn gen
Dirk Pranke0fd41bcd2015-06-19 00:05:50990 # in order to ensure that we have a build directory.
Dirk Prankea3727f92017-07-17 17:30:33991 ret = self.RunGNGen(vals, compute_grit_inputs_for_analyze=True)
Dirk Pranke0fd41bcd2015-06-19 00:05:50992 if ret:
993 return ret
994
dprankecb4a2e242016-09-19 01:13:14995 build_path = self.args.path[0]
996 input_path = self.args.input_path[0]
997 gn_input_path = input_path + '.gn'
998 output_path = self.args.output_path[0]
999 gn_output_path = output_path + '.gn'
1000
dpranke7837fc362015-11-19 03:54:161001 inp = self.ReadInputJSON(['files', 'test_targets',
1002 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321003 if self.args.verbose:
1004 self.Print()
1005 self.Print('analyze input:')
1006 self.PrintJSON(inp)
1007 self.Print()
1008
dpranke76734662015-04-16 02:17:501009
dpranke7c5f614d2015-07-22 23:43:391010 # This shouldn't normally happen, but could due to unusual race conditions,
1011 # like a try job that gets scheduled before a patch lands but runs after
1012 # the patch has landed.
1013 if not inp['files']:
1014 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161015 self.WriteJSON({
1016 'status': 'No dependency',
1017 'compile_targets': [],
1018 'test_targets': [],
1019 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391020 return 0
1021
dprankecb4a2e242016-09-19 01:13:141022 gn_inp = {}
dprankeb7b183f2017-04-24 23:50:161023 gn_inp['files'] = ['//' + f for f in inp['files'] if not f.startswith('//')]
dprankef61de2f2015-05-14 04:09:561024
dprankecb4a2e242016-09-19 01:13:141025 isolate_map = self.ReadIsolateMap()
1026 err, gn_inp['additional_compile_targets'] = self.MapTargetsToLabels(
1027 isolate_map, inp['additional_compile_targets'])
dprankecb4a2e242016-09-19 01:13:141028 if err:
1029 raise MBErr(err)
1030
1031 err, gn_inp['test_targets'] = self.MapTargetsToLabels(
1032 isolate_map, inp['test_targets'])
dprankecb4a2e242016-09-19 01:13:141033 if err:
1034 raise MBErr(err)
1035 labels_to_targets = {}
1036 for i, label in enumerate(gn_inp['test_targets']):
1037 labels_to_targets[label] = inp['test_targets'][i]
1038
dprankef61de2f2015-05-14 04:09:561039 try:
dprankecb4a2e242016-09-19 01:13:141040 self.WriteJSON(gn_inp, gn_input_path)
1041 cmd = self.GNCmd('analyze', build_path, gn_input_path, gn_output_path)
1042 ret, _, _ = self.Run(cmd, force_verbose=True)
1043 if ret:
1044 return ret
dpranke067d0142015-05-14 22:52:451045
dprankecb4a2e242016-09-19 01:13:141046 gn_outp_str = self.ReadFile(gn_output_path)
1047 try:
1048 gn_outp = json.loads(gn_outp_str)
1049 except Exception as e:
1050 self.Print("Failed to parse the JSON string GN returned: %s\n%s"
1051 % (repr(gn_outp_str), str(e)))
1052 raise
1053
1054 outp = {}
1055 if 'status' in gn_outp:
1056 outp['status'] = gn_outp['status']
1057 if 'error' in gn_outp:
1058 outp['error'] = gn_outp['error']
1059 if 'invalid_targets' in gn_outp:
1060 outp['invalid_targets'] = gn_outp['invalid_targets']
1061 if 'compile_targets' in gn_outp:
Dirk Pranke45165072017-11-08 04:57:491062 all_input_compile_targets = sorted(
1063 set(inp['test_targets'] + inp['additional_compile_targets']))
1064
1065 # If we're building 'all', we can throw away the rest of the targets
1066 # since they're redundant.
dpranke385a3102016-09-20 22:04:081067 if 'all' in gn_outp['compile_targets']:
1068 outp['compile_targets'] = ['all']
1069 else:
Dirk Pranke45165072017-11-08 04:57:491070 outp['compile_targets'] = gn_outp['compile_targets']
1071
1072 # crbug.com/736215: When GN returns targets back, for targets in
1073 # the default toolchain, GN will have generated a phony ninja
1074 # target matching the label, and so we can safely (and easily)
1075 # transform any GN label into the matching ninja target. For
1076 # targets in other toolchains, though, GN doesn't generate the
1077 # phony targets, and we don't know how to turn the labels into
1078 # compile targets. In this case, we also conservatively give up
1079 # and build everything. Probably the right thing to do here is
1080 # to have GN return the compile targets directly.
1081 if any("(" in target for target in outp['compile_targets']):
1082 self.Print('WARNING: targets with non-default toolchains were '
1083 'found, building everything instead.')
1084 outp['compile_targets'] = all_input_compile_targets
1085 else:
dpranke385a3102016-09-20 22:04:081086 outp['compile_targets'] = [
Dirk Pranke45165072017-11-08 04:57:491087 label.replace('//', '') for label in outp['compile_targets']]
1088
1089 # Windows has a maximum command line length of 8k; even Linux
1090 # maxes out at 128k; if analyze returns a *really long* list of
1091 # targets, we just give up and conservatively build everything instead.
1092 # Probably the right thing here is for ninja to support response
1093 # files as input on the command line
1094 # (see https://github.com/ninja-build/ninja/issues/1355).
1095 if len(' '.join(outp['compile_targets'])) > 7*1024:
1096 self.Print('WARNING: Too many compile targets were affected.')
1097 self.Print('WARNING: Building everything instead to avoid '
1098 'command-line length issues.')
1099 outp['compile_targets'] = all_input_compile_targets
1100
1101
dprankecb4a2e242016-09-19 01:13:141102 if 'test_targets' in gn_outp:
1103 outp['test_targets'] = [
1104 labels_to_targets[label] for label in gn_outp['test_targets']]
1105
1106 if self.args.verbose:
1107 self.Print()
1108 self.Print('analyze output:')
1109 self.PrintJSON(outp)
1110 self.Print()
1111
1112 self.WriteJSON(outp, output_path)
1113
dprankef61de2f2015-05-14 04:09:561114 finally:
dprankecb4a2e242016-09-19 01:13:141115 if self.Exists(gn_input_path):
1116 self.RemoveFile(gn_input_path)
1117 if self.Exists(gn_output_path):
1118 self.RemoveFile(gn_output_path)
dprankefe4602312015-04-08 16:20:351119
1120 return 0
1121
dpranked8113582015-06-05 20:08:251122 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351123 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321124 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351125 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321126 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351127
1128 try:
1129 inp = json.loads(self.ReadFile(path))
1130 except Exception as e:
1131 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321132 (path, e), output_path)
dpranked8113582015-06-05 20:08:251133
1134 for k in required_keys:
1135 if not k in inp:
1136 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1137 output_path)
dprankefe4602312015-04-08 16:20:351138
1139 return inp
1140
dpranked5b2b9432015-06-23 16:55:301141 def WriteFailureAndRaise(self, msg, output_path):
1142 if output_path:
dprankee0547cd2015-09-15 01:27:401143 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351144 raise MBErr(msg)
1145
dprankee0547cd2015-09-15 01:27:401146 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321147 try:
dprankee0547cd2015-09-15 01:27:401148 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1149 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321150 except Exception as e:
1151 raise MBErr('Error %s writing to the output path "%s"' %
1152 (e, path))
dprankefe4602312015-04-08 16:20:351153
aneeshmde50f472016-04-01 01:13:101154 def CheckCompile(self, master, builder):
1155 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1156 url = urllib2.quote(url_template.format(master=master, builder=builder),
1157 safe=':/()?=')
1158 try:
1159 builds = json.loads(self.Fetch(url))
1160 except Exception as e:
1161 return str(e)
1162 successes = sorted(
1163 [int(x) for x in builds.keys() if "text" in builds[x] and
1164 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1165 reverse=True)
1166 if not successes:
1167 return "no successful builds"
1168 build = builds[str(successes[0])]
1169 step_names = set([step["name"] for step in build["steps"]])
1170 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1171 if compile_indicators & step_names:
1172 return "compiles"
1173 return "does not compile"
1174
dpranke3cec199c2015-09-22 23:29:021175 def PrintCmd(self, cmd, env):
1176 if self.platform == 'win32':
1177 env_prefix = 'set '
1178 env_quoter = QuoteForSet
1179 shell_quoter = QuoteForCmd
1180 else:
1181 env_prefix = ''
1182 env_quoter = pipes.quote
1183 shell_quoter = pipes.quote
1184
1185 def print_env(var):
1186 if env and var in env:
1187 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1188
dprankeec079262016-06-07 02:21:201189 print_env('LLVM_FORCE_HEAD_REVISION')
dpranke3cec199c2015-09-22 23:29:021190
dpranke8c2cfd32015-09-17 20:12:331191 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351192 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021193 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351194
dprankecda00332015-04-11 04:18:321195 def PrintJSON(self, obj):
1196 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1197
dpranke751516a2015-10-03 01:11:341198 def Build(self, target):
1199 build_dir = self.ToSrcRelPath(self.args.path[0])
1200 ninja_cmd = ['ninja', '-C', build_dir]
1201 if self.args.jobs:
1202 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1203 ninja_cmd.append(target)
1204 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1205 return ret
1206
1207 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351208 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401209 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021210 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351211 if self.args.dryrun:
1212 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401213
dpranke751516a2015-10-03 01:11:341214 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401215 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341216 if ret:
1217 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351218 if out:
dprankeee5b51f62015-04-09 00:03:221219 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351220 if err:
dprankeee5b51f62015-04-09 00:03:221221 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351222 return ret, out, err
1223
dpranke751516a2015-10-03 01:11:341224 def Call(self, cmd, env=None, buffer_output=True):
1225 if buffer_output:
1226 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1227 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1228 env=env)
1229 out, err = p.communicate()
1230 else:
1231 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1232 env=env)
1233 p.wait()
1234 out = err = ''
dprankefe4602312015-04-08 16:20:351235 return p.returncode, out, err
1236
1237 def ExpandUser(self, path):
1238 # This function largely exists so it can be overridden for testing.
1239 return os.path.expanduser(path)
1240
1241 def Exists(self, path):
1242 # This function largely exists so it can be overridden for testing.
1243 return os.path.exists(path)
1244
dpranke867bcf4a2016-03-14 22:28:321245 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501246 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321247 f = urllib2.urlopen(url)
1248 contents = f.read()
1249 f.close()
1250 return contents
1251
dprankec3441d12015-06-23 23:01:351252 def MaybeMakeDirectory(self, path):
1253 try:
1254 os.makedirs(path)
1255 except OSError, e:
1256 if e.errno != errno.EEXIST:
1257 raise
1258
dpranke8c2cfd32015-09-17 20:12:331259 def PathJoin(self, *comps):
1260 # This function largely exists so it can be overriden for testing.
1261 return os.path.join(*comps)
1262
dpranke030d7a6d2016-03-26 17:23:501263 def Print(self, *args, **kwargs):
1264 # This function largely exists so it can be overridden for testing.
1265 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101266 if kwargs.get('stream', sys.stdout) == sys.stdout:
1267 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501268
dprankefe4602312015-04-08 16:20:351269 def ReadFile(self, path):
1270 # This function largely exists so it can be overriden for testing.
1271 with open(path) as fp:
1272 return fp.read()
1273
dpranke030d7a6d2016-03-26 17:23:501274 def RelPath(self, path, start='.'):
1275 # This function largely exists so it can be overriden for testing.
1276 return os.path.relpath(path, start)
1277
dprankef61de2f2015-05-14 04:09:561278 def RemoveFile(self, path):
1279 # This function largely exists so it can be overriden for testing.
1280 os.remove(path)
1281
dprankec161aa92015-09-14 20:21:131282 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331283 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131284 # In other places in chromium, we often have to retry this command
1285 # because we're worried about other processes still holding on to
1286 # file handles, but when MB is invoked, it will be early enough in the
1287 # build that their should be no other processes to interfere. We
1288 # can change this if need be.
1289 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1290 else:
1291 shutil.rmtree(abs_path, ignore_errors=True)
1292
dprankef61de2f2015-05-14 04:09:561293 def TempFile(self, mode='w'):
1294 # This function largely exists so it can be overriden for testing.
1295 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1296
dprankee0547cd2015-09-15 01:27:401297 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351298 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401299 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301300 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351301 with open(path, 'w') as fp:
1302 return fp.write(contents)
1303
dprankef61de2f2015-05-14 04:09:561304
dprankefe4602312015-04-08 16:20:351305class MBErr(Exception):
1306 pass
1307
1308
dpranke3cec199c2015-09-22 23:29:021309# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1310# details of this next section, which handles escaping command lines
1311# so that they can be copied and pasted into a cmd window.
1312UNSAFE_FOR_SET = set('^<>&|')
1313UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1314ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1315
1316
1317def QuoteForSet(arg):
1318 if any(a in UNSAFE_FOR_SET for a in arg):
1319 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1320 return arg
1321
1322
1323def QuoteForCmd(arg):
1324 # First, escape the arg so that CommandLineToArgvW will parse it properly.
dpranke3cec199c2015-09-22 23:29:021325 if arg == '' or ' ' in arg or '"' in arg:
1326 quote_re = re.compile(r'(\\*)"')
1327 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1328
1329 # Then check to see if the arg contains any metacharacters other than
1330 # double quotes; if it does, quote everything (including the double
1331 # quotes) for safety.
1332 if any(a in UNSAFE_FOR_CMD for a in arg):
1333 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1334 return arg
1335
1336
dprankefe4602312015-04-08 16:20:351337if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591338 sys.exit(main(sys.argv[1:]))