blob: b2d0851d3b2820f136f5215ffab8823827206c1c [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
6"""MB - the Meta-Build wrapper around GYP and GN
7
8MB is a wrapper script for GYP and GN that can be used to generate build files
9for 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
dpranked8113582015-06-05 20:08:2520import pprint
dpranke3cec199c2015-09-22 23:29:0221import re
dprankefe4602312015-04-08 16:20:3522import shutil
23import sys
24import subprocess
dprankef61de2f2015-05-14 04:09:5625import tempfile
dprankebbe6d4672016-04-19 06:56:5726import traceback
dpranke867bcf4a2016-03-14 22:28:3227import urllib2
28
29from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3530
dprankeeca4a782016-04-14 01:42:3831CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
32 os.path.abspath(__file__))))
33sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path
34
35import gn_helpers
36
37
dprankefe4602312015-04-08 16:20:3538def main(args):
dprankeee5b51f62015-04-09 00:03:2239 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5940 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3541
42
43class MetaBuildWrapper(object):
44 def __init__(self):
dprankeeca4a782016-04-14 01:42:3845 self.chromium_src_dir = CHROMIUM_SRC_DIR
46 self.default_config = os.path.join(self.chromium_src_dir, 'tools', 'mb',
47 'mb_config.pyl')
dpranke8c2cfd32015-09-17 20:12:3348 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5149 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3350 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3551 self.args = argparse.Namespace()
52 self.configs = {}
53 self.masters = {}
54 self.mixins = {}
dprankefe4602312015-04-08 16:20:3555
dpranke255085e2016-03-16 05:23:5956 def Main(self, args):
57 self.ParseArgs(args)
58 try:
59 ret = self.args.func()
60 if ret:
61 self.DumpInputFiles()
62 return ret
63 except KeyboardInterrupt:
64 self.Print('interrupted, exiting', stream=sys.stderr)
65 return 130
dprankebbe6d4672016-04-19 06:56:5766 except Exception:
dpranke255085e2016-03-16 05:23:5967 self.DumpInputFiles()
dprankebbe6d4672016-04-19 06:56:5768 s = traceback.format_exc()
69 for l in s.splitlines():
70 self.Print(l)
dpranke255085e2016-03-16 05:23:5971 return 1
72
dprankefe4602312015-04-08 16:20:3573 def ParseArgs(self, argv):
74 def AddCommonOptions(subp):
75 subp.add_argument('-b', '--builder',
76 help='builder name to look up config from')
77 subp.add_argument('-m', '--master',
78 help='master name to look up config from')
79 subp.add_argument('-c', '--config',
80 help='configuration to analyze')
81 subp.add_argument('-f', '--config-file', metavar='PATH',
82 default=self.default_config,
83 help='path to config file '
84 '(default is //tools/mb/mb_config.pyl)')
dpranked0c138b2016-04-13 18:28:4785 subp.add_argument('-g', '--goma-dir',
86 help='path to goma directory')
agrieve41d21a72016-04-14 18:02:2687 subp.add_argument('--android-version-code',
88 help='Sets GN arg android_default_version_code and '
89 'GYP_DEFINE app_manifest_version_code')
90 subp.add_argument('--android-version-name',
91 help='Sets GN arg android_default_version_name and '
92 'GYP_DEFINE app_manifest_version_name')
dprankefe4602312015-04-08 16:20:3593 subp.add_argument('-n', '--dryrun', action='store_true',
94 help='Do a dry run (i.e., do nothing, just print '
95 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:4096 subp.add_argument('-v', '--verbose', action='store_true',
97 help='verbose logging')
dprankefe4602312015-04-08 16:20:3598
99 parser = argparse.ArgumentParser(prog='mb')
100 subps = parser.add_subparsers()
101
102 subp = subps.add_parser('analyze',
103 help='analyze whether changes to a set of files '
104 'will cause a set of binaries to be rebuilt.')
105 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:25106 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35107 help='path build was generated into.')
108 subp.add_argument('input_path', nargs=1,
109 help='path to a file containing the input arguments '
110 'as a JSON object.')
111 subp.add_argument('output_path', nargs=1,
112 help='path to a file containing the output arguments '
113 'as a JSON object.')
114 subp.set_defaults(func=self.CmdAnalyze)
115
116 subp = subps.add_parser('gen',
117 help='generate a new set of build files')
118 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39119 subp.add_argument('--swarming-targets-file',
120 help='save runtime dependencies for targets listed '
121 'in file.')
dpranked8113582015-06-05 20:08:25122 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35123 help='path to generate build into')
124 subp.set_defaults(func=self.CmdGen)
125
dpranke751516a2015-10-03 01:11:34126 subp = subps.add_parser('isolate',
127 help='generate the .isolate files for a given'
128 'binary')
129 AddCommonOptions(subp)
130 subp.add_argument('path', nargs=1,
131 help='path build was generated into')
132 subp.add_argument('target', nargs=1,
133 help='ninja target to generate the isolate for')
134 subp.set_defaults(func=self.CmdIsolate)
135
dprankefe4602312015-04-08 16:20:35136 subp = subps.add_parser('lookup',
137 help='look up the command for a given config or '
138 'builder')
139 AddCommonOptions(subp)
140 subp.set_defaults(func=self.CmdLookup)
141
dpranke030d7a6d2016-03-26 17:23:50142 subp = subps.add_parser(
143 'run',
144 help='build and run the isolated version of a '
145 'binary',
146 formatter_class=argparse.RawDescriptionHelpFormatter)
147 subp.description = (
148 'Build, isolate, and run the given binary with the command line\n'
149 'listed in the isolate. You may pass extra arguments after the\n'
150 'target; use "--" if the extra arguments need to include switches.\n'
151 '\n'
152 'Examples:\n'
153 '\n'
154 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
155 ' //out/Default content_browsertests\n'
156 '\n'
157 ' % tools/mb/mb.py run out/Default content_browsertests\n'
158 '\n'
159 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
160 ' --test-launcher-retry-limit=0'
161 '\n'
162 )
163
dpranke751516a2015-10-03 01:11:34164 AddCommonOptions(subp)
165 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
166 help='Number of jobs to pass to ninja')
167 subp.add_argument('--no-build', dest='build', default=True,
168 action='store_false',
169 help='Do not build, just isolate and run')
170 subp.add_argument('path', nargs=1,
dpranke030d7a6d2016-03-26 17:23:50171 help=('path to generate build into (or use).'
172 ' This can be either a regular path or a '
173 'GN-style source-relative path like '
174 '//out/Default.'))
dpranke751516a2015-10-03 01:11:34175 subp.add_argument('target', nargs=1,
176 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50177 subp.add_argument('extra_args', nargs='*',
178 help=('extra args to pass to the isolate to run. Use '
179 '"--" as the first arg if you need to pass '
180 'switches'))
dpranke751516a2015-10-03 01:11:34181 subp.set_defaults(func=self.CmdRun)
182
dprankefe4602312015-04-08 16:20:35183 subp = subps.add_parser('validate',
184 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17185 subp.add_argument('-f', '--config-file', metavar='PATH',
186 default=self.default_config,
187 help='path to config file '
188 '(default is //tools/mb/mb_config.pyl)')
dprankefe4602312015-04-08 16:20:35189 subp.set_defaults(func=self.CmdValidate)
190
dpranke867bcf4a2016-03-14 22:28:32191 subp = subps.add_parser('audit',
192 help='Audit the config file to track progress')
193 subp.add_argument('-f', '--config-file', metavar='PATH',
194 default=self.default_config,
195 help='path to config file '
196 '(default is //tools/mb/mb_config.pyl)')
197 subp.add_argument('-i', '--internal', action='store_true',
198 help='check internal masters also')
199 subp.add_argument('-m', '--master', action='append',
200 help='master to audit (default is all non-internal '
201 'masters in file)')
202 subp.add_argument('-u', '--url-template', action='store',
203 default='https://build.chromium.org/p/'
204 '{master}/json/builders',
205 help='URL scheme for JSON APIs to buildbot '
206 '(default: %(default)s) ')
aneeshmde50f472016-04-01 01:13:10207 subp.add_argument('-c', '--check-compile', action='store_true',
208 help='check whether tbd and master-only bots actually'
209 ' do compiles')
dpranke867bcf4a2016-03-14 22:28:32210 subp.set_defaults(func=self.CmdAudit)
211
dprankefe4602312015-04-08 16:20:35212 subp = subps.add_parser('help',
213 help='Get help on a subcommand.')
214 subp.add_argument(nargs='?', action='store', dest='subcommand',
215 help='The command to get help for.')
216 subp.set_defaults(func=self.CmdHelp)
217
218 self.args = parser.parse_args(argv)
219
dprankeb2be10a2016-02-22 17:11:00220 def DumpInputFiles(self):
221
dprankef7b7eb7a2016-03-28 22:42:59222 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00223 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59224 self.Print("\n# To recreate the file passed to %s:" % arg_name)
225 self.Print("%% cat > %s <<EOF)" % path)
dprankeb2be10a2016-02-22 17:11:00226 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59227 self.Print(contents)
228 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00229
dprankef7b7eb7a2016-03-28 22:42:59230 if getattr(self.args, 'input_path', None):
231 DumpContentsOfFilePassedTo(
232 'argv[0] (input_path)', self.args.input_path[0])
233 if getattr(self.args, 'swarming_targets_file', None):
234 DumpContentsOfFilePassedTo(
235 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00236
dprankefe4602312015-04-08 16:20:35237 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34238 vals = self.Lookup()
dprankee88057c2016-04-12 22:40:08239 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35240 if vals['type'] == 'gn':
241 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35242 else:
dpranke751516a2015-10-03 01:11:34243 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35244
245 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34246 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13247 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35248 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50249 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35250 else:
dpranke751516a2015-10-03 01:11:34251 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35252
253 def CmdHelp(self):
254 if self.args.subcommand:
255 self.ParseArgs([self.args.subcommand, '--help'])
256 else:
257 self.ParseArgs(['--help'])
258
dpranke751516a2015-10-03 01:11:34259 def CmdIsolate(self):
260 vals = self.GetConfig()
261 if not vals:
262 return 1
263
264 if vals['type'] == 'gn':
265 return self.RunGNIsolate(vals)
266 else:
267 return self.Build('%s_run' % self.args.target[0])
268
269 def CmdLookup(self):
270 vals = self.Lookup()
271 if vals['type'] == 'gn':
dprankeeca4a782016-04-14 01:42:38272 cmd = self.GNCmd('gen', '_path_')
273 gn_args = self.GNArgs(vals)
274 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
dpranke751516a2015-10-03 01:11:34275 env = None
276 else:
277 cmd, env = self.GYPCmd('_path_', vals)
278
279 self.PrintCmd(cmd, env)
280 return 0
281
282 def CmdRun(self):
283 vals = self.GetConfig()
284 if not vals:
285 return 1
286
287 build_dir = self.args.path[0]
288 target = self.args.target[0]
289
290 if vals['type'] == 'gn':
291 if self.args.build:
292 ret = self.Build(target)
293 if ret:
294 return ret
295 ret = self.RunGNIsolate(vals)
296 if ret:
297 return ret
298 else:
299 ret = self.Build('%s_run' % target)
300 if ret:
301 return ret
302
dpranke030d7a6d2016-03-26 17:23:50303 cmd = [
dpranke751516a2015-10-03 01:11:34304 self.executable,
305 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
306 'run',
307 '-s',
dpranke030d7a6d2016-03-26 17:23:50308 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
309 ]
310 if self.args.extra_args:
311 cmd += ['--'] + self.args.extra_args
312
313 ret, _, _ = self.Run(cmd, force_verbose=False, buffer_output=False)
dpranke751516a2015-10-03 01:11:34314
315 return ret
316
dpranke0cafc162016-03-19 00:41:10317 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35318 errs = []
319
320 # Read the file to make sure it parses.
321 self.ReadConfigFile()
322
dpranke3be00142016-03-17 22:46:04323 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35324 all_configs = {}
dprankefe4602312015-04-08 16:20:35325 for master in self.masters:
dpranke3be00142016-03-17 22:46:04326 for config in self.masters[master].values():
327 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35328
dpranke9dd5e252016-04-14 04:23:09329 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35330 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09331 if config.startswith('//'):
332 if not self.Exists(self.ToAbsPath(config)):
333 errs.append('Unknown args file "%s" referenced from "%s".' %
334 (config, loc))
335 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35336 errs.append('Unknown config "%s" referenced from "%s".' %
337 (config, loc))
338
339 # Check that every actual config is actually referenced.
340 for config in self.configs:
341 if not config in all_configs:
342 errs.append('Unused config "%s".' % config)
343
344 # Figure out the whole list of mixins, and check that every mixin
345 # listed by a config or another mixin actually exists.
346 referenced_mixins = set()
347 for config, mixins in self.configs.items():
348 for mixin in mixins:
349 if not mixin in self.mixins:
350 errs.append('Unknown mixin "%s" referenced by config "%s".' %
351 (mixin, config))
352 referenced_mixins.add(mixin)
353
354 for mixin in self.mixins:
355 for sub_mixin in self.mixins[mixin].get('mixins', []):
356 if not sub_mixin in self.mixins:
357 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
358 (sub_mixin, mixin))
359 referenced_mixins.add(sub_mixin)
360
361 # Check that every mixin defined is actually referenced somewhere.
362 for mixin in self.mixins:
363 if not mixin in referenced_mixins:
364 errs.append('Unreferenced mixin "%s".' % mixin)
365
dpranke255085e2016-03-16 05:23:59366 # If we're checking the Chromium config, check that the 'chromium' bots
367 # which build public artifacts do not include the chrome_with_codecs mixin.
368 if self.args.config_file == self.default_config:
369 if 'chromium' in self.masters:
370 for builder in self.masters['chromium']:
371 config = self.masters['chromium'][builder]
372 def RecurseMixins(current_mixin):
373 if current_mixin == 'chrome_with_codecs':
374 errs.append('Public artifact builder "%s" can not contain the '
375 '"chrome_with_codecs" mixin.' % builder)
376 return
377 if not 'mixins' in self.mixins[current_mixin]:
378 return
379 for mixin in self.mixins[current_mixin]['mixins']:
380 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41381
dpranke255085e2016-03-16 05:23:59382 for mixin in self.configs[config]:
383 RecurseMixins(mixin)
384 else:
385 errs.append('Missing "chromium" master. Please update this '
386 'proprietary codecs check with the name of the master '
387 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41388
dprankefe4602312015-04-08 16:20:35389 if errs:
dpranke4323c80632015-08-10 22:53:54390 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17391 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35392
dpranke0cafc162016-03-19 00:41:10393 if print_ok:
394 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35395 return 0
396
dpranke867bcf4a2016-03-14 22:28:32397 def CmdAudit(self):
398 """Track the progress of the GYP->GN migration on the bots."""
399
dpranke0cafc162016-03-19 00:41:10400 # First, make sure the config file is okay, but don't print anything
401 # if it is (it will throw an error if it isn't).
402 self.CmdValidate(print_ok=False)
403
dpranke867bcf4a2016-03-14 22:28:32404 stats = OrderedDict()
405 STAT_MASTER_ONLY = 'Master only'
406 STAT_CONFIG_ONLY = 'Config only'
407 STAT_TBD = 'Still TBD'
408 STAT_GYP = 'Still GYP'
409 STAT_DONE = 'Done (on GN)'
410 stats[STAT_MASTER_ONLY] = 0
411 stats[STAT_CONFIG_ONLY] = 0
412 stats[STAT_TBD] = 0
413 stats[STAT_GYP] = 0
414 stats[STAT_DONE] = 0
415
aneeshmde50f472016-04-01 01:13:10416 def PrintBuilders(heading, builders, notes):
dpranke867bcf4a2016-03-14 22:28:32417 stats.setdefault(heading, 0)
418 stats[heading] += len(builders)
419 if builders:
420 self.Print(' %s:' % heading)
421 for builder in sorted(builders):
aneeshmde50f472016-04-01 01:13:10422 self.Print(' %s%s' % (builder, notes[builder]))
dpranke867bcf4a2016-03-14 22:28:32423
424 self.ReadConfigFile()
425
426 masters = self.args.master or self.masters
427 for master in sorted(masters):
428 url = self.args.url_template.replace('{master}', master)
429
430 self.Print('Auditing %s' % master)
431
432 MASTERS_TO_SKIP = (
433 'client.skia',
434 'client.v8.fyi',
435 'tryserver.v8',
436 )
437 if master in MASTERS_TO_SKIP:
438 # Skip these bots because converting them is the responsibility of
439 # those teams and out of scope for the Chromium migration to GN.
440 self.Print(' Skipped (out of scope)')
441 self.Print('')
442 continue
443
dprankeeafba352016-03-15 19:34:53444 INTERNAL_MASTERS = ('official.desktop', 'official.desktop.continuous')
dpranke867bcf4a2016-03-14 22:28:32445 if master in INTERNAL_MASTERS and not self.args.internal:
446 # Skip these because the servers aren't accessible by default ...
447 self.Print(' Skipped (internal)')
448 self.Print('')
449 continue
450
451 try:
452 # Fetch the /builders contents from the buildbot master. The
453 # keys of the dict are the builder names themselves.
454 json_contents = self.Fetch(url)
455 d = json.loads(json_contents)
456 except Exception as e:
457 self.Print(str(e))
458 return 1
459
460 config_builders = set(self.masters[master])
461 master_builders = set(d.keys())
462 both = master_builders & config_builders
463 master_only = master_builders - config_builders
464 config_only = config_builders - master_builders
465 tbd = set()
466 gyp = set()
467 done = set()
aneeshmde50f472016-04-01 01:13:10468 notes = {builder: '' for builder in config_builders | master_builders}
dpranke867bcf4a2016-03-14 22:28:32469
470 for builder in both:
471 config = self.masters[master][builder]
472 if config == 'tbd':
473 tbd.add(builder)
dprankebbe6d4672016-04-19 06:56:57474 elif config.startswith('//'):
475 done.add(builder)
dpranke867bcf4a2016-03-14 22:28:32476 else:
477 # TODO(dpranke): Check if MB is actually running?
478 vals = self.FlattenConfig(config)
479 if vals['type'] == 'gyp':
480 gyp.add(builder)
481 else:
482 done.add(builder)
483
aneeshmde50f472016-04-01 01:13:10484 if self.args.check_compile and (tbd or master_only):
485 either = tbd | master_only
486 for builder in either:
487 notes[builder] = ' (' + self.CheckCompile(master, builder) +')'
488
dpranke867bcf4a2016-03-14 22:28:32489 if master_only or config_only or tbd or gyp:
aneeshmde50f472016-04-01 01:13:10490 PrintBuilders(STAT_MASTER_ONLY, master_only, notes)
491 PrintBuilders(STAT_CONFIG_ONLY, config_only, notes)
492 PrintBuilders(STAT_TBD, tbd, notes)
493 PrintBuilders(STAT_GYP, gyp, notes)
dpranke867bcf4a2016-03-14 22:28:32494 else:
dprankebbe6d4672016-04-19 06:56:57495 self.Print(' All GN!')
dpranke867bcf4a2016-03-14 22:28:32496
497 stats[STAT_DONE] += len(done)
498
499 self.Print('')
500
501 fmt = '{:<27} {:>4}'
502 self.Print(fmt.format('Totals', str(sum(int(v) for v in stats.values()))))
503 self.Print(fmt.format('-' * 27, '----'))
504 for stat, count in stats.items():
505 self.Print(fmt.format(stat, str(count)))
506
507 return 0
508
dprankefe4602312015-04-08 16:20:35509 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34510 build_dir = self.args.path[0]
511
512 vals = {}
513 if self.args.builder or self.args.master or self.args.config:
514 vals = self.Lookup()
515 if vals['type'] == 'gn':
516 # Re-run gn gen in order to ensure the config is consistent with the
517 # build dir.
518 self.RunGNGen(vals)
519 return vals
520
521 # TODO: We can only get the config for GN build dirs, not GYP build dirs.
522 # GN stores the args that were used in args.gn in the build dir,
523 # but GYP doesn't store them anywhere. We should consider modifying
524 # gyp_chromium to record the arguments it runs with in a similar
525 # manner.
526
527 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
528 if not self.Exists(mb_type_path):
529 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
530 if not self.Exists(gn_args_path):
531 self.Print('Must either specify a path to an existing GN build dir '
532 'or pass in a -m/-b pair or a -c flag to specify the '
533 'configuration')
534 return {}
535 else:
536 mb_type = 'gn'
537 else:
538 mb_type = self.ReadFile(mb_type_path).strip()
539
540 if mb_type == 'gn':
541 vals = self.GNValsFromDir(build_dir)
542 else:
543 vals = {}
544 vals['type'] = mb_type
545
546 return vals
547
548 def GNValsFromDir(self, build_dir):
549 args_contents = self.ReadFile(
550 self.PathJoin(self.ToAbsPath(build_dir), 'args.gn'))
551 gn_args = []
552 for l in args_contents.splitlines():
553 fields = l.split(' ')
554 name = fields[0]
555 val = ' '.join(fields[2:])
556 gn_args.append('%s=%s' % (name, val))
557
558 return {
559 'gn_args': ' '.join(gn_args),
560 'type': 'gn',
561 }
562
563 def Lookup(self):
dprankee0f486f2015-11-19 23:42:00564 vals = self.ReadBotConfig()
565 if not vals:
566 self.ReadConfigFile()
567 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09568 if config.startswith('//'):
569 if not self.Exists(self.ToAbsPath(config)):
570 raise MBErr('args file "%s" not found' % config)
571 vals = {
572 'type': 'gn',
573 'args_file': config,
574 'gn_args': '',
575 }
576 else:
577 if not config in self.configs:
578 raise MBErr('Config "%s" not found in %s' %
579 (config, self.args.config_file))
580 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34581
582 # Do some basic sanity checking on the config so that we
583 # don't have to do this in every caller.
584 assert 'type' in vals, 'No meta-build type specified in the config'
585 assert vals['type'] in ('gn', 'gyp'), (
586 'Unknown meta-build type "%s"' % vals['gn_args'])
587
588 return vals
dprankefe4602312015-04-08 16:20:35589
dprankee0f486f2015-11-19 23:42:00590 def ReadBotConfig(self):
591 if not self.args.master or not self.args.builder:
592 return {}
593 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
594 self.args.master, self.args.builder + '.json')
595 if not self.Exists(path):
596 return {}
597
598 contents = json.loads(self.ReadFile(path))
599 gyp_vals = contents.get('GYP_DEFINES', {})
600 if isinstance(gyp_vals, dict):
601 gyp_defines = ' '.join('%s=%s' % (k, v) for k, v in gyp_vals.items())
602 else:
603 gyp_defines = ' '.join(gyp_vals)
604 gn_args = ' '.join(contents.get('gn_args', []))
605
606 return {
607 'type': contents.get('mb_type', ''),
608 'gn_args': gn_args,
609 'gyp_defines': gyp_defines,
dprankef75a3de52015-12-14 22:17:52610 'gyp_crosscompile': False,
dprankee0f486f2015-11-19 23:42:00611 }
612
dprankefe4602312015-04-08 16:20:35613 def ReadConfigFile(self):
614 if not self.Exists(self.args.config_file):
615 raise MBErr('config file not found at %s' % self.args.config_file)
616
617 try:
618 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
619 except SyntaxError as e:
620 raise MBErr('Failed to parse config file "%s": %s' %
621 (self.args.config_file, e))
622
dprankefe4602312015-04-08 16:20:35623 self.configs = contents['configs']
624 self.masters = contents['masters']
625 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35626
627 def ConfigFromArgs(self):
628 if self.args.config:
629 if self.args.master or self.args.builder:
630 raise MBErr('Can not specific both -c/--config and -m/--master or '
631 '-b/--builder')
632
633 return self.args.config
634
635 if not self.args.master or not self.args.builder:
636 raise MBErr('Must specify either -c/--config or '
637 '(-m/--master and -b/--builder)')
638
639 if not self.args.master in self.masters:
640 raise MBErr('Master name "%s" not found in "%s"' %
641 (self.args.master, self.args.config_file))
642
643 if not self.args.builder in self.masters[self.args.master]:
644 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
645 (self.args.builder, self.args.master, self.args.config_file))
646
647 return self.masters[self.args.master][self.args.builder]
648
649 def FlattenConfig(self, config):
650 mixins = self.configs[config]
651 vals = {
652 'type': None,
653 'gn_args': [],
dprankec161aa92015-09-14 20:21:13654 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59655 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35656 }
657
658 visited = []
659 self.FlattenMixins(mixins, vals, visited)
660 return vals
661
662 def FlattenMixins(self, mixins, vals, visited):
663 for m in mixins:
664 if m not in self.mixins:
665 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22666
667 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35668
669 visited.append(m)
670
671 mixin_vals = self.mixins[m]
672 if 'type' in mixin_vals:
673 vals['type'] = mixin_vals['type']
674 if 'gn_args' in mixin_vals:
675 if vals['gn_args']:
676 vals['gn_args'] += ' ' + mixin_vals['gn_args']
677 else:
678 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59679 if 'gyp_crosscompile' in mixin_vals:
680 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35681 if 'gyp_defines' in mixin_vals:
682 if vals['gyp_defines']:
683 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
684 else:
685 vals['gyp_defines'] = mixin_vals['gyp_defines']
686 if 'mixins' in mixin_vals:
687 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
688 return vals
689
dprankec161aa92015-09-14 20:21:13690 def ClobberIfNeeded(self, vals):
691 path = self.args.path[0]
692 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33693 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13694 needs_clobber = False
695 new_mb_type = vals['type']
696 if self.Exists(build_dir):
697 if self.Exists(mb_type_path):
698 old_mb_type = self.ReadFile(mb_type_path)
699 if old_mb_type != new_mb_type:
700 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
701 (old_mb_type, new_mb_type, path))
702 needs_clobber = True
703 else:
704 # There is no 'mb_type' file in the build directory, so this probably
705 # means that the prior build(s) were not done through mb, and we
706 # have no idea if this was a GYP build or a GN build. Clobber it
707 # to be safe.
708 self.Print("%s/mb_type missing, clobbering to be safe" % path)
709 needs_clobber = True
710
dpranke3cec199c2015-09-22 23:29:02711 if self.args.dryrun:
712 return
713
dprankec161aa92015-09-14 20:21:13714 if needs_clobber:
715 self.RemoveDirectory(build_dir)
716
717 self.MaybeMakeDirectory(build_dir)
718 self.WriteFile(mb_type_path, new_mb_type)
719
Dirk Pranke0fd41bcd2015-06-19 00:05:50720 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34721 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50722
dprankeeca4a782016-04-14 01:42:38723 cmd = self.GNCmd('gen', build_dir, '--check')
724 gn_args = self.GNArgs(vals)
725
726 # Since GN hasn't run yet, the build directory may not even exist.
727 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
728
729 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
dpranke4ff8b9f2016-04-15 03:07:54730 self.WriteFile(gn_args_path, gn_args, force_verbose=True)
dpranke74559b52015-06-10 21:20:39731
732 swarming_targets = []
dpranke751516a2015-10-03 01:11:34733 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39734 # We need GN to generate the list of runtime dependencies for
735 # the compile targets listed (one per line) in the file so
736 # we can run them via swarming. We use ninja_to_gn.pyl to convert
737 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00738 path = self.args.swarming_targets_file
739 if not self.Exists(path):
740 self.WriteFailureAndRaise('"%s" does not exist' % path,
741 output_path=None)
742 contents = self.ReadFile(path)
743 swarming_targets = set(contents.splitlines())
dpranke8c2cfd32015-09-17 20:12:33744 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47745 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39746 gn_labels = []
dprankeb2be10a2016-02-22 17:11:00747 err = ''
dpranke74559b52015-06-10 21:20:39748 for target in swarming_targets:
jbudorickdcff99982016-02-03 19:38:07749 target_name = self.GNTargetName(target)
750 if not target_name in gn_isolate_map:
dprankeb2be10a2016-02-22 17:11:00751 err += ('test target "%s" not found\n' % target_name)
752 elif gn_isolate_map[target_name]['type'] == 'unknown':
753 err += ('test target "%s" type is unknown\n' % target_name)
754 else:
755 gn_labels.append(gn_isolate_map[target_name]['label'])
756
757 if err:
758 raise MBErr('Error: Failed to match swarming targets to %s:\n%s' %
759 ('//testing/buildbot/gn_isolate_map.pyl', err))
dpranke74559b52015-06-10 21:20:39760
dpranke751516a2015-10-03 01:11:34761 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dpranke74559b52015-06-10 21:20:39762 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
763 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
764
dprankefe4602312015-04-08 16:20:35765 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40766 if ret:
767 # If `gn gen` failed, we should exit early rather than trying to
768 # generate isolates. Run() will have already logged any error output.
769 self.Print('GN gen failed: %d' % ret)
770 return ret
dpranke74559b52015-06-10 21:20:39771
772 for target in swarming_targets:
jbudorick91c8a6012016-01-29 23:20:02773 if target.endswith('_apk'):
774 # "_apk" targets may be either android_apk or executable. The former
775 # will result in runtime_deps associated with the stamp file, while the
776 # latter will result in runtime_deps associated with the executable.
jbudorickdcff99982016-02-03 19:38:07777 target_name = self.GNTargetName(target)
778 label = gn_isolate_map[target_name]['label']
jbudorick91c8a6012016-01-29 23:20:02779 runtime_deps_targets = [
dpranke48ccf8f2016-03-28 23:58:28780 target_name + '.runtime_deps',
781 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
jbudorick91c8a6012016-01-29 23:20:02782 elif gn_isolate_map[target]['type'] == 'gpu_browser_test':
dpranke48ccf8f2016-03-28 23:58:28783 if self.platform == 'win32':
784 runtime_deps_targets = ['browser_tests.exe.runtime_deps']
785 else:
786 runtime_deps_targets = ['browser_tests.runtime_deps']
dprankefe0d35e2016-02-05 02:43:59787 elif (gn_isolate_map[target]['type'] == 'script' or
788 gn_isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11789 # For script targets, the build target is usually a group,
790 # for which gn generates the runtime_deps next to the stamp file
791 # for the label, which lives under the obj/ directory.
792 label = gn_isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28793 runtime_deps_targets = [
794 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
795 elif self.platform == 'win32':
796 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52797 else:
dpranke48ccf8f2016-03-28 23:58:28798 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02799
dpranke48ccf8f2016-03-28 23:58:28800 for r in runtime_deps_targets:
801 runtime_deps_path = self.ToAbsPath(build_dir, r)
802 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02803 break
804 else:
dpranke48ccf8f2016-03-28 23:58:28805 raise MBErr('did not generate any of %s' %
806 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39807
dprankea55584f12015-07-22 00:52:47808 command, extra_files = self.GetIsolateCommand(target, vals,
809 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30810
dpranke48ccf8f2016-03-28 23:58:28811 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30812
dpranke751516a2015-10-03 01:11:34813 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
814 extra_files)
dpranked5b2b9432015-06-23 16:55:30815
dpranke751516a2015-10-03 01:11:34816 return 0
817
818 def RunGNIsolate(self, vals):
819 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
820 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
821
822 build_dir = self.args.path[0]
823 target = self.args.target[0]
jbudorickdcff99982016-02-03 19:38:07824 target_name = self.GNTargetName(target)
dpranke751516a2015-10-03 01:11:34825 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
826
jbudorickdcff99982016-02-03 19:38:07827 label = gn_isolate_map[target_name]['label']
dprankeeca4a782016-04-14 01:42:38828 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20829 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34830 if ret:
dpranke030d7a6d2016-03-26 17:23:50831 if out:
832 self.Print(out)
dpranke751516a2015-10-03 01:11:34833 return ret
834
835 runtime_deps = out.splitlines()
836
837 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
838 extra_files)
839
840 ret, _, _ = self.Run([
841 self.executable,
842 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
843 'check',
844 '-i',
845 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
846 '-s',
847 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
848 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30849
dprankefe4602312015-04-08 16:20:35850 return ret
851
dpranke751516a2015-10-03 01:11:34852 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
853 extra_files):
854 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
855 self.WriteFile(isolate_path,
856 pprint.pformat({
857 'variables': {
858 'command': command,
859 'files': sorted(runtime_deps + extra_files),
860 }
861 }) + '\n')
862
863 self.WriteJSON(
864 {
865 'args': [
866 '--isolated',
867 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
868 '--isolate',
869 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
870 ],
871 'dir': self.chromium_src_dir,
872 'version': 1,
873 },
874 isolate_path + 'd.gen.json',
875 )
876
dprankeeca4a782016-04-14 01:42:38877 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51878 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20879 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51880 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20881 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51882 else:
dpranke40da0202016-02-13 05:05:20883 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38884
dpranke40da0202016-02-13 05:05:20885 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranked1fba482015-04-14 20:54:51886
dprankeeca4a782016-04-14 01:42:38887 return [gn_path, subcommand, path] + list(args)
888
889 def GNArgs(self, vals):
890 gn_args = vals['gn_args']
dpranked0c138b2016-04-13 18:28:47891 if self.args.goma_dir:
892 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38893
agrieve41d21a72016-04-14 18:02:26894 android_version_code = self.args.android_version_code
895 if android_version_code:
896 gn_args += ' android_default_version_code="%s"' % android_version_code
897
898 android_version_name = self.args.android_version_name
899 if android_version_name:
900 gn_args += ' android_default_version_name="%s"' % android_version_name
901
dprankeeca4a782016-04-14 01:42:38902 # Canonicalize the arg string into a sorted, newline-separated list
903 # of key-value pairs, and de-dup the keys if need be so that only
904 # the last instance of each arg is listed.
905 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
906
dpranke9dd5e252016-04-14 04:23:09907 args_file = vals.get('args_file', None)
908 if args_file:
909 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38910 return gn_args
dprankefe4602312015-04-08 16:20:35911
Dirk Pranke0fd41bcd2015-06-19 00:05:50912 def RunGYPGen(self, vals):
913 path = self.args.path[0]
914
dpranke8c2cfd32015-09-17 20:12:33915 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41916 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59917 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35918 return ret
919
920 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33921 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32922 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16923 inp = self.ReadInputJSON(['files', 'test_targets',
924 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32925 self.Print()
926 self.Print('analyze input:')
927 self.PrintJSON(inp)
928 self.Print()
929
dpranke38f4acb62015-09-29 23:50:41930 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33931 cmd.extend(['-f', 'analyzer',
932 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35933 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02934 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32935 if not ret and self.args.verbose:
936 outp = json.loads(self.ReadFile(self.args.output_path[0]))
937 self.Print()
938 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39939 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32940 self.Print()
941
dprankefe4602312015-04-08 16:20:35942 return ret
943
dprankea55584f12015-07-22 00:52:47944 def GetIsolateCommand(self, target, vals, gn_isolate_map):
jbudoricke8428732016-02-02 02:17:06945 android = 'target_os="android"' in vals['gn_args']
946
dpranked8113582015-06-05 20:08:25947 # This needs to mirror the settings in //build/config/ui.gni:
948 # use_x11 = is_linux && !use_ozone.
949 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33950 use_x11 = (self.platform == 'linux2' and
jbudoricke8428732016-02-02 02:17:06951 not android and
dpranked8113582015-06-05 20:08:25952 not 'use_ozone=true' in vals['gn_args'])
953
954 asan = 'is_asan=true' in vals['gn_args']
955 msan = 'is_msan=true' in vals['gn_args']
956 tsan = 'is_tsan=true' in vals['gn_args']
957
jbudorickdcff99982016-02-03 19:38:07958 target_name = self.GNTargetName(target)
959 test_type = gn_isolate_map[target_name]['type']
dprankefe0d35e2016-02-05 02:43:59960
961 executable = gn_isolate_map[target_name].get('executable', target_name)
962 executable_suffix = '.exe' if self.platform == 'win32' else ''
963
dprankea55584f12015-07-22 00:52:47964 cmdline = []
965 extra_files = []
dpranked8113582015-06-05 20:08:25966
jbudoricke8428732016-02-02 02:17:06967 if android:
968 # TODO(jbudorick): This won't work with instrumentation test targets.
969 # Revisit this logic when those are added to gn_isolate_map.pyl.
jbudorickdcff99982016-02-03 19:38:07970 cmdline = [self.PathJoin('bin', 'run_%s' % target_name)]
jbudoricke8428732016-02-02 02:17:06971 elif use_x11 and test_type == 'windowed_test_launcher':
dprankea55584f12015-07-22 00:52:47972 extra_files = [
973 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25974 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47975 '../../testing/xvfb.py',
976 ]
977 cmdline = [
dprankefe0d35e2016-02-05 02:43:59978 '../../testing/xvfb.py',
979 '.',
980 './' + str(executable) + executable_suffix,
981 '--brave-new-test-launcher',
982 '--test-launcher-bot-mode',
983 '--asan=%d' % asan,
984 '--msan=%d' % msan,
985 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47986 ]
987 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
988 extra_files = [
989 '../../testing/test_env.py'
990 ]
991 cmdline = [
992 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:59993 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:25994 '--brave-new-test-launcher',
995 '--test-launcher-bot-mode',
996 '--asan=%d' % asan,
997 '--msan=%d' % msan,
998 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47999 ]
dprankedbdd9d82015-08-12 21:18:181000 elif test_type == 'gpu_browser_test':
1001 extra_files = [
1002 '../../testing/test_env.py'
1003 ]
1004 gtest_filter = gn_isolate_map[target]['gtest_filter']
1005 cmdline = [
1006 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:111007 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:181008 '--test-launcher-bot-mode',
1009 '--enable-gpu',
1010 '--test-launcher-jobs=1',
1011 '--gtest_filter=%s' % gtest_filter,
1012 ]
dpranke6abd8652015-08-28 03:21:111013 elif test_type == 'script':
1014 extra_files = [
1015 '../../testing/test_env.py'
1016 ]
1017 cmdline = [
1018 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:391019 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:591020 ]
dprankea55584f12015-07-22 00:52:471021 elif test_type in ('raw'):
1022 extra_files = []
1023 cmdline = [
1024 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:591025 ]
dpranked8113582015-06-05 20:08:251026
dprankea55584f12015-07-22 00:52:471027 else:
1028 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
1029 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:251030
jbudorick8a0560422016-02-05 06:07:171031 cmdline += gn_isolate_map[target_name].get('args', [])
dprankefe0d35e2016-02-05 02:43:591032
dpranked8113582015-06-05 20:08:251033 return cmdline, extra_files
1034
dpranke74559b52015-06-10 21:20:391035 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:331036 return self.PathJoin(self.chromium_src_dir,
1037 self.ToSrcRelPath(build_path),
1038 *comps)
dpranked8113582015-06-05 20:08:251039
dprankeee5b51f62015-04-09 00:03:221040 def ToSrcRelPath(self, path):
1041 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501042 if path.startswith('//'):
1043 return path[2:].replace('/', self.sep)
1044 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351045
1046 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:221047 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:331048 output_dir, _, _ = rpath.rpartition(self.sep)
1049 return output_dir
dprankefe4602312015-04-08 16:20:351050
dpranke38f4acb62015-09-29 23:50:411051 def GYPCmd(self, output_dir, vals):
1052 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:021053 goma_dir = self.args.goma_dir
1054
1055 # GYP uses shlex.split() to split the gyp defines into separate arguments,
1056 # so we can support backslashes and and spaces in arguments by quoting
1057 # them, even on Windows, where this normally wouldn't work.
dpranked0c138b2016-04-13 18:28:471058 if goma_dir and ('\\' in goma_dir or ' ' in goma_dir):
dpranke3cec199c2015-09-22 23:29:021059 goma_dir = "'%s'" % goma_dir
dpranked0c138b2016-04-13 18:28:471060
1061 if goma_dir:
1062 gyp_defines += ' gomadir=%s' % goma_dir
dpranke3cec199c2015-09-22 23:29:021063
agrieve41d21a72016-04-14 18:02:261064 android_version_code = self.args.android_version_code
1065 if android_version_code:
1066 gyp_defines += ' app_manifest_version_code=%s' % android_version_code
1067
1068 android_version_name = self.args.android_version_name
1069 if android_version_name:
1070 gyp_defines += ' app_manifest_version_name=%s' % android_version_name
1071
dprankefe4602312015-04-08 16:20:351072 cmd = [
dpranke8c2cfd32015-09-17 20:12:331073 self.executable,
1074 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:351075 '-G',
1076 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:351077 ]
dpranke38f4acb62015-09-29 23:50:411078
1079 # Ensure that we have an environment that only contains
1080 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:021081 env = os.environ.copy()
dprankef75a3de52015-12-14 22:17:521082 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:411083 if 'GYP_CHROMIUM_NO_ACTION' in env:
1084 del env['GYP_CHROMIUM_NO_ACTION']
1085 if 'GYP_CROSSCOMPILE' in env:
1086 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:021087 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:411088 if vals['gyp_crosscompile']:
1089 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:021090 return cmd, env
dprankefe4602312015-04-08 16:20:351091
Dirk Pranke0fd41bcd2015-06-19 00:05:501092 def RunGNAnalyze(self, vals):
1093 # analyze runs before 'gn gen' now, so we need to run gn gen
1094 # in order to ensure that we have a build directory.
1095 ret = self.RunGNGen(vals)
1096 if ret:
1097 return ret
1098
dpranke7837fc362015-11-19 03:54:161099 inp = self.ReadInputJSON(['files', 'test_targets',
1100 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321101 if self.args.verbose:
1102 self.Print()
1103 self.Print('analyze input:')
1104 self.PrintJSON(inp)
1105 self.Print()
1106
dpranke7837fc362015-11-19 03:54:161107 # TODO(crbug.com/555273) - currently GN treats targets and
1108 # additional_compile_targets identically since we can't tell the
1109 # difference between a target that is a group in GN and one that isn't.
1110 # We should eventually fix this and treat the two types differently.
1111 targets = (set(inp['test_targets']) |
1112 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:021113
dprankecda00332015-04-11 04:18:321114 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351115
1116 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:021117 # what to do about it. Also, bail out early if 'all' was asked for,
1118 # since we can't deal with it yet.
1119 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
1120 'all' in targets):
dpranke7837fc362015-11-19 03:54:161121 self.WriteJSON({
1122 'status': 'Found dependency (all)',
1123 'compile_targets': sorted(targets),
1124 'test_targets': sorted(targets & set(inp['test_targets'])),
1125 }, output_path)
dpranke76734662015-04-16 02:17:501126 return 0
1127
dpranke7c5f614d2015-07-22 23:43:391128 # This shouldn't normally happen, but could due to unusual race conditions,
1129 # like a try job that gets scheduled before a patch lands but runs after
1130 # the patch has landed.
1131 if not inp['files']:
1132 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161133 self.WriteJSON({
1134 'status': 'No dependency',
1135 'compile_targets': [],
1136 'test_targets': [],
1137 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391138 return 0
1139
Dirk Pranke12ee2db2015-04-14 23:15:321140 ret = 0
dprankef61de2f2015-05-14 04:09:561141 response_file = self.TempFile()
1142 response_file.write('\n'.join(inp['files']) + '\n')
1143 response_file.close()
1144
dpranke5ab84a502015-11-13 17:35:021145 matching_targets = set()
dprankef61de2f2015-05-14 04:09:561146 try:
dprankeeca4a782016-04-14 01:42:381147 cmd = self.GNCmd('refs',
1148 self.args.path[0],
1149 '@%s' % response_file.name,
1150 '--all',
1151 '--as=output')
dprankee0547cd2015-09-15 01:27:401152 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:121153 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:321154 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1155 output_path)
dpranke8c2cfd32015-09-17 20:12:331156 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:561157 for output in out.splitlines():
1158 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:021159 if build_output in targets:
1160 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:451161
dprankeeca4a782016-04-14 01:42:381162 cmd = self.GNCmd('refs',
1163 self.args.path[0],
1164 '@%s' % response_file.name,
1165 '--all')
dprankee0547cd2015-09-15 01:27:401166 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:451167 if ret and not 'The input matches no targets' in out:
1168 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1169 output_path)
1170 for label in out.splitlines():
1171 build_target = label[2:]
newt309af8f2015-08-25 22:10:201172 # We want to accept 'chrome/android:chrome_public_apk' and
1173 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:451174 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:021175 for input_target in targets:
dpranke067d0142015-05-14 22:52:451176 if (input_target == build_target or
1177 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:021178 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:561179 finally:
1180 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:351181
dprankef61de2f2015-05-14 04:09:561182 if matching_targets:
dpranke7837fc362015-11-19 03:54:161183 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:021184 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:161185 'compile_targets': sorted(matching_targets),
1186 'test_targets': sorted(matching_targets &
1187 set(inp['test_targets'])),
1188 }, output_path)
dprankefe4602312015-04-08 16:20:351189 else:
dpranke7837fc362015-11-19 03:54:161190 self.WriteJSON({
1191 'status': 'No dependency',
1192 'compile_targets': [],
1193 'test_targets': [],
1194 }, output_path)
dprankecda00332015-04-11 04:18:321195
dprankee0547cd2015-09-15 01:27:401196 if self.args.verbose:
dprankecda00332015-04-11 04:18:321197 outp = json.loads(self.ReadFile(output_path))
1198 self.Print()
1199 self.Print('analyze output:')
1200 self.PrintJSON(outp)
1201 self.Print()
dprankefe4602312015-04-08 16:20:351202
1203 return 0
1204
dpranked8113582015-06-05 20:08:251205 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351206 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321207 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351208 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321209 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351210
1211 try:
1212 inp = json.loads(self.ReadFile(path))
1213 except Exception as e:
1214 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321215 (path, e), output_path)
dpranked8113582015-06-05 20:08:251216
1217 for k in required_keys:
1218 if not k in inp:
1219 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1220 output_path)
dprankefe4602312015-04-08 16:20:351221
1222 return inp
1223
dpranked5b2b9432015-06-23 16:55:301224 def WriteFailureAndRaise(self, msg, output_path):
1225 if output_path:
dprankee0547cd2015-09-15 01:27:401226 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351227 raise MBErr(msg)
1228
dprankee0547cd2015-09-15 01:27:401229 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321230 try:
dprankee0547cd2015-09-15 01:27:401231 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1232 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321233 except Exception as e:
1234 raise MBErr('Error %s writing to the output path "%s"' %
1235 (e, path))
dprankefe4602312015-04-08 16:20:351236
aneeshmde50f472016-04-01 01:13:101237 def CheckCompile(self, master, builder):
1238 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1239 url = urllib2.quote(url_template.format(master=master, builder=builder),
1240 safe=':/()?=')
1241 try:
1242 builds = json.loads(self.Fetch(url))
1243 except Exception as e:
1244 return str(e)
1245 successes = sorted(
1246 [int(x) for x in builds.keys() if "text" in builds[x] and
1247 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1248 reverse=True)
1249 if not successes:
1250 return "no successful builds"
1251 build = builds[str(successes[0])]
1252 step_names = set([step["name"] for step in build["steps"]])
1253 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1254 if compile_indicators & step_names:
1255 return "compiles"
1256 return "does not compile"
1257
dpranke3cec199c2015-09-22 23:29:021258 def PrintCmd(self, cmd, env):
1259 if self.platform == 'win32':
1260 env_prefix = 'set '
1261 env_quoter = QuoteForSet
1262 shell_quoter = QuoteForCmd
1263 else:
1264 env_prefix = ''
1265 env_quoter = pipes.quote
1266 shell_quoter = pipes.quote
1267
1268 def print_env(var):
1269 if env and var in env:
1270 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1271
1272 print_env('GYP_CROSSCOMPILE')
1273 print_env('GYP_DEFINES')
1274
dpranke8c2cfd32015-09-17 20:12:331275 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351276 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021277 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351278
dprankecda00332015-04-11 04:18:321279 def PrintJSON(self, obj):
1280 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1281
dpranke030d7a6d2016-03-26 17:23:501282 def GNTargetName(self, target):
1283 return target[:-len('_apk')] if target.endswith('_apk') else target
dprankefe4602312015-04-08 16:20:351284
dpranke751516a2015-10-03 01:11:341285 def Build(self, target):
1286 build_dir = self.ToSrcRelPath(self.args.path[0])
1287 ninja_cmd = ['ninja', '-C', build_dir]
1288 if self.args.jobs:
1289 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1290 ninja_cmd.append(target)
1291 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1292 return ret
1293
1294 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351295 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401296 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021297 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351298 if self.args.dryrun:
1299 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401300
dpranke751516a2015-10-03 01:11:341301 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401302 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341303 if ret:
1304 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351305 if out:
dprankeee5b51f62015-04-09 00:03:221306 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351307 if err:
dprankeee5b51f62015-04-09 00:03:221308 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351309 return ret, out, err
1310
dpranke751516a2015-10-03 01:11:341311 def Call(self, cmd, env=None, buffer_output=True):
1312 if buffer_output:
1313 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1314 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1315 env=env)
1316 out, err = p.communicate()
1317 else:
1318 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1319 env=env)
1320 p.wait()
1321 out = err = ''
dprankefe4602312015-04-08 16:20:351322 return p.returncode, out, err
1323
1324 def ExpandUser(self, path):
1325 # This function largely exists so it can be overridden for testing.
1326 return os.path.expanduser(path)
1327
1328 def Exists(self, path):
1329 # This function largely exists so it can be overridden for testing.
1330 return os.path.exists(path)
1331
dpranke867bcf4a2016-03-14 22:28:321332 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501333 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321334 f = urllib2.urlopen(url)
1335 contents = f.read()
1336 f.close()
1337 return contents
1338
dprankec3441d12015-06-23 23:01:351339 def MaybeMakeDirectory(self, path):
1340 try:
1341 os.makedirs(path)
1342 except OSError, e:
1343 if e.errno != errno.EEXIST:
1344 raise
1345
dpranke8c2cfd32015-09-17 20:12:331346 def PathJoin(self, *comps):
1347 # This function largely exists so it can be overriden for testing.
1348 return os.path.join(*comps)
1349
dpranke030d7a6d2016-03-26 17:23:501350 def Print(self, *args, **kwargs):
1351 # This function largely exists so it can be overridden for testing.
1352 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101353 if kwargs.get('stream', sys.stdout) == sys.stdout:
1354 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501355
dprankefe4602312015-04-08 16:20:351356 def ReadFile(self, path):
1357 # This function largely exists so it can be overriden for testing.
1358 with open(path) as fp:
1359 return fp.read()
1360
dpranke030d7a6d2016-03-26 17:23:501361 def RelPath(self, path, start='.'):
1362 # This function largely exists so it can be overriden for testing.
1363 return os.path.relpath(path, start)
1364
dprankef61de2f2015-05-14 04:09:561365 def RemoveFile(self, path):
1366 # This function largely exists so it can be overriden for testing.
1367 os.remove(path)
1368
dprankec161aa92015-09-14 20:21:131369 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331370 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131371 # In other places in chromium, we often have to retry this command
1372 # because we're worried about other processes still holding on to
1373 # file handles, but when MB is invoked, it will be early enough in the
1374 # build that their should be no other processes to interfere. We
1375 # can change this if need be.
1376 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1377 else:
1378 shutil.rmtree(abs_path, ignore_errors=True)
1379
dprankef61de2f2015-05-14 04:09:561380 def TempFile(self, mode='w'):
1381 # This function largely exists so it can be overriden for testing.
1382 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1383
dprankee0547cd2015-09-15 01:27:401384 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351385 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401386 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301387 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351388 with open(path, 'w') as fp:
1389 return fp.write(contents)
1390
dprankef61de2f2015-05-14 04:09:561391
dprankefe4602312015-04-08 16:20:351392class MBErr(Exception):
1393 pass
1394
1395
dpranke3cec199c2015-09-22 23:29:021396# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1397# details of this next section, which handles escaping command lines
1398# so that they can be copied and pasted into a cmd window.
1399UNSAFE_FOR_SET = set('^<>&|')
1400UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1401ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1402
1403
1404def QuoteForSet(arg):
1405 if any(a in UNSAFE_FOR_SET for a in arg):
1406 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1407 return arg
1408
1409
1410def QuoteForCmd(arg):
1411 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1412 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1413 if arg == '' or ' ' in arg or '"' in arg:
1414 quote_re = re.compile(r'(\\*)"')
1415 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1416
1417 # Then check to see if the arg contains any metacharacters other than
1418 # double quotes; if it does, quote everything (including the double
1419 # quotes) for safety.
1420 if any(a in UNSAFE_FOR_CMD for a in arg):
1421 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1422 return arg
1423
1424
dprankefe4602312015-04-08 16:20:351425if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591426 sys.exit(main(sys.argv[1:]))