#!/usr/bin/env python # Copyright 2016 the V8 project authors. All rights reserved. # Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """MB - the Meta-Build wrapper around GN. MB is a wrapper script for GN that can be used to generate build files for sets of canned configurations and analyze them. """ # for py2/py3 compatibility from __future__ import print_function import argparse import ast import errno import json import os import pipes import platform import pprint import re import shutil import sys import subprocess import tempfile import traceback import urllib2 from collections import OrderedDict CHROMIUM_SRC_DIR = os.path.dirname(os.path.dirname(os.path.dirname( os.path.abspath(__file__)))) sys.path = [os.path.join(CHROMIUM_SRC_DIR, 'build')] + sys.path import gn_helpers try: cmp # Python 2 except NameError: # Python 3 def cmp(x, y): # pylint: disable=redefined-builtin return (x > y) - (x < y) def main(args): mbw = MetaBuildWrapper() return mbw.Main(args) class MetaBuildWrapper(object): def __init__(self): self.chromium_src_dir = CHROMIUM_SRC_DIR self.default_config = os.path.join(self.chromium_src_dir, 'infra', 'mb', 'mb_config.pyl') self.default_isolate_map = os.path.join(self.chromium_src_dir, 'infra', 'mb', 'gn_isolate_map.pyl') self.executable = sys.executable self.platform = sys.platform self.sep = os.sep self.args = argparse.Namespace() self.configs = {} self.luci_tryservers = {} self.builder_groups = {} self.mixins = {} self.isolate_exe = 'isolate.exe' if self.platform.startswith( 'win') else 'isolate' def Main(self, args): self.ParseArgs(args) try: ret = self.args.func() if ret: self.DumpInputFiles() return ret except KeyboardInterrupt: self.Print('interrupted, exiting') return 130 except Exception: self.DumpInputFiles() s = traceback.format_exc() for l in s.splitlines(): self.Print(l) return 1 def ParseArgs(self, argv): def AddCommonOptions(subp): subp.add_argument('-b', '--builder', help='builder name to look up config from') subp.add_argument( '-m', '--builder-group', help='builder group name to look up config from') subp.add_argument('-c', '--config', help='configuration to analyze') subp.add_argument('--phase', help='optional phase name (used when builders ' 'do multiple compiles with different ' 'arguments in a single build)') subp.add_argument('-f', '--config-file', metavar='PATH', default=self.default_config, help='path to config file ' '(default is %(default)s)') subp.add_argument('-i', '--isolate-map-file', metavar='PATH', help='path to isolate map file ' '(default is %(default)s)', default=[], action='append', dest='isolate_map_files') subp.add_argument('-g', '--goma-dir', help='path to goma directory') subp.add_argument('--android-version-code', help='Sets GN arg android_default_version_code') subp.add_argument('--android-version-name', help='Sets GN arg android_default_version_name') subp.add_argument('-n', '--dryrun', action='store_true', help='Do a dry run (i.e., do nothing, just print ' 'the commands that will run)') subp.add_argument('-v', '--verbose', action='store_true', help='verbose logging') parser = argparse.ArgumentParser(prog='mb') subps = parser.add_subparsers() subp = subps.add_parser('analyze', help='analyze whether changes to a set of files ' 'will cause a set of binaries to be rebuilt.') AddCommonOptions(subp) subp.add_argument('path', nargs=1, help='path build was generated into.') subp.add_argument('input_path', nargs=1, help='path to a file containing the input arguments ' 'as a JSON object.') subp.add_argument('output_path', nargs=1, help='path to a file containing the output arguments ' 'as a JSON object.') subp.add_argument('--json-output', help='Write errors to json.output') subp.set_defaults(func=self.CmdAnalyze) subp = subps.add_parser('export', help='print out the expanded configuration for' 'each builder as a JSON object') subp.add_argument('-f', '--config-file', metavar='PATH', default=self.default_config, help='path to config file (default is %(default)s)') subp.add_argument('-g', '--goma-dir', help='path to goma directory') subp.set_defaults(func=self.CmdExport) subp = subps.add_parser('gen', help='generate a new set of build files') AddCommonOptions(subp) subp.add_argument('--swarming-targets-file', help='save runtime dependencies for targets listed ' 'in file.') subp.add_argument('--json-output', help='Write errors to json.output') subp.add_argument('path', nargs=1, help='path to generate build into') subp.set_defaults(func=self.CmdGen) subp = subps.add_parser('isolate', help='generate the .isolate files for a given' 'binary') AddCommonOptions(subp) subp.add_argument('path', nargs=1, help='path build was generated into') subp.add_argument('target', nargs=1, help='ninja target to generate the isolate for') subp.set_defaults(func=self.CmdIsolate) subp = subps.add_parser('lookup', help='look up the command for a given config or ' 'builder') AddCommonOptions(subp) subp.add_argument('--quiet', default=False, action='store_true', help='Print out just the arguments, ' 'do not emulate the output of the gen subcommand.') subp.add_argument('--recursive', default=False, action='store_true', help='Lookup arguments from imported files, ' 'implies --quiet') subp.set_defaults(func=self.CmdLookup) subp = subps.add_parser( 'run', help='build and run the isolated version of a ' 'binary', formatter_class=argparse.RawDescriptionHelpFormatter) subp.description = ( 'Build, isolate, and run the given binary with the command line\n' 'listed in the isolate. You may pass extra arguments after the\n' 'target; use "--" if the extra arguments need to include switches.\n' '\n' 'Examples:\n' '\n' ' % tools/mb/mb.py run -m chromium.linux -b "Linux Builder" \\\n' ' //out/Default content_browsertests\n' '\n' ' % tools/mb/mb.py run out/Default content_browsertests\n' '\n' ' % tools/mb/mb.py run out/Default content_browsertests -- \\\n' ' --test-launcher-retry-limit=0' '\n' ) AddCommonOptions(subp) subp.add_argument('-j', '--jobs', dest='jobs', type=int, help='Number of jobs to pass to ninja') subp.add_argument('--no-build', dest='build', default=True, action='store_false', help='Do not build, just isolate and run') subp.add_argument('path', nargs=1, help=('path to generate build into (or use).' ' This can be either a regular path or a ' 'GN-style source-relative path like ' '//out/Default.')) subp.add_argument('-s', '--swarmed', action='store_true', help='Run under swarming with the default dimensions') subp.add_argument('-d', '--dimension', default=[], action='append', nargs=2, dest='dimensions', metavar='FOO bar', help='dimension to filter on') subp.add_argument('--no-default-dimensions', action='store_false', dest='default_dimensions', default=True, help='Do not automatically add dimensions to the task') subp.add_argument('target', nargs=1, help='ninja target to build and run') subp.add_argument('extra_args', nargs='*', help=('extra args to pass to the isolate to run. Use ' '"--" as the first arg if you need to pass ' 'switches')) subp.set_defaults(func=self.CmdRun) subp = subps.add_parser('validate', help='validate the config file') subp.add_argument('-f', '--config-file', metavar='PATH', default=self.default_config, help='path to config file (default is %(default)s)') subp.set_defaults(func=self.CmdValidate) subp = subps.add_parser('gerrit-buildbucket-config', help='Print buildbucket.config for gerrit ' '(see MB user guide)') subp.add_argument('-f', '--config-file', metavar='PATH', default=self.default_config, help='path to config file (default is %(default)s)') subp.set_defaults(func=self.CmdBuildbucket) subp = subps.add_parser('help', help='Get help on a subcommand.') subp.add_argument(nargs='?', action='store', dest='subcommand', help='The command to get help for.') subp.set_defaults(func=self.CmdHelp) self.args = parser.parse_args(argv) def DumpInputFiles(self): def DumpContentsOfFilePassedTo(arg_name, path): if path and self.Exists(path): self.Print("\n# To recreate the file passed to %s:" % arg_name) self.Print("%% cat > %s < 7*1024: self.Print('WARNING: Too many compile targets were affected.') self.Print('WARNING: Building everything instead to avoid ' 'command-line length issues.') outp['compile_targets'] = all_input_compile_targets if 'test_targets' in gn_outp: outp['test_targets'] = [ labels_to_targets[label] for label in gn_outp['test_targets']] if self.args.verbose: self.Print() self.Print('analyze output:') self.PrintJSON(outp) self.Print() self.WriteJSON(outp, output_path) finally: if self.Exists(gn_input_path): self.RemoveFile(gn_input_path) if self.Exists(gn_output_path): self.RemoveFile(gn_output_path) return 0 def ReadInputJSON(self, required_keys): path = self.args.input_path[0] output_path = self.args.output_path[0] if not self.Exists(path): self.WriteFailureAndRaise('"%s" does not exist' % path, output_path) try: inp = json.loads(self.ReadFile(path)) except Exception as e: self.WriteFailureAndRaise('Failed to read JSON input from "%s": %s' % (path, e), output_path) for k in required_keys: if not k in inp: self.WriteFailureAndRaise('input file is missing a "%s" key' % k, output_path) return inp def WriteFailureAndRaise(self, msg, output_path): if output_path: self.WriteJSON({'error': msg}, output_path, force_verbose=True) raise MBErr(msg) def WriteJSON(self, obj, path, force_verbose=False): try: self.WriteFile(path, json.dumps(obj, indent=2, sort_keys=True) + '\n', force_verbose=force_verbose) except Exception as e: raise MBErr('Error %s writing to the output path "%s"' % (e, path)) def CheckCompile(self, builder_group, builder): url_template = self.args.url_template + '/{builder}/builds/_all?as_text=1' url = urllib2.quote( url_template.format(builder_group=builder_group, builder=builder), safe=':/()?=') try: builds = json.loads(self.Fetch(url)) except Exception as e: return str(e) successes = sorted( [int(x) for x in builds.keys() if "text" in builds[x] and cmp(builds[x]["text"][:2], ["build", "successful"]) == 0], reverse=True) if not successes: return "no successful builds" build = builds[str(successes[0])] step_names = set([step["name"] for step in build["steps"]]) compile_indicators = set(["compile", "compile (with patch)", "analyze"]) if compile_indicators & step_names: return "compiles" return "does not compile" def PrintCmd(self, cmd, env): if self.platform == 'win32': env_prefix = 'set ' env_quoter = QuoteForSet shell_quoter = QuoteForCmd else: env_prefix = '' env_quoter = pipes.quote shell_quoter = pipes.quote def print_env(var): if env and var in env: self.Print('%s%s=%s' % (env_prefix, var, env_quoter(env[var]))) print_env('LLVM_FORCE_HEAD_REVISION') if cmd[0] == self.executable: cmd = ['python'] + cmd[1:] self.Print(*[shell_quoter(arg) for arg in cmd]) def PrintJSON(self, obj): self.Print(json.dumps(obj, indent=2, sort_keys=True)) def Build(self, target): build_dir = self.ToSrcRelPath(self.args.path[0]) ninja_cmd = ['ninja', '-C', build_dir] if self.args.jobs: ninja_cmd.extend(['-j', '%d' % self.args.jobs]) ninja_cmd.append(target) ret, _, _ = self.Run(ninja_cmd, force_verbose=False, buffer_output=False) return ret def Run(self, cmd, env=None, force_verbose=True, buffer_output=True): # This function largely exists so it can be overridden for testing. if self.args.dryrun or self.args.verbose or force_verbose: self.PrintCmd(cmd, env) if self.args.dryrun: return 0, '', '' ret, out, err = self.Call(cmd, env=env, buffer_output=buffer_output) if self.args.verbose or force_verbose: if ret: self.Print(' -> returned %d' % ret) if out: self.Print(out, end='') if err: self.Print(err, end='', file=sys.stderr) return ret, out, err def Call(self, cmd, env=None, buffer_output=True): if buffer_output: p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) out, err = p.communicate() else: p = subprocess.Popen(cmd, shell=False, cwd=self.chromium_src_dir, env=env) p.wait() out = err = '' return p.returncode, out, err def ExpandUser(self, path): # This function largely exists so it can be overridden for testing. return os.path.expanduser(path) def Exists(self, path): # This function largely exists so it can be overridden for testing. return os.path.exists(path) def Fetch(self, url): # This function largely exists so it can be overridden for testing. f = urllib2.urlopen(url) contents = f.read() f.close() return contents def MaybeMakeDirectory(self, path): try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: raise def PathJoin(self, *comps): # This function largely exists so it can be overriden for testing. return os.path.join(*comps) def Print(self, *args, **kwargs): # This function largely exists so it can be overridden for testing. print(*args, **kwargs) if kwargs.get('stream', sys.stdout) == sys.stdout: sys.stdout.flush() def ReadFile(self, path): # This function largely exists so it can be overriden for testing. with open(path) as fp: return fp.read() def RelPath(self, path, start='.'): # This function largely exists so it can be overriden for testing. return os.path.relpath(path, start) def RemoveFile(self, path): # This function largely exists so it can be overriden for testing. os.remove(path) def RemoveDirectory(self, abs_path): if self.platform == 'win32': # In other places in chromium, we often have to retry this command # because we're worried about other processes still holding on to # file handles, but when MB is invoked, it will be early enough in the # build that their should be no other processes to interfere. We # can change this if need be. self.Run(['cmd.exe', '/c', 'rmdir', '/q', '/s', abs_path]) else: shutil.rmtree(abs_path, ignore_errors=True) def TempFile(self, mode='w'): # This function largely exists so it can be overriden for testing. return tempfile.NamedTemporaryFile(mode=mode, delete=False) def WriteFile(self, path, contents, force_verbose=False): # This function largely exists so it can be overriden for testing. if self.args.dryrun or self.args.verbose or force_verbose: self.Print('\nWriting """\\\n%s""" to %s.\n' % (contents, path)) with open(path, 'w') as fp: return fp.write(contents) class MBErr(Exception): pass # See http://goo.gl/l5NPDW and http://goo.gl/4Diozm for the painful # details of this next section, which handles escaping command lines # so that they can be copied and pasted into a cmd window. UNSAFE_FOR_SET = set('^<>&|') UNSAFE_FOR_CMD = UNSAFE_FOR_SET.union(set('()%')) ALL_META_CHARS = UNSAFE_FOR_CMD.union(set('"')) def QuoteForSet(arg): if any(a in UNSAFE_FOR_SET for a in arg): arg = ''.join('^' + a if a in UNSAFE_FOR_SET else a for a in arg) return arg def QuoteForCmd(arg): # First, escape the arg so that CommandLineToArgvW will parse it properly. if arg == '' or ' ' in arg or '"' in arg: quote_re = re.compile(r'(\\*)"') arg = '"%s"' % (quote_re.sub(lambda mo: 2 * mo.group(1) + '\\"', arg)) # Then check to see if the arg contains any metacharacters other than # double quotes; if it does, quote everything (including the double # quotes) for safety. if any(a in UNSAFE_FOR_CMD for a in arg): arg = ''.join('^' + a if a in ALL_META_CHARS else a for a in arg) return arg if __name__ == '__main__': sys.exit(main(sys.argv[1:]))