blob: ae7de3f28c0747922dc84326a2431c559e3cd42e [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
dpranke867bcf4a2016-03-14 22:28:3226import urllib2
27
28from collections import OrderedDict
dprankefe4602312015-04-08 16:20:3529
dprankeeca4a782016-04-14 01:42:3830CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname(
31 os.path.abspath(__file__))))
32sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path
33
34import gn_helpers
35
36
dprankefe4602312015-04-08 16:20:3537def main(args):
dprankeee5b51f62015-04-09 00:03:2238 mbw = MetaBuildWrapper()
dpranke255085e2016-03-16 05:23:5939 return mbw.Main(args)
dprankefe4602312015-04-08 16:20:3540
41
42class MetaBuildWrapper(object):
43 def __init__(self):
dprankeeca4a782016-04-14 01:42:3844 self.chromium_src_dir = CHROMIUM_SRC_DIR
45 self.default_config = os.path.join(self.chromium_src_dir, 'tools', 'mb',
46 'mb_config.pyl')
dpranke8c2cfd32015-09-17 20:12:3347 self.executable = sys.executable
dpranked1fba482015-04-14 20:54:5148 self.platform = sys.platform
dpranke8c2cfd32015-09-17 20:12:3349 self.sep = os.sep
dprankefe4602312015-04-08 16:20:3550 self.args = argparse.Namespace()
51 self.configs = {}
52 self.masters = {}
53 self.mixins = {}
dprankefe4602312015-04-08 16:20:3554
dpranke255085e2016-03-16 05:23:5955 def Main(self, args):
56 self.ParseArgs(args)
57 try:
58 ret = self.args.func()
59 if ret:
60 self.DumpInputFiles()
61 return ret
62 except KeyboardInterrupt:
63 self.Print('interrupted, exiting', stream=sys.stderr)
64 return 130
65 except Exception as e:
66 self.DumpInputFiles()
67 self.Print(str(e))
68 return 1
69
dprankefe4602312015-04-08 16:20:3570 def ParseArgs(self, argv):
71 def AddCommonOptions(subp):
72 subp.add_argument('-b', '--builder',
73 help='builder name to look up config from')
74 subp.add_argument('-m', '--master',
75 help='master name to look up config from')
76 subp.add_argument('-c', '--config',
77 help='configuration to analyze')
78 subp.add_argument('-f', '--config-file', metavar='PATH',
79 default=self.default_config,
80 help='path to config file '
81 '(default is //tools/mb/mb_config.pyl)')
dpranked0c138b2016-04-13 18:28:4782 subp.add_argument('-g', '--goma-dir',
83 help='path to goma directory')
dprankefe4602312015-04-08 16:20:3584 subp.add_argument('-n', '--dryrun', action='store_true',
85 help='Do a dry run (i.e., do nothing, just print '
86 'the commands that will run)')
dprankee0547cd2015-09-15 01:27:4087 subp.add_argument('-v', '--verbose', action='store_true',
88 help='verbose logging')
dprankefe4602312015-04-08 16:20:3589
90 parser = argparse.ArgumentParser(prog='mb')
91 subps = parser.add_subparsers()
92
93 subp = subps.add_parser('analyze',
94 help='analyze whether changes to a set of files '
95 'will cause a set of binaries to be rebuilt.')
96 AddCommonOptions(subp)
dpranked8113582015-06-05 20:08:2597 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:3598 help='path build was generated into.')
99 subp.add_argument('input_path', nargs=1,
100 help='path to a file containing the input arguments '
101 'as a JSON object.')
102 subp.add_argument('output_path', nargs=1,
103 help='path to a file containing the output arguments '
104 'as a JSON object.')
105 subp.set_defaults(func=self.CmdAnalyze)
106
107 subp = subps.add_parser('gen',
108 help='generate a new set of build files')
109 AddCommonOptions(subp)
dpranke74559b52015-06-10 21:20:39110 subp.add_argument('--swarming-targets-file',
111 help='save runtime dependencies for targets listed '
112 'in file.')
dpranked8113582015-06-05 20:08:25113 subp.add_argument('path', nargs=1,
dprankefe4602312015-04-08 16:20:35114 help='path to generate build into')
115 subp.set_defaults(func=self.CmdGen)
116
dpranke751516a2015-10-03 01:11:34117 subp = subps.add_parser('isolate',
118 help='generate the .isolate files for a given'
119 'binary')
120 AddCommonOptions(subp)
121 subp.add_argument('path', nargs=1,
122 help='path build was generated into')
123 subp.add_argument('target', nargs=1,
124 help='ninja target to generate the isolate for')
125 subp.set_defaults(func=self.CmdIsolate)
126
dprankefe4602312015-04-08 16:20:35127 subp = subps.add_parser('lookup',
128 help='look up the command for a given config or '
129 'builder')
130 AddCommonOptions(subp)
131 subp.set_defaults(func=self.CmdLookup)
132
dpranke030d7a6d2016-03-26 17:23:50133 subp = subps.add_parser(
134 'run',
135 help='build and run the isolated version of a '
136 'binary',
137 formatter_class=argparse.RawDescriptionHelpFormatter)
138 subp.description = (
139 'Build, isolate, and run the given binary with the command line\n'
140 'listed in the isolate. You may pass extra arguments after the\n'
141 'target; use "--" if the extra arguments need to include switches.\n'
142 '\n'
143 'Examples:\n'
144 '\n'
145 ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n'
146 ' //out/Default content_browsertests\n'
147 '\n'
148 ' % tools/mb/mb.py run out/Default content_browsertests\n'
149 '\n'
150 ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n'
151 ' --test-launcher-retry-limit=0'
152 '\n'
153 )
154
dpranke751516a2015-10-03 01:11:34155 AddCommonOptions(subp)
156 subp.add_argument('-j', '--jobs', dest='jobs', type=int,
157 help='Number of jobs to pass to ninja')
158 subp.add_argument('--no-build', dest='build', default=True,
159 action='store_false',
160 help='Do not build, just isolate and run')
161 subp.add_argument('path', nargs=1,
dpranke030d7a6d2016-03-26 17:23:50162 help=('path to generate build into (or use).'
163 ' This can be either a regular path or a '
164 'GN-style source-relative path like '
165 '//out/Default.'))
dpranke751516a2015-10-03 01:11:34166 subp.add_argument('target', nargs=1,
167 help='ninja target to build and run')
dpranke030d7a6d2016-03-26 17:23:50168 subp.add_argument('extra_args', nargs='*',
169 help=('extra args to pass to the isolate to run. Use '
170 '"--" as the first arg if you need to pass '
171 'switches'))
dpranke751516a2015-10-03 01:11:34172 subp.set_defaults(func=self.CmdRun)
173
dprankefe4602312015-04-08 16:20:35174 subp = subps.add_parser('validate',
175 help='validate the config file')
dprankea5a77ca2015-07-16 23:24:17176 subp.add_argument('-f', '--config-file', metavar='PATH',
177 default=self.default_config,
178 help='path to config file '
179 '(default is //tools/mb/mb_config.pyl)')
dprankefe4602312015-04-08 16:20:35180 subp.set_defaults(func=self.CmdValidate)
181
dpranke867bcf4a2016-03-14 22:28:32182 subp = subps.add_parser('audit',
183 help='Audit the config file to track progress')
184 subp.add_argument('-f', '--config-file', metavar='PATH',
185 default=self.default_config,
186 help='path to config file '
187 '(default is //tools/mb/mb_config.pyl)')
188 subp.add_argument('-i', '--internal', action='store_true',
189 help='check internal masters also')
190 subp.add_argument('-m', '--master', action='append',
191 help='master to audit (default is all non-internal '
192 'masters in file)')
193 subp.add_argument('-u', '--url-template', action='store',
194 default='https://build.chromium.org/p/'
195 '{master}/json/builders',
196 help='URL scheme for JSON APIs to buildbot '
197 '(default: %(default)s) ')
aneeshmde50f472016-04-01 01:13:10198 subp.add_argument('-c', '--check-compile', action='store_true',
199 help='check whether tbd and master-only bots actually'
200 ' do compiles')
dpranke867bcf4a2016-03-14 22:28:32201 subp.set_defaults(func=self.CmdAudit)
202
dprankefe4602312015-04-08 16:20:35203 subp = subps.add_parser('help',
204 help='Get help on a subcommand.')
205 subp.add_argument(nargs='?', action='store', dest='subcommand',
206 help='The command to get help for.')
207 subp.set_defaults(func=self.CmdHelp)
208
209 self.args = parser.parse_args(argv)
210
dprankeb2be10a2016-02-22 17:11:00211 def DumpInputFiles(self):
212
dprankef7b7eb7a2016-03-28 22:42:59213 def DumpContentsOfFilePassedTo(arg_name, path):
dprankeb2be10a2016-02-22 17:11:00214 if path and self.Exists(path):
dprankef7b7eb7a2016-03-28 22:42:59215 self.Print("\n# To recreate the file passed to %s:" % arg_name)
216 self.Print("%% cat > %s <<EOF)" % path)
dprankeb2be10a2016-02-22 17:11:00217 contents = self.ReadFile(path)
dprankef7b7eb7a2016-03-28 22:42:59218 self.Print(contents)
219 self.Print("EOF\n%\n")
dprankeb2be10a2016-02-22 17:11:00220
dprankef7b7eb7a2016-03-28 22:42:59221 if getattr(self.args, 'input_path', None):
222 DumpContentsOfFilePassedTo(
223 'argv[0] (input_path)', self.args.input_path[0])
224 if getattr(self.args, 'swarming_targets_file', None):
225 DumpContentsOfFilePassedTo(
226 '--swarming-targets-file', self.args.swarming_targets_file)
dprankeb2be10a2016-02-22 17:11:00227
dprankefe4602312015-04-08 16:20:35228 def CmdAnalyze(self):
dpranke751516a2015-10-03 01:11:34229 vals = self.Lookup()
dprankee88057c2016-04-12 22:40:08230 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35231 if vals['type'] == 'gn':
232 return self.RunGNAnalyze(vals)
dprankefe4602312015-04-08 16:20:35233 else:
dpranke751516a2015-10-03 01:11:34234 return self.RunGYPAnalyze(vals)
dprankefe4602312015-04-08 16:20:35235
236 def CmdGen(self):
dpranke751516a2015-10-03 01:11:34237 vals = self.Lookup()
dprankec161aa92015-09-14 20:21:13238 self.ClobberIfNeeded(vals)
dprankefe4602312015-04-08 16:20:35239 if vals['type'] == 'gn':
Dirk Pranke0fd41bcd2015-06-19 00:05:50240 return self.RunGNGen(vals)
dprankefe4602312015-04-08 16:20:35241 else:
dpranke751516a2015-10-03 01:11:34242 return self.RunGYPGen(vals)
dprankefe4602312015-04-08 16:20:35243
244 def CmdHelp(self):
245 if self.args.subcommand:
246 self.ParseArgs([self.args.subcommand, '--help'])
247 else:
248 self.ParseArgs(['--help'])
249
dpranke751516a2015-10-03 01:11:34250 def CmdIsolate(self):
251 vals = self.GetConfig()
252 if not vals:
253 return 1
254
255 if vals['type'] == 'gn':
256 return self.RunGNIsolate(vals)
257 else:
258 return self.Build('%s_run' % self.args.target[0])
259
260 def CmdLookup(self):
261 vals = self.Lookup()
262 if vals['type'] == 'gn':
dprankeeca4a782016-04-14 01:42:38263 cmd = self.GNCmd('gen', '_path_')
264 gn_args = self.GNArgs(vals)
265 self.Print('\nWriting """\\\n%s""" to _path_/args.gn.\n' % gn_args)
dpranke751516a2015-10-03 01:11:34266 env = None
267 else:
268 cmd, env = self.GYPCmd('_path_', vals)
269
270 self.PrintCmd(cmd, env)
271 return 0
272
273 def CmdRun(self):
274 vals = self.GetConfig()
275 if not vals:
276 return 1
277
278 build_dir = self.args.path[0]
279 target = self.args.target[0]
280
281 if vals['type'] == 'gn':
282 if self.args.build:
283 ret = self.Build(target)
284 if ret:
285 return ret
286 ret = self.RunGNIsolate(vals)
287 if ret:
288 return ret
289 else:
290 ret = self.Build('%s_run' % target)
291 if ret:
292 return ret
293
dpranke030d7a6d2016-03-26 17:23:50294 cmd = [
dpranke751516a2015-10-03 01:11:34295 self.executable,
296 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
297 'run',
298 '-s',
dpranke030d7a6d2016-03-26 17:23:50299 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
300 ]
301 if self.args.extra_args:
302 cmd += ['--'] + self.args.extra_args
303
304 ret, _, _ = self.Run(cmd, force_verbose=False, buffer_output=False)
dpranke751516a2015-10-03 01:11:34305
306 return ret
307
dpranke0cafc162016-03-19 00:41:10308 def CmdValidate(self, print_ok=True):
dprankefe4602312015-04-08 16:20:35309 errs = []
310
311 # Read the file to make sure it parses.
312 self.ReadConfigFile()
313
dpranke3be00142016-03-17 22:46:04314 # Build a list of all of the configs referenced by builders.
dprankefe4602312015-04-08 16:20:35315 all_configs = {}
dprankefe4602312015-04-08 16:20:35316 for master in self.masters:
dpranke3be00142016-03-17 22:46:04317 for config in self.masters[master].values():
318 all_configs[config] = master
dprankefe4602312015-04-08 16:20:35319
dpranke9dd5e252016-04-14 04:23:09320 # Check that every referenced args file or config actually exists.
dprankefe4602312015-04-08 16:20:35321 for config, loc in all_configs.items():
dpranke9dd5e252016-04-14 04:23:09322 if config.startswith('//'):
323 if not self.Exists(self.ToAbsPath(config)):
324 errs.append('Unknown args file "%s" referenced from "%s".' %
325 (config, loc))
326 elif not config in self.configs:
dprankefe4602312015-04-08 16:20:35327 errs.append('Unknown config "%s" referenced from "%s".' %
328 (config, loc))
329
330 # Check that every actual config is actually referenced.
331 for config in self.configs:
332 if not config in all_configs:
333 errs.append('Unused config "%s".' % config)
334
335 # Figure out the whole list of mixins, and check that every mixin
336 # listed by a config or another mixin actually exists.
337 referenced_mixins = set()
338 for config, mixins in self.configs.items():
339 for mixin in mixins:
340 if not mixin in self.mixins:
341 errs.append('Unknown mixin "%s" referenced by config "%s".' %
342 (mixin, config))
343 referenced_mixins.add(mixin)
344
345 for mixin in self.mixins:
346 for sub_mixin in self.mixins[mixin].get('mixins', []):
347 if not sub_mixin in self.mixins:
348 errs.append('Unknown mixin "%s" referenced by mixin "%s".' %
349 (sub_mixin, mixin))
350 referenced_mixins.add(sub_mixin)
351
352 # Check that every mixin defined is actually referenced somewhere.
353 for mixin in self.mixins:
354 if not mixin in referenced_mixins:
355 errs.append('Unreferenced mixin "%s".' % mixin)
356
dpranke255085e2016-03-16 05:23:59357 # If we're checking the Chromium config, check that the 'chromium' bots
358 # which build public artifacts do not include the chrome_with_codecs mixin.
359 if self.args.config_file == self.default_config:
360 if 'chromium' in self.masters:
361 for builder in self.masters['chromium']:
362 config = self.masters['chromium'][builder]
363 def RecurseMixins(current_mixin):
364 if current_mixin == 'chrome_with_codecs':
365 errs.append('Public artifact builder "%s" can not contain the '
366 '"chrome_with_codecs" mixin.' % builder)
367 return
368 if not 'mixins' in self.mixins[current_mixin]:
369 return
370 for mixin in self.mixins[current_mixin]['mixins']:
371 RecurseMixins(mixin)
dalecurtis56fd27e2016-03-09 23:06:41372
dpranke255085e2016-03-16 05:23:59373 for mixin in self.configs[config]:
374 RecurseMixins(mixin)
375 else:
376 errs.append('Missing "chromium" master. Please update this '
377 'proprietary codecs check with the name of the master '
378 'responsible for public build artifacts.')
dalecurtis56fd27e2016-03-09 23:06:41379
dprankefe4602312015-04-08 16:20:35380 if errs:
dpranke4323c80632015-08-10 22:53:54381 raise MBErr(('mb config file %s has problems:' % self.args.config_file) +
dprankea33267872015-08-12 15:45:17382 '\n ' + '\n '.join(errs))
dprankefe4602312015-04-08 16:20:35383
dpranke0cafc162016-03-19 00:41:10384 if print_ok:
385 self.Print('mb config file %s looks ok.' % self.args.config_file)
dprankefe4602312015-04-08 16:20:35386 return 0
387
dpranke867bcf4a2016-03-14 22:28:32388 def CmdAudit(self):
389 """Track the progress of the GYP->GN migration on the bots."""
390
dpranke0cafc162016-03-19 00:41:10391 # First, make sure the config file is okay, but don't print anything
392 # if it is (it will throw an error if it isn't).
393 self.CmdValidate(print_ok=False)
394
dpranke867bcf4a2016-03-14 22:28:32395 stats = OrderedDict()
396 STAT_MASTER_ONLY = 'Master only'
397 STAT_CONFIG_ONLY = 'Config only'
398 STAT_TBD = 'Still TBD'
399 STAT_GYP = 'Still GYP'
400 STAT_DONE = 'Done (on GN)'
401 stats[STAT_MASTER_ONLY] = 0
402 stats[STAT_CONFIG_ONLY] = 0
403 stats[STAT_TBD] = 0
404 stats[STAT_GYP] = 0
405 stats[STAT_DONE] = 0
406
aneeshmde50f472016-04-01 01:13:10407 def PrintBuilders(heading, builders, notes):
dpranke867bcf4a2016-03-14 22:28:32408 stats.setdefault(heading, 0)
409 stats[heading] += len(builders)
410 if builders:
411 self.Print(' %s:' % heading)
412 for builder in sorted(builders):
aneeshmde50f472016-04-01 01:13:10413 self.Print(' %s%s' % (builder, notes[builder]))
dpranke867bcf4a2016-03-14 22:28:32414
415 self.ReadConfigFile()
416
417 masters = self.args.master or self.masters
418 for master in sorted(masters):
419 url = self.args.url_template.replace('{master}', master)
420
421 self.Print('Auditing %s' % master)
422
423 MASTERS_TO_SKIP = (
424 'client.skia',
425 'client.v8.fyi',
426 'tryserver.v8',
427 )
428 if master in MASTERS_TO_SKIP:
429 # Skip these bots because converting them is the responsibility of
430 # those teams and out of scope for the Chromium migration to GN.
431 self.Print(' Skipped (out of scope)')
432 self.Print('')
433 continue
434
dprankeeafba352016-03-15 19:34:53435 INTERNAL_MASTERS = ('official.desktop', 'official.desktop.continuous')
dpranke867bcf4a2016-03-14 22:28:32436 if master in INTERNAL_MASTERS and not self.args.internal:
437 # Skip these because the servers aren't accessible by default ...
438 self.Print(' Skipped (internal)')
439 self.Print('')
440 continue
441
442 try:
443 # Fetch the /builders contents from the buildbot master. The
444 # keys of the dict are the builder names themselves.
445 json_contents = self.Fetch(url)
446 d = json.loads(json_contents)
447 except Exception as e:
448 self.Print(str(e))
449 return 1
450
451 config_builders = set(self.masters[master])
452 master_builders = set(d.keys())
453 both = master_builders & config_builders
454 master_only = master_builders - config_builders
455 config_only = config_builders - master_builders
456 tbd = set()
457 gyp = set()
458 done = set()
aneeshmde50f472016-04-01 01:13:10459 notes = {builder: '' for builder in config_builders | master_builders}
dpranke867bcf4a2016-03-14 22:28:32460
461 for builder in both:
462 config = self.masters[master][builder]
463 if config == 'tbd':
464 tbd.add(builder)
465 else:
466 # TODO(dpranke): Check if MB is actually running?
467 vals = self.FlattenConfig(config)
468 if vals['type'] == 'gyp':
469 gyp.add(builder)
470 else:
471 done.add(builder)
472
aneeshmde50f472016-04-01 01:13:10473 if self.args.check_compile and (tbd or master_only):
474 either = tbd | master_only
475 for builder in either:
476 notes[builder] = ' (' + self.CheckCompile(master, builder) +')'
477
dpranke867bcf4a2016-03-14 22:28:32478 if master_only or config_only or tbd or gyp:
aneeshmde50f472016-04-01 01:13:10479 PrintBuilders(STAT_MASTER_ONLY, master_only, notes)
480 PrintBuilders(STAT_CONFIG_ONLY, config_only, notes)
481 PrintBuilders(STAT_TBD, tbd, notes)
482 PrintBuilders(STAT_GYP, gyp, notes)
dpranke867bcf4a2016-03-14 22:28:32483 else:
dprankeeafba352016-03-15 19:34:53484 self.Print(' ... done')
dpranke867bcf4a2016-03-14 22:28:32485
486 stats[STAT_DONE] += len(done)
487
488 self.Print('')
489
490 fmt = '{:<27} {:>4}'
491 self.Print(fmt.format('Totals', str(sum(int(v) for v in stats.values()))))
492 self.Print(fmt.format('-' * 27, '----'))
493 for stat, count in stats.items():
494 self.Print(fmt.format(stat, str(count)))
495
496 return 0
497
dprankefe4602312015-04-08 16:20:35498 def GetConfig(self):
dpranke751516a2015-10-03 01:11:34499 build_dir = self.args.path[0]
500
501 vals = {}
502 if self.args.builder or self.args.master or self.args.config:
503 vals = self.Lookup()
504 if vals['type'] == 'gn':
505 # Re-run gn gen in order to ensure the config is consistent with the
506 # build dir.
507 self.RunGNGen(vals)
508 return vals
509
510 # TODO: We can only get the config for GN build dirs, not GYP build dirs.
511 # GN stores the args that were used in args.gn in the build dir,
512 # but GYP doesn't store them anywhere. We should consider modifying
513 # gyp_chromium to record the arguments it runs with in a similar
514 # manner.
515
516 mb_type_path = self.PathJoin(self.ToAbsPath(build_dir), 'mb_type')
517 if not self.Exists(mb_type_path):
518 gn_args_path = self.PathJoin(self.ToAbsPath(build_dir), 'args.gn')
519 if not self.Exists(gn_args_path):
520 self.Print('Must either specify a path to an existing GN build dir '
521 'or pass in a -m/-b pair or a -c flag to specify the '
522 'configuration')
523 return {}
524 else:
525 mb_type = 'gn'
526 else:
527 mb_type = self.ReadFile(mb_type_path).strip()
528
529 if mb_type == 'gn':
530 vals = self.GNValsFromDir(build_dir)
531 else:
532 vals = {}
533 vals['type'] = mb_type
534
535 return vals
536
537 def GNValsFromDir(self, build_dir):
538 args_contents = self.ReadFile(
539 self.PathJoin(self.ToAbsPath(build_dir), 'args.gn'))
540 gn_args = []
541 for l in args_contents.splitlines():
542 fields = l.split(' ')
543 name = fields[0]
544 val = ' '.join(fields[2:])
545 gn_args.append('%s=%s' % (name, val))
546
547 return {
548 'gn_args': ' '.join(gn_args),
549 'type': 'gn',
550 }
551
552 def Lookup(self):
dprankee0f486f2015-11-19 23:42:00553 vals = self.ReadBotConfig()
554 if not vals:
555 self.ReadConfigFile()
556 config = self.ConfigFromArgs()
dpranke9dd5e252016-04-14 04:23:09557 if config.startswith('//'):
558 if not self.Exists(self.ToAbsPath(config)):
559 raise MBErr('args file "%s" not found' % config)
560 vals = {
561 'type': 'gn',
562 'args_file': config,
563 'gn_args': '',
564 }
565 else:
566 if not config in self.configs:
567 raise MBErr('Config "%s" not found in %s' %
568 (config, self.args.config_file))
569 vals = self.FlattenConfig(config)
dpranke751516a2015-10-03 01:11:34570
571 # Do some basic sanity checking on the config so that we
572 # don't have to do this in every caller.
573 assert 'type' in vals, 'No meta-build type specified in the config'
574 assert vals['type'] in ('gn', 'gyp'), (
575 'Unknown meta-build type "%s"' % vals['gn_args'])
576
577 return vals
dprankefe4602312015-04-08 16:20:35578
dprankee0f486f2015-11-19 23:42:00579 def ReadBotConfig(self):
580 if not self.args.master or not self.args.builder:
581 return {}
582 path = self.PathJoin(self.chromium_src_dir, 'ios', 'build', 'bots',
583 self.args.master, self.args.builder + '.json')
584 if not self.Exists(path):
585 return {}
586
587 contents = json.loads(self.ReadFile(path))
588 gyp_vals = contents.get('GYP_DEFINES', {})
589 if isinstance(gyp_vals, dict):
590 gyp_defines = ' '.join('%s=%s' % (k, v) for k, v in gyp_vals.items())
591 else:
592 gyp_defines = ' '.join(gyp_vals)
593 gn_args = ' '.join(contents.get('gn_args', []))
594
595 return {
596 'type': contents.get('mb_type', ''),
597 'gn_args': gn_args,
598 'gyp_defines': gyp_defines,
dprankef75a3de52015-12-14 22:17:52599 'gyp_crosscompile': False,
dprankee0f486f2015-11-19 23:42:00600 }
601
dprankefe4602312015-04-08 16:20:35602 def ReadConfigFile(self):
603 if not self.Exists(self.args.config_file):
604 raise MBErr('config file not found at %s' % self.args.config_file)
605
606 try:
607 contents = ast.literal_eval(self.ReadFile(self.args.config_file))
608 except SyntaxError as e:
609 raise MBErr('Failed to parse config file "%s": %s' %
610 (self.args.config_file, e))
611
dprankefe4602312015-04-08 16:20:35612 self.configs = contents['configs']
613 self.masters = contents['masters']
614 self.mixins = contents['mixins']
dprankefe4602312015-04-08 16:20:35615
616 def ConfigFromArgs(self):
617 if self.args.config:
618 if self.args.master or self.args.builder:
619 raise MBErr('Can not specific both -c/--config and -m/--master or '
620 '-b/--builder')
621
622 return self.args.config
623
624 if not self.args.master or not self.args.builder:
625 raise MBErr('Must specify either -c/--config or '
626 '(-m/--master and -b/--builder)')
627
628 if not self.args.master in self.masters:
629 raise MBErr('Master name "%s" not found in "%s"' %
630 (self.args.master, self.args.config_file))
631
632 if not self.args.builder in self.masters[self.args.master]:
633 raise MBErr('Builder name "%s" not found under masters[%s] in "%s"' %
634 (self.args.builder, self.args.master, self.args.config_file))
635
636 return self.masters[self.args.master][self.args.builder]
637
638 def FlattenConfig(self, config):
639 mixins = self.configs[config]
640 vals = {
641 'type': None,
642 'gn_args': [],
dprankec161aa92015-09-14 20:21:13643 'gyp_defines': '',
dprankeedc49c382015-08-14 02:32:59644 'gyp_crosscompile': False,
dprankefe4602312015-04-08 16:20:35645 }
646
647 visited = []
648 self.FlattenMixins(mixins, vals, visited)
649 return vals
650
651 def FlattenMixins(self, mixins, vals, visited):
652 for m in mixins:
653 if m not in self.mixins:
654 raise MBErr('Unknown mixin "%s"' % m)
dprankeee5b51f62015-04-09 00:03:22655
656 # TODO: check for cycles in mixins.
dprankefe4602312015-04-08 16:20:35657
658 visited.append(m)
659
660 mixin_vals = self.mixins[m]
661 if 'type' in mixin_vals:
662 vals['type'] = mixin_vals['type']
663 if 'gn_args' in mixin_vals:
664 if vals['gn_args']:
665 vals['gn_args'] += ' ' + mixin_vals['gn_args']
666 else:
667 vals['gn_args'] = mixin_vals['gn_args']
dprankeedc49c382015-08-14 02:32:59668 if 'gyp_crosscompile' in mixin_vals:
669 vals['gyp_crosscompile'] = mixin_vals['gyp_crosscompile']
dprankefe4602312015-04-08 16:20:35670 if 'gyp_defines' in mixin_vals:
671 if vals['gyp_defines']:
672 vals['gyp_defines'] += ' ' + mixin_vals['gyp_defines']
673 else:
674 vals['gyp_defines'] = mixin_vals['gyp_defines']
675 if 'mixins' in mixin_vals:
676 self.FlattenMixins(mixin_vals['mixins'], vals, visited)
677 return vals
678
dprankec161aa92015-09-14 20:21:13679 def ClobberIfNeeded(self, vals):
680 path = self.args.path[0]
681 build_dir = self.ToAbsPath(path)
dpranke8c2cfd32015-09-17 20:12:33682 mb_type_path = self.PathJoin(build_dir, 'mb_type')
dprankec161aa92015-09-14 20:21:13683 needs_clobber = False
684 new_mb_type = vals['type']
685 if self.Exists(build_dir):
686 if self.Exists(mb_type_path):
687 old_mb_type = self.ReadFile(mb_type_path)
688 if old_mb_type != new_mb_type:
689 self.Print("Build type mismatch: was %s, will be %s, clobbering %s" %
690 (old_mb_type, new_mb_type, path))
691 needs_clobber = True
692 else:
693 # There is no 'mb_type' file in the build directory, so this probably
694 # means that the prior build(s) were not done through mb, and we
695 # have no idea if this was a GYP build or a GN build. Clobber it
696 # to be safe.
697 self.Print("%s/mb_type missing, clobbering to be safe" % path)
698 needs_clobber = True
699
dpranke3cec199c2015-09-22 23:29:02700 if self.args.dryrun:
701 return
702
dprankec161aa92015-09-14 20:21:13703 if needs_clobber:
704 self.RemoveDirectory(build_dir)
705
706 self.MaybeMakeDirectory(build_dir)
707 self.WriteFile(mb_type_path, new_mb_type)
708
Dirk Pranke0fd41bcd2015-06-19 00:05:50709 def RunGNGen(self, vals):
dpranke751516a2015-10-03 01:11:34710 build_dir = self.args.path[0]
Dirk Pranke0fd41bcd2015-06-19 00:05:50711
dprankeeca4a782016-04-14 01:42:38712 cmd = self.GNCmd('gen', build_dir, '--check')
713 gn_args = self.GNArgs(vals)
714
715 # Since GN hasn't run yet, the build directory may not even exist.
716 self.MaybeMakeDirectory(self.ToAbsPath(build_dir))
717
718 gn_args_path = self.ToAbsPath(build_dir, 'args.gn')
719 self.WriteFile(gn_args_path, gn_args)
dpranke74559b52015-06-10 21:20:39720
721 swarming_targets = []
dpranke751516a2015-10-03 01:11:34722 if getattr(self.args, 'swarming_targets_file', None):
dpranke74559b52015-06-10 21:20:39723 # We need GN to generate the list of runtime dependencies for
724 # the compile targets listed (one per line) in the file so
725 # we can run them via swarming. We use ninja_to_gn.pyl to convert
726 # the compile targets to the matching GN labels.
dprankeb2be10a2016-02-22 17:11:00727 path = self.args.swarming_targets_file
728 if not self.Exists(path):
729 self.WriteFailureAndRaise('"%s" does not exist' % path,
730 output_path=None)
731 contents = self.ReadFile(path)
732 swarming_targets = set(contents.splitlines())
dpranke8c2cfd32015-09-17 20:12:33733 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
dprankea55584f12015-07-22 00:52:47734 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
dpranke74559b52015-06-10 21:20:39735 gn_labels = []
dprankeb2be10a2016-02-22 17:11:00736 err = ''
dpranke74559b52015-06-10 21:20:39737 for target in swarming_targets:
jbudorickdcff99982016-02-03 19:38:07738 target_name = self.GNTargetName(target)
739 if not target_name in gn_isolate_map:
dprankeb2be10a2016-02-22 17:11:00740 err += ('test target "%s" not found\n' % target_name)
741 elif gn_isolate_map[target_name]['type'] == 'unknown':
742 err += ('test target "%s" type is unknown\n' % target_name)
743 else:
744 gn_labels.append(gn_isolate_map[target_name]['label'])
745
746 if err:
747 raise MBErr('Error: Failed to match swarming targets to %s:\n%s' %
748 ('//testing/buildbot/gn_isolate_map.pyl', err))
dpranke74559b52015-06-10 21:20:39749
dpranke751516a2015-10-03 01:11:34750 gn_runtime_deps_path = self.ToAbsPath(build_dir, 'runtime_deps')
dpranke74559b52015-06-10 21:20:39751 self.WriteFile(gn_runtime_deps_path, '\n'.join(gn_labels) + '\n')
752 cmd.append('--runtime-deps-list-file=%s' % gn_runtime_deps_path)
753
dprankefe4602312015-04-08 16:20:35754 ret, _, _ = self.Run(cmd)
dprankee0547cd2015-09-15 01:27:40755 if ret:
756 # If `gn gen` failed, we should exit early rather than trying to
757 # generate isolates. Run() will have already logged any error output.
758 self.Print('GN gen failed: %d' % ret)
759 return ret
dpranke74559b52015-06-10 21:20:39760
761 for target in swarming_targets:
jbudorick91c8a6012016-01-29 23:20:02762 if target.endswith('_apk'):
763 # "_apk" targets may be either android_apk or executable. The former
764 # will result in runtime_deps associated with the stamp file, while the
765 # latter will result in runtime_deps associated with the executable.
jbudorickdcff99982016-02-03 19:38:07766 target_name = self.GNTargetName(target)
767 label = gn_isolate_map[target_name]['label']
jbudorick91c8a6012016-01-29 23:20:02768 runtime_deps_targets = [
dpranke48ccf8f2016-03-28 23:58:28769 target_name + '.runtime_deps',
770 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
jbudorick91c8a6012016-01-29 23:20:02771 elif gn_isolate_map[target]['type'] == 'gpu_browser_test':
dpranke48ccf8f2016-03-28 23:58:28772 if self.platform == 'win32':
773 runtime_deps_targets = ['browser_tests.exe.runtime_deps']
774 else:
775 runtime_deps_targets = ['browser_tests.runtime_deps']
dprankefe0d35e2016-02-05 02:43:59776 elif (gn_isolate_map[target]['type'] == 'script' or
777 gn_isolate_map[target].get('label_type') == 'group'):
dpranke6abd8652015-08-28 03:21:11778 # For script targets, the build target is usually a group,
779 # for which gn generates the runtime_deps next to the stamp file
780 # for the label, which lives under the obj/ directory.
781 label = gn_isolate_map[target]['label']
dpranke48ccf8f2016-03-28 23:58:28782 runtime_deps_targets = [
783 'obj/%s.stamp.runtime_deps' % label.replace(':', '/')]
784 elif self.platform == 'win32':
785 runtime_deps_targets = [target + '.exe.runtime_deps']
dpranke34bd39d2015-06-24 02:36:52786 else:
dpranke48ccf8f2016-03-28 23:58:28787 runtime_deps_targets = [target + '.runtime_deps']
jbudorick91c8a6012016-01-29 23:20:02788
dpranke48ccf8f2016-03-28 23:58:28789 for r in runtime_deps_targets:
790 runtime_deps_path = self.ToAbsPath(build_dir, r)
791 if self.Exists(runtime_deps_path):
jbudorick91c8a6012016-01-29 23:20:02792 break
793 else:
dpranke48ccf8f2016-03-28 23:58:28794 raise MBErr('did not generate any of %s' %
795 ', '.join(runtime_deps_targets))
dpranke74559b52015-06-10 21:20:39796
dprankea55584f12015-07-22 00:52:47797 command, extra_files = self.GetIsolateCommand(target, vals,
798 gn_isolate_map)
dpranked5b2b9432015-06-23 16:55:30799
dpranke48ccf8f2016-03-28 23:58:28800 runtime_deps = self.ReadFile(runtime_deps_path).splitlines()
dpranked5b2b9432015-06-23 16:55:30801
dpranke751516a2015-10-03 01:11:34802 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
803 extra_files)
dpranked5b2b9432015-06-23 16:55:30804
dpranke751516a2015-10-03 01:11:34805 return 0
806
807 def RunGNIsolate(self, vals):
808 gn_isolate_map = ast.literal_eval(self.ReadFile(self.PathJoin(
809 self.chromium_src_dir, 'testing', 'buildbot', 'gn_isolate_map.pyl')))
810
811 build_dir = self.args.path[0]
812 target = self.args.target[0]
jbudorickdcff99982016-02-03 19:38:07813 target_name = self.GNTargetName(target)
dpranke751516a2015-10-03 01:11:34814 command, extra_files = self.GetIsolateCommand(target, vals, gn_isolate_map)
815
jbudorickdcff99982016-02-03 19:38:07816 label = gn_isolate_map[target_name]['label']
dprankeeca4a782016-04-14 01:42:38817 cmd = self.GNCmd('desc', build_dir, label, 'runtime_deps')
dpranke40da0202016-02-13 05:05:20818 ret, out, _ = self.Call(cmd)
dpranke751516a2015-10-03 01:11:34819 if ret:
dpranke030d7a6d2016-03-26 17:23:50820 if out:
821 self.Print(out)
dpranke751516a2015-10-03 01:11:34822 return ret
823
824 runtime_deps = out.splitlines()
825
826 self.WriteIsolateFiles(build_dir, command, target, runtime_deps,
827 extra_files)
828
829 ret, _, _ = self.Run([
830 self.executable,
831 self.PathJoin('tools', 'swarming_client', 'isolate.py'),
832 'check',
833 '-i',
834 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
835 '-s',
836 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target))],
837 buffer_output=False)
dpranked5b2b9432015-06-23 16:55:30838
dprankefe4602312015-04-08 16:20:35839 return ret
840
dpranke751516a2015-10-03 01:11:34841 def WriteIsolateFiles(self, build_dir, command, target, runtime_deps,
842 extra_files):
843 isolate_path = self.ToAbsPath(build_dir, target + '.isolate')
844 self.WriteFile(isolate_path,
845 pprint.pformat({
846 'variables': {
847 'command': command,
848 'files': sorted(runtime_deps + extra_files),
849 }
850 }) + '\n')
851
852 self.WriteJSON(
853 {
854 'args': [
855 '--isolated',
856 self.ToSrcRelPath('%s/%s.isolated' % (build_dir, target)),
857 '--isolate',
858 self.ToSrcRelPath('%s/%s.isolate' % (build_dir, target)),
859 ],
860 'dir': self.chromium_src_dir,
861 'version': 1,
862 },
863 isolate_path + 'd.gen.json',
864 )
865
dprankeeca4a782016-04-14 01:42:38866 def GNCmd(self, subcommand, path, *args):
dpranked1fba482015-04-14 20:54:51867 if self.platform == 'linux2':
dpranke40da0202016-02-13 05:05:20868 subdir, exe = 'linux64', 'gn'
dpranked1fba482015-04-14 20:54:51869 elif self.platform == 'darwin':
dpranke40da0202016-02-13 05:05:20870 subdir, exe = 'mac', 'gn'
dpranked1fba482015-04-14 20:54:51871 else:
dpranke40da0202016-02-13 05:05:20872 subdir, exe = 'win', 'gn.exe'
dprankeeca4a782016-04-14 01:42:38873
dpranke40da0202016-02-13 05:05:20874 gn_path = self.PathJoin(self.chromium_src_dir, 'buildtools', subdir, exe)
dpranked1fba482015-04-14 20:54:51875
dprankeeca4a782016-04-14 01:42:38876 return [gn_path, subcommand, path] + list(args)
877
878 def GNArgs(self, vals):
879 gn_args = vals['gn_args']
dpranked0c138b2016-04-13 18:28:47880 if self.args.goma_dir:
881 gn_args += ' goma_dir="%s"' % self.args.goma_dir
dprankeeca4a782016-04-14 01:42:38882
883 # Canonicalize the arg string into a sorted, newline-separated list
884 # of key-value pairs, and de-dup the keys if need be so that only
885 # the last instance of each arg is listed.
886 gn_args = gn_helpers.ToGNString(gn_helpers.FromGNArgs(gn_args))
887
dpranke9dd5e252016-04-14 04:23:09888 args_file = vals.get('args_file', None)
889 if args_file:
890 gn_args = ('import("%s")\n' % vals['args_file']) + gn_args
dprankeeca4a782016-04-14 01:42:38891 return gn_args
dprankefe4602312015-04-08 16:20:35892
Dirk Pranke0fd41bcd2015-06-19 00:05:50893 def RunGYPGen(self, vals):
894 path = self.args.path[0]
895
dpranke8c2cfd32015-09-17 20:12:33896 output_dir = self.ParseGYPConfigPath(path)
dpranke38f4acb62015-09-29 23:50:41897 cmd, env = self.GYPCmd(output_dir, vals)
dprankeedc49c382015-08-14 02:32:59898 ret, _, _ = self.Run(cmd, env=env)
dprankefe4602312015-04-08 16:20:35899 return ret
900
901 def RunGYPAnalyze(self, vals):
dpranke8c2cfd32015-09-17 20:12:33902 output_dir = self.ParseGYPConfigPath(self.args.path[0])
dprankecda00332015-04-11 04:18:32903 if self.args.verbose:
dpranke7837fc362015-11-19 03:54:16904 inp = self.ReadInputJSON(['files', 'test_targets',
905 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:32906 self.Print()
907 self.Print('analyze input:')
908 self.PrintJSON(inp)
909 self.Print()
910
dpranke38f4acb62015-09-29 23:50:41911 cmd, env = self.GYPCmd(output_dir, vals)
dpranke1d306312015-08-11 21:17:33912 cmd.extend(['-f', 'analyzer',
913 '-G', 'config_path=%s' % self.args.input_path[0],
dprankefe4602312015-04-08 16:20:35914 '-G', 'analyzer_output_path=%s' % self.args.output_path[0]])
dpranke3cec199c2015-09-22 23:29:02915 ret, _, _ = self.Run(cmd, env=env)
dprankecda00332015-04-11 04:18:32916 if not ret and self.args.verbose:
917 outp = json.loads(self.ReadFile(self.args.output_path[0]))
918 self.Print()
919 self.Print('analyze output:')
dpranke74559b52015-06-10 21:20:39920 self.PrintJSON(outp)
dprankecda00332015-04-11 04:18:32921 self.Print()
922
dprankefe4602312015-04-08 16:20:35923 return ret
924
dprankea55584f12015-07-22 00:52:47925 def GetIsolateCommand(self, target, vals, gn_isolate_map):
jbudoricke8428732016-02-02 02:17:06926 android = 'target_os="android"' in vals['gn_args']
927
dpranked8113582015-06-05 20:08:25928 # This needs to mirror the settings in //build/config/ui.gni:
929 # use_x11 = is_linux && !use_ozone.
930 # TODO(dpranke): Figure out how to keep this in sync better.
dpranke8c2cfd32015-09-17 20:12:33931 use_x11 = (self.platform == 'linux2' and
jbudoricke8428732016-02-02 02:17:06932 not android and
dpranked8113582015-06-05 20:08:25933 not 'use_ozone=true' in vals['gn_args'])
934
935 asan = 'is_asan=true' in vals['gn_args']
936 msan = 'is_msan=true' in vals['gn_args']
937 tsan = 'is_tsan=true' in vals['gn_args']
938
jbudorickdcff99982016-02-03 19:38:07939 target_name = self.GNTargetName(target)
940 test_type = gn_isolate_map[target_name]['type']
dprankefe0d35e2016-02-05 02:43:59941
942 executable = gn_isolate_map[target_name].get('executable', target_name)
943 executable_suffix = '.exe' if self.platform == 'win32' else ''
944
dprankea55584f12015-07-22 00:52:47945 cmdline = []
946 extra_files = []
dpranked8113582015-06-05 20:08:25947
jbudoricke8428732016-02-02 02:17:06948 if android:
949 # TODO(jbudorick): This won't work with instrumentation test targets.
950 # Revisit this logic when those are added to gn_isolate_map.pyl.
jbudorickdcff99982016-02-03 19:38:07951 cmdline = [self.PathJoin('bin', 'run_%s' % target_name)]
jbudoricke8428732016-02-02 02:17:06952 elif use_x11 and test_type == 'windowed_test_launcher':
dprankea55584f12015-07-22 00:52:47953 extra_files = [
954 'xdisplaycheck',
dpranked8113582015-06-05 20:08:25955 '../../testing/test_env.py',
dprankea55584f12015-07-22 00:52:47956 '../../testing/xvfb.py',
957 ]
958 cmdline = [
dprankefe0d35e2016-02-05 02:43:59959 '../../testing/xvfb.py',
960 '.',
961 './' + str(executable) + executable_suffix,
962 '--brave-new-test-launcher',
963 '--test-launcher-bot-mode',
964 '--asan=%d' % asan,
965 '--msan=%d' % msan,
966 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47967 ]
968 elif test_type in ('windowed_test_launcher', 'console_test_launcher'):
969 extra_files = [
970 '../../testing/test_env.py'
971 ]
972 cmdline = [
973 '../../testing/test_env.py',
dprankefe0d35e2016-02-05 02:43:59974 './' + str(executable) + executable_suffix,
dpranked8113582015-06-05 20:08:25975 '--brave-new-test-launcher',
976 '--test-launcher-bot-mode',
977 '--asan=%d' % asan,
978 '--msan=%d' % msan,
979 '--tsan=%d' % tsan,
dprankea55584f12015-07-22 00:52:47980 ]
dprankedbdd9d82015-08-12 21:18:18981 elif test_type == 'gpu_browser_test':
982 extra_files = [
983 '../../testing/test_env.py'
984 ]
985 gtest_filter = gn_isolate_map[target]['gtest_filter']
986 cmdline = [
987 '../../testing/test_env.py',
dpranke6abd8652015-08-28 03:21:11988 './browser_tests' + executable_suffix,
dprankedbdd9d82015-08-12 21:18:18989 '--test-launcher-bot-mode',
990 '--enable-gpu',
991 '--test-launcher-jobs=1',
992 '--gtest_filter=%s' % gtest_filter,
993 ]
dpranke6abd8652015-08-28 03:21:11994 elif test_type == 'script':
995 extra_files = [
996 '../../testing/test_env.py'
997 ]
998 cmdline = [
999 '../../testing/test_env.py',
nednguyenfffd76a52015-09-29 19:37:391000 '../../' + self.ToSrcRelPath(gn_isolate_map[target]['script'])
dprankefe0d35e2016-02-05 02:43:591001 ]
dprankea55584f12015-07-22 00:52:471002 elif test_type in ('raw'):
1003 extra_files = []
1004 cmdline = [
1005 './' + str(target) + executable_suffix,
dprankefe0d35e2016-02-05 02:43:591006 ]
dpranked8113582015-06-05 20:08:251007
dprankea55584f12015-07-22 00:52:471008 else:
1009 self.WriteFailureAndRaise('No command line for %s found (test type %s).'
1010 % (target, test_type), output_path=None)
dpranked8113582015-06-05 20:08:251011
jbudorick8a0560422016-02-05 06:07:171012 cmdline += gn_isolate_map[target_name].get('args', [])
dprankefe0d35e2016-02-05 02:43:591013
dpranked8113582015-06-05 20:08:251014 return cmdline, extra_files
1015
dpranke74559b52015-06-10 21:20:391016 def ToAbsPath(self, build_path, *comps):
dpranke8c2cfd32015-09-17 20:12:331017 return self.PathJoin(self.chromium_src_dir,
1018 self.ToSrcRelPath(build_path),
1019 *comps)
dpranked8113582015-06-05 20:08:251020
dprankeee5b51f62015-04-09 00:03:221021 def ToSrcRelPath(self, path):
1022 """Returns a relative path from the top of the repo."""
dpranke030d7a6d2016-03-26 17:23:501023 if path.startswith('//'):
1024 return path[2:].replace('/', self.sep)
1025 return self.RelPath(path, self.chromium_src_dir)
dprankefe4602312015-04-08 16:20:351026
1027 def ParseGYPConfigPath(self, path):
dprankeee5b51f62015-04-09 00:03:221028 rpath = self.ToSrcRelPath(path)
dpranke8c2cfd32015-09-17 20:12:331029 output_dir, _, _ = rpath.rpartition(self.sep)
1030 return output_dir
dprankefe4602312015-04-08 16:20:351031
dpranke38f4acb62015-09-29 23:50:411032 def GYPCmd(self, output_dir, vals):
1033 gyp_defines = vals['gyp_defines']
dpranke3cec199c2015-09-22 23:29:021034 goma_dir = self.args.goma_dir
1035
1036 # GYP uses shlex.split() to split the gyp defines into separate arguments,
1037 # so we can support backslashes and and spaces in arguments by quoting
1038 # them, even on Windows, where this normally wouldn't work.
dpranked0c138b2016-04-13 18:28:471039 if goma_dir and ('\\' in goma_dir or ' ' in goma_dir):
dpranke3cec199c2015-09-22 23:29:021040 goma_dir = "'%s'" % goma_dir
dpranked0c138b2016-04-13 18:28:471041
1042 if goma_dir:
1043 gyp_defines += ' gomadir=%s' % goma_dir
dpranke3cec199c2015-09-22 23:29:021044
dprankefe4602312015-04-08 16:20:351045 cmd = [
dpranke8c2cfd32015-09-17 20:12:331046 self.executable,
1047 self.PathJoin('build', 'gyp_chromium'),
dprankefe4602312015-04-08 16:20:351048 '-G',
1049 'output_dir=' + output_dir,
dprankefe4602312015-04-08 16:20:351050 ]
dpranke38f4acb62015-09-29 23:50:411051
1052 # Ensure that we have an environment that only contains
1053 # the exact values of the GYP variables we need.
dpranke3cec199c2015-09-22 23:29:021054 env = os.environ.copy()
dprankef75a3de52015-12-14 22:17:521055 env['GYP_GENERATORS'] = 'ninja'
dpranke38f4acb62015-09-29 23:50:411056 if 'GYP_CHROMIUM_NO_ACTION' in env:
1057 del env['GYP_CHROMIUM_NO_ACTION']
1058 if 'GYP_CROSSCOMPILE' in env:
1059 del env['GYP_CROSSCOMPILE']
dpranke3cec199c2015-09-22 23:29:021060 env['GYP_DEFINES'] = gyp_defines
dpranke38f4acb62015-09-29 23:50:411061 if vals['gyp_crosscompile']:
1062 env['GYP_CROSSCOMPILE'] = '1'
dpranke3cec199c2015-09-22 23:29:021063 return cmd, env
dprankefe4602312015-04-08 16:20:351064
Dirk Pranke0fd41bcd2015-06-19 00:05:501065 def RunGNAnalyze(self, vals):
1066 # analyze runs before 'gn gen' now, so we need to run gn gen
1067 # in order to ensure that we have a build directory.
1068 ret = self.RunGNGen(vals)
1069 if ret:
1070 return ret
1071
dpranke7837fc362015-11-19 03:54:161072 inp = self.ReadInputJSON(['files', 'test_targets',
1073 'additional_compile_targets'])
dprankecda00332015-04-11 04:18:321074 if self.args.verbose:
1075 self.Print()
1076 self.Print('analyze input:')
1077 self.PrintJSON(inp)
1078 self.Print()
1079
dpranke7837fc362015-11-19 03:54:161080 # TODO(crbug.com/555273) - currently GN treats targets and
1081 # additional_compile_targets identically since we can't tell the
1082 # difference between a target that is a group in GN and one that isn't.
1083 # We should eventually fix this and treat the two types differently.
1084 targets = (set(inp['test_targets']) |
1085 set(inp['additional_compile_targets']))
dpranke5ab84a502015-11-13 17:35:021086
dprankecda00332015-04-11 04:18:321087 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351088
1089 # Bail out early if a GN file was modified, since 'gn refs' won't know
dpranke5ab84a502015-11-13 17:35:021090 # what to do about it. Also, bail out early if 'all' was asked for,
1091 # since we can't deal with it yet.
1092 if (any(f.endswith('.gn') or f.endswith('.gni') for f in inp['files']) or
1093 'all' in targets):
dpranke7837fc362015-11-19 03:54:161094 self.WriteJSON({
1095 'status': 'Found dependency (all)',
1096 'compile_targets': sorted(targets),
1097 'test_targets': sorted(targets & set(inp['test_targets'])),
1098 }, output_path)
dpranke76734662015-04-16 02:17:501099 return 0
1100
dpranke7c5f614d2015-07-22 23:43:391101 # This shouldn't normally happen, but could due to unusual race conditions,
1102 # like a try job that gets scheduled before a patch lands but runs after
1103 # the patch has landed.
1104 if not inp['files']:
1105 self.Print('Warning: No files modified in patch, bailing out early.')
dpranke7837fc362015-11-19 03:54:161106 self.WriteJSON({
1107 'status': 'No dependency',
1108 'compile_targets': [],
1109 'test_targets': [],
1110 }, output_path)
dpranke7c5f614d2015-07-22 23:43:391111 return 0
1112
Dirk Pranke12ee2db2015-04-14 23:15:321113 ret = 0
dprankef61de2f2015-05-14 04:09:561114 response_file = self.TempFile()
1115 response_file.write('\n'.join(inp['files']) + '\n')
1116 response_file.close()
1117
dpranke5ab84a502015-11-13 17:35:021118 matching_targets = set()
dprankef61de2f2015-05-14 04:09:561119 try:
dprankeeca4a782016-04-14 01:42:381120 cmd = self.GNCmd('refs',
1121 self.args.path[0],
1122 '@%s' % response_file.name,
1123 '--all',
1124 '--as=output')
dprankee0547cd2015-09-15 01:27:401125 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke0b3b7882015-04-24 03:38:121126 if ret and not 'The input matches no targets' in out:
dprankecda00332015-04-11 04:18:321127 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1128 output_path)
dpranke8c2cfd32015-09-17 20:12:331129 build_dir = self.ToSrcRelPath(self.args.path[0]) + self.sep
dprankef61de2f2015-05-14 04:09:561130 for output in out.splitlines():
1131 build_output = output.replace(build_dir, '')
dpranke5ab84a502015-11-13 17:35:021132 if build_output in targets:
1133 matching_targets.add(build_output)
dpranke067d0142015-05-14 22:52:451134
dprankeeca4a782016-04-14 01:42:381135 cmd = self.GNCmd('refs',
1136 self.args.path[0],
1137 '@%s' % response_file.name,
1138 '--all')
dprankee0547cd2015-09-15 01:27:401139 ret, out, _ = self.Run(cmd, force_verbose=False)
dpranke067d0142015-05-14 22:52:451140 if ret and not 'The input matches no targets' in out:
1141 self.WriteFailureAndRaise('gn refs returned %d: %s' % (ret, out),
1142 output_path)
1143 for label in out.splitlines():
1144 build_target = label[2:]
newt309af8f2015-08-25 22:10:201145 # We want to accept 'chrome/android:chrome_public_apk' and
1146 # just 'chrome_public_apk'. This may result in too many targets
dpranke067d0142015-05-14 22:52:451147 # getting built, but we can adjust that later if need be.
dpranke5ab84a502015-11-13 17:35:021148 for input_target in targets:
dpranke067d0142015-05-14 22:52:451149 if (input_target == build_target or
1150 build_target.endswith(':' + input_target)):
dpranke5ab84a502015-11-13 17:35:021151 matching_targets.add(input_target)
dprankef61de2f2015-05-14 04:09:561152 finally:
1153 self.RemoveFile(response_file.name)
dprankefe4602312015-04-08 16:20:351154
dprankef61de2f2015-05-14 04:09:561155 if matching_targets:
dpranke7837fc362015-11-19 03:54:161156 self.WriteJSON({
dpranke5ab84a502015-11-13 17:35:021157 'status': 'Found dependency',
dpranke7837fc362015-11-19 03:54:161158 'compile_targets': sorted(matching_targets),
1159 'test_targets': sorted(matching_targets &
1160 set(inp['test_targets'])),
1161 }, output_path)
dprankefe4602312015-04-08 16:20:351162 else:
dpranke7837fc362015-11-19 03:54:161163 self.WriteJSON({
1164 'status': 'No dependency',
1165 'compile_targets': [],
1166 'test_targets': [],
1167 }, output_path)
dprankecda00332015-04-11 04:18:321168
dprankee0547cd2015-09-15 01:27:401169 if self.args.verbose:
dprankecda00332015-04-11 04:18:321170 outp = json.loads(self.ReadFile(output_path))
1171 self.Print()
1172 self.Print('analyze output:')
1173 self.PrintJSON(outp)
1174 self.Print()
dprankefe4602312015-04-08 16:20:351175
1176 return 0
1177
dpranked8113582015-06-05 20:08:251178 def ReadInputJSON(self, required_keys):
dprankefe4602312015-04-08 16:20:351179 path = self.args.input_path[0]
dprankecda00332015-04-11 04:18:321180 output_path = self.args.output_path[0]
dprankefe4602312015-04-08 16:20:351181 if not self.Exists(path):
dprankecda00332015-04-11 04:18:321182 self.WriteFailureAndRaise('"%s" does not exist' % path, output_path)
dprankefe4602312015-04-08 16:20:351183
1184 try:
1185 inp = json.loads(self.ReadFile(path))
1186 except Exception as e:
1187 self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' %
dprankecda00332015-04-11 04:18:321188 (path, e), output_path)
dpranked8113582015-06-05 20:08:251189
1190 for k in required_keys:
1191 if not k in inp:
1192 self.WriteFailureAndRaise('input file is missing a "%s" key' % k,
1193 output_path)
dprankefe4602312015-04-08 16:20:351194
1195 return inp
1196
dpranked5b2b9432015-06-23 16:55:301197 def WriteFailureAndRaise(self, msg, output_path):
1198 if output_path:
dprankee0547cd2015-09-15 01:27:401199 self.WriteJSON({'error': msg}, output_path, force_verbose=True)
dprankefe4602312015-04-08 16:20:351200 raise MBErr(msg)
1201
dprankee0547cd2015-09-15 01:27:401202 def WriteJSON(self, obj, path, force_verbose=False):
dprankecda00332015-04-11 04:18:321203 try:
dprankee0547cd2015-09-15 01:27:401204 self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n',
1205 force_verbose=force_verbose)
dprankecda00332015-04-11 04:18:321206 except Exception as e:
1207 raise MBErr('Error %s writing to the output path "%s"' %
1208 (e, path))
dprankefe4602312015-04-08 16:20:351209
aneeshmde50f472016-04-01 01:13:101210 def CheckCompile(self, master, builder):
1211 url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1'
1212 url = urllib2.quote(url_template.format(master=master, builder=builder),
1213 safe=':/()?=')
1214 try:
1215 builds = json.loads(self.Fetch(url))
1216 except Exception as e:
1217 return str(e)
1218 successes = sorted(
1219 [int(x) for x in builds.keys() if "text" in builds[x] and
1220 cmp(builds[x]["text"][:2], ["build", "successful"]) == 0],
1221 reverse=True)
1222 if not successes:
1223 return "no successful builds"
1224 build = builds[str(successes[0])]
1225 step_names = set([step["name"] for step in build["steps"]])
1226 compile_indicators = set(["compile", "compile (with patch)", "analyze"])
1227 if compile_indicators & step_names:
1228 return "compiles"
1229 return "does not compile"
1230
dpranke3cec199c2015-09-22 23:29:021231 def PrintCmd(self, cmd, env):
1232 if self.platform == 'win32':
1233 env_prefix = 'set '
1234 env_quoter = QuoteForSet
1235 shell_quoter = QuoteForCmd
1236 else:
1237 env_prefix = ''
1238 env_quoter = pipes.quote
1239 shell_quoter = pipes.quote
1240
1241 def print_env(var):
1242 if env and var in env:
1243 self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var])))
1244
1245 print_env('GYP_CROSSCOMPILE')
1246 print_env('GYP_DEFINES')
1247
dpranke8c2cfd32015-09-17 20:12:331248 if cmd[0] == self.executable:
dprankefe4602312015-04-08 16:20:351249 cmd = ['python'] + cmd[1:]
dpranke3cec199c2015-09-22 23:29:021250 self.Print(*[shell_quoter(arg) for arg in cmd])
dprankefe4602312015-04-08 16:20:351251
dprankecda00332015-04-11 04:18:321252 def PrintJSON(self, obj):
1253 self.Print(json.dumps(obj, indent=2, sort_keys=True))
1254
dpranke030d7a6d2016-03-26 17:23:501255 def GNTargetName(self, target):
1256 return target[:-len('_apk')] if target.endswith('_apk') else target
dprankefe4602312015-04-08 16:20:351257
dpranke751516a2015-10-03 01:11:341258 def Build(self, target):
1259 build_dir = self.ToSrcRelPath(self.args.path[0])
1260 ninja_cmd = ['ninja', '-C', build_dir]
1261 if self.args.jobs:
1262 ninja_cmd.extend(['-j', '%d' % self.args.jobs])
1263 ninja_cmd.append(target)
1264 ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False)
1265 return ret
1266
1267 def Run(self, cmd, env=None, force_verbose=True, buffer_output=True):
dprankefe4602312015-04-08 16:20:351268 # This function largely exists so it can be overridden for testing.
dprankee0547cd2015-09-15 01:27:401269 if self.args.dryrun or self.args.verbose or force_verbose:
dpranke3cec199c2015-09-22 23:29:021270 self.PrintCmd(cmd, env)
dprankefe4602312015-04-08 16:20:351271 if self.args.dryrun:
1272 return 0, '', ''
dprankee0547cd2015-09-15 01:27:401273
dpranke751516a2015-10-03 01:11:341274 ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output)
dprankee0547cd2015-09-15 01:27:401275 if self.args.verbose or force_verbose:
dpranke751516a2015-10-03 01:11:341276 if ret:
1277 self.Print(' -> returned %d' % ret)
dprankefe4602312015-04-08 16:20:351278 if out:
dprankeee5b51f62015-04-09 00:03:221279 self.Print(out, end='')
dprankefe4602312015-04-08 16:20:351280 if err:
dprankeee5b51f62015-04-09 00:03:221281 self.Print(err, end='', file=sys.stderr)
dprankefe4602312015-04-08 16:20:351282 return ret, out, err
1283
dpranke751516a2015-10-03 01:11:341284 def Call(self, cmd, env=None, buffer_output=True):
1285 if buffer_output:
1286 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1287 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
1288 env=env)
1289 out, err = p.communicate()
1290 else:
1291 p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir,
1292 env=env)
1293 p.wait()
1294 out = err = ''
dprankefe4602312015-04-08 16:20:351295 return p.returncode, out, err
1296
1297 def ExpandUser(self, path):
1298 # This function largely exists so it can be overridden for testing.
1299 return os.path.expanduser(path)
1300
1301 def Exists(self, path):
1302 # This function largely exists so it can be overridden for testing.
1303 return os.path.exists(path)
1304
dpranke867bcf4a2016-03-14 22:28:321305 def Fetch(self, url):
dpranke030d7a6d2016-03-26 17:23:501306 # This function largely exists so it can be overridden for testing.
dpranke867bcf4a2016-03-14 22:28:321307 f = urllib2.urlopen(url)
1308 contents = f.read()
1309 f.close()
1310 return contents
1311
dprankec3441d12015-06-23 23:01:351312 def MaybeMakeDirectory(self, path):
1313 try:
1314 os.makedirs(path)
1315 except OSError, e:
1316 if e.errno != errno.EEXIST:
1317 raise
1318
dpranke8c2cfd32015-09-17 20:12:331319 def PathJoin(self, *comps):
1320 # This function largely exists so it can be overriden for testing.
1321 return os.path.join(*comps)
1322
dpranke030d7a6d2016-03-26 17:23:501323 def Print(self, *args, **kwargs):
1324 # This function largely exists so it can be overridden for testing.
1325 print(*args, **kwargs)
aneeshmde50f472016-04-01 01:13:101326 if kwargs.get('stream', sys.stdout) == sys.stdout:
1327 sys.stdout.flush()
dpranke030d7a6d2016-03-26 17:23:501328
dprankefe4602312015-04-08 16:20:351329 def ReadFile(self, path):
1330 # This function largely exists so it can be overriden for testing.
1331 with open(path) as fp:
1332 return fp.read()
1333
dpranke030d7a6d2016-03-26 17:23:501334 def RelPath(self, path, start='.'):
1335 # This function largely exists so it can be overriden for testing.
1336 return os.path.relpath(path, start)
1337
dprankef61de2f2015-05-14 04:09:561338 def RemoveFile(self, path):
1339 # This function largely exists so it can be overriden for testing.
1340 os.remove(path)
1341
dprankec161aa92015-09-14 20:21:131342 def RemoveDirectory(self, abs_path):
dpranke8c2cfd32015-09-17 20:12:331343 if self.platform == 'win32':
dprankec161aa92015-09-14 20:21:131344 # In other places in chromium, we often have to retry this command
1345 # because we're worried about other processes still holding on to
1346 # file handles, but when MB is invoked, it will be early enough in the
1347 # build that their should be no other processes to interfere. We
1348 # can change this if need be.
1349 self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path])
1350 else:
1351 shutil.rmtree(abs_path, ignore_errors=True)
1352
dprankef61de2f2015-05-14 04:09:561353 def TempFile(self, mode='w'):
1354 # This function largely exists so it can be overriden for testing.
1355 return tempfile.NamedTemporaryFile(mode=mode, delete=False)
1356
dprankee0547cd2015-09-15 01:27:401357 def WriteFile(self, path, contents, force_verbose=False):
dprankefe4602312015-04-08 16:20:351358 # This function largely exists so it can be overriden for testing.
dprankee0547cd2015-09-15 01:27:401359 if self.args.dryrun or self.args.verbose or force_verbose:
dpranked5b2b9432015-06-23 16:55:301360 self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path))
dprankefe4602312015-04-08 16:20:351361 with open(path, 'w') as fp:
1362 return fp.write(contents)
1363
dprankef61de2f2015-05-14 04:09:561364
dprankefe4602312015-04-08 16:20:351365class MBErr(Exception):
1366 pass
1367
1368
dpranke3cec199c2015-09-22 23:29:021369# See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful
1370# details of this next section, which handles escaping command lines
1371# so that they can be copied and pasted into a cmd window.
1372UNSAFE_FOR_SET = set('^<>&|')
1373UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%'))
1374ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"'))
1375
1376
1377def QuoteForSet(arg):
1378 if any(a in UNSAFE_FOR_SET for a in arg):
1379 arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg)
1380 return arg
1381
1382
1383def QuoteForCmd(arg):
1384 # First, escape the arg so that CommandLineToArgvW will parse it properly.
1385 # From //tools/gyp/pylib/gyp/msvs_emulation.py:23.
1386 if arg == '' or ' ' in arg or '"' in arg:
1387 quote_re = re.compile(r'(\\*)"')
1388 arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg))
1389
1390 # Then check to see if the arg contains any metacharacters other than
1391 # double quotes; if it does, quote everything (including the double
1392 # quotes) for safety.
1393 if any(a in UNSAFE_FOR_CMD for a in arg):
1394 arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg)
1395 return arg
1396
1397
dprankefe4602312015-04-08 16:20:351398if __name__ == '__main__':
dpranke255085e2016-03-16 05:23:591399 sys.exit(main(sys.argv[1:]))