mach_bootstrap.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. # This Source Code Form is subject to the terms of the Mozilla Public
  2. # License, v. 2.0. If a copy of the MPL was not distributed with this
  3. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  4. from __future__ import print_function, unicode_literals
  5. import errno
  6. import json
  7. import os
  8. import platform
  9. import random
  10. import subprocess
  11. import sys
  12. import uuid
  13. import __builtin__
  14. from types import ModuleType
  15. STATE_DIR_FIRST_RUN = '''
  16. mach and the build system store shared state in a common directory on the
  17. filesystem. The following directory will be created:
  18. {userdir}
  19. If you would like to use a different directory, hit CTRL+c and set the
  20. MOZBUILD_STATE_PATH environment variable to the directory you would like to
  21. use and re-run mach. For this change to take effect forever, you'll likely
  22. want to export this environment variable from your shell's init scripts.
  23. Press ENTER/RETURN to continue or CTRL+c to abort.
  24. '''.lstrip()
  25. # TODO Bug 794506 Integrate with the in-tree virtualenv configuration.
  26. SEARCH_PATHS = [
  27. 'python/mach',
  28. 'python/mozboot',
  29. 'python/mozbuild',
  30. 'python/mozlint',
  31. 'python/mozversioncontrol',
  32. 'python/blessings',
  33. 'python/compare-locales',
  34. 'python/configobj',
  35. 'python/futures',
  36. 'python/jsmin',
  37. 'python/psutil',
  38. 'python/pylru',
  39. 'python/which',
  40. 'python/pystache',
  41. 'python/pyyaml/lib',
  42. 'python/requests',
  43. 'python/slugid',
  44. 'python/py',
  45. 'python/pytest',
  46. 'python/redo',
  47. 'python/voluptuous',
  48. 'build',
  49. 'build/pymake',
  50. 'config',
  51. 'dom/bindings',
  52. 'dom/bindings/parser',
  53. 'dom/media/test/external',
  54. 'layout/tools/reftest',
  55. 'other-licenses/ply',
  56. 'taskcluster',
  57. 'testing',
  58. 'testing/firefox-ui/harness',
  59. 'testing/marionette/client',
  60. 'testing/marionette/harness',
  61. 'testing/marionette/harness/marionette_harness/runner/mixins/browsermob-proxy-py',
  62. 'testing/marionette/puppeteer/firefox',
  63. 'testing/mozbase/mozcrash',
  64. 'testing/mozbase/mozdebug',
  65. 'testing/mozbase/mozdevice',
  66. 'testing/mozbase/mozfile',
  67. 'testing/mozbase/mozhttpd',
  68. 'testing/mozbase/mozinfo',
  69. 'testing/mozbase/mozinstall',
  70. 'testing/mozbase/mozleak',
  71. 'testing/mozbase/mozlog',
  72. 'testing/mozbase/moznetwork',
  73. 'testing/mozbase/mozprocess',
  74. 'testing/mozbase/mozprofile',
  75. 'testing/mozbase/mozrunner',
  76. 'testing/mozbase/mozsystemmonitor',
  77. 'testing/mozbase/mozscreenshot',
  78. 'testing/mozbase/moztest',
  79. 'testing/mozbase/mozversion',
  80. 'testing/mozbase/manifestparser',
  81. 'testing/taskcluster',
  82. 'testing/tools/autotry',
  83. 'testing/xpcshell',
  84. 'xpcom/idl-parser',
  85. ]
  86. # Individual files providing mach commands.
  87. MACH_MODULES = [
  88. 'build/valgrind/mach_commands.py',
  89. 'devtools/shared/css/generated/mach_commands.py',
  90. 'dom/bindings/mach_commands.py',
  91. 'dom/media/test/external/mach_commands.py',
  92. 'layout/tools/reftest/mach_commands.py',
  93. 'python/mach_commands.py',
  94. 'python/mach/mach/commands/commandinfo.py',
  95. 'python/mach/mach/commands/settings.py',
  96. 'python/compare-locales/mach_commands.py',
  97. 'python/mozboot/mozboot/mach_commands.py',
  98. 'python/mozbuild/mozbuild/mach_commands.py',
  99. 'python/mozbuild/mozbuild/backend/mach_commands.py',
  100. 'python/mozbuild/mozbuild/compilation/codecomplete.py',
  101. 'python/mozbuild/mozbuild/frontend/mach_commands.py',
  102. 'services/common/tests/mach_commands.py',
  103. 'taskcluster/mach_commands.py',
  104. 'testing/firefox-ui/mach_commands.py',
  105. 'testing/mach_commands.py',
  106. 'testing/marionette/mach_commands.py',
  107. 'testing/mochitest/mach_commands.py',
  108. 'testing/mozharness/mach_commands.py',
  109. 'testing/talos/mach_commands.py',
  110. 'testing/xpcshell/mach_commands.py',
  111. 'tools/docs/mach_commands.py',
  112. 'tools/lint/mach_commands.py',
  113. 'tools/mach_commands.py',
  114. 'tools/power/mach_commands.py',
  115. ]
  116. if os.path.exists('addon-sdk/mach_commands.py'):
  117. MACH_MODULES += [ 'addon-sdk/mach_commands.py' ]
  118. CATEGORIES = {
  119. 'build': {
  120. 'short': 'Build Commands',
  121. 'long': 'Interact with the build system',
  122. 'priority': 80,
  123. },
  124. 'post-build': {
  125. 'short': 'Post-build Commands',
  126. 'long': 'Common actions performed after completing a build.',
  127. 'priority': 70,
  128. },
  129. 'testing': {
  130. 'short': 'Testing',
  131. 'long': 'Run tests.',
  132. 'priority': 60,
  133. },
  134. 'ci': {
  135. 'short': 'CI',
  136. 'long': 'Taskcluster commands',
  137. 'priority': 59
  138. },
  139. 'devenv': {
  140. 'short': 'Development Environment',
  141. 'long': 'Set up and configure your development environment.',
  142. 'priority': 50,
  143. },
  144. 'build-dev': {
  145. 'short': 'Low-level Build System Interaction',
  146. 'long': 'Interact with specific parts of the build system.',
  147. 'priority': 20,
  148. },
  149. 'misc': {
  150. 'short': 'Potpourri',
  151. 'long': 'Potent potables and assorted snacks.',
  152. 'priority': 10,
  153. },
  154. 'disabled': {
  155. 'short': 'Disabled',
  156. 'long': 'The disabled commands are hidden by default. Use -v to display them. These commands are unavailable for your current context, run "mach <command>" to see why.',
  157. 'priority': 0,
  158. }
  159. }
  160. # We submit data to telemetry approximately every this many mach invocations
  161. TELEMETRY_SUBMISSION_FREQUENCY = 10
  162. def bootstrap(topsrcdir, mozilla_dir=None):
  163. if mozilla_dir is None:
  164. mozilla_dir = topsrcdir
  165. # Ensure we are running Python 2.7+. We put this check here so we generate a
  166. # user-friendly error message rather than a cryptic stack trace on module
  167. # import.
  168. if sys.version_info[0] != 2 or sys.version_info[1] < 7:
  169. print('Python 2.7 or above (but not Python 3) is required to run mach.')
  170. print('You are running Python', platform.python_version())
  171. sys.exit(1)
  172. # Global build system and mach state is stored in a central directory. By
  173. # default, this is ~/.mozbuild. However, it can be defined via an
  174. # environment variable. We detect first run (by lack of this directory
  175. # existing) and notify the user that it will be created. The logic for
  176. # creation is much simpler for the "advanced" environment variable use
  177. # case. For default behavior, we educate users and give them an opportunity
  178. # to react. We always exit after creating the directory because users don't
  179. # like surprises.
  180. sys.path[0:0] = [os.path.join(mozilla_dir, path) for path in SEARCH_PATHS]
  181. import mach.main
  182. from mozboot.util import get_state_dir
  183. def telemetry_handler(context, data):
  184. # We have not opted-in to telemetry
  185. if 'BUILD_SYSTEM_TELEMETRY' not in os.environ:
  186. return
  187. telemetry_dir = os.path.join(get_state_dir()[0], 'telemetry')
  188. try:
  189. os.mkdir(telemetry_dir)
  190. except OSError as e:
  191. if e.errno != errno.EEXIST:
  192. raise
  193. outgoing_dir = os.path.join(telemetry_dir, 'outgoing')
  194. try:
  195. os.mkdir(outgoing_dir)
  196. except OSError as e:
  197. if e.errno != errno.EEXIST:
  198. raise
  199. # Add common metadata to help submit sorted data later on.
  200. data['argv'] = sys.argv
  201. data.setdefault('system', {}).update(dict(
  202. architecture=list(platform.architecture()),
  203. machine=platform.machine(),
  204. python_version=platform.python_version(),
  205. release=platform.release(),
  206. system=platform.system(),
  207. version=platform.version(),
  208. ))
  209. if platform.system() == 'Linux':
  210. dist = list(platform.linux_distribution())
  211. data['system']['linux_distribution'] = dist
  212. elif platform.system() == 'Windows':
  213. win32_ver=list((platform.win32_ver())),
  214. data['system']['win32_ver'] = win32_ver
  215. elif platform.system() == 'Darwin':
  216. # mac version is a special Cupertino snowflake
  217. r, v, m = platform.mac_ver()
  218. data['system']['mac_ver'] = [r, list(v), m]
  219. with open(os.path.join(outgoing_dir, str(uuid.uuid4()) + '.json'),
  220. 'w') as f:
  221. json.dump(data, f, sort_keys=True)
  222. def should_skip_dispatch(context, handler):
  223. # The user is performing a maintenance command.
  224. if handler.name in ('bootstrap', 'doctor', 'mach-commands', 'mercurial-setup'):
  225. return True
  226. # We are running in automation.
  227. if 'MOZ_AUTOMATION' in os.environ or 'TASK_ID' in os.environ:
  228. return True
  229. # The environment is likely a machine invocation.
  230. if sys.stdin.closed or not sys.stdin.isatty():
  231. return True
  232. return False
  233. def post_dispatch_handler(context, handler, args):
  234. """Perform global operations after command dispatch.
  235. For now, we will use this to handle build system telemetry.
  236. """
  237. # Don't do anything when...
  238. if should_skip_dispatch(context, handler):
  239. return
  240. # We call mach environment in client.mk which would cause the
  241. # data submission below to block the forward progress of make.
  242. if handler.name in ('environment'):
  243. return
  244. # We have not opted-in to telemetry
  245. if 'BUILD_SYSTEM_TELEMETRY' not in os.environ:
  246. return
  247. # Every n-th operation
  248. if random.randint(1, TELEMETRY_SUBMISSION_FREQUENCY) != 1:
  249. return
  250. with open(os.devnull, 'wb') as devnull:
  251. subprocess.Popen([sys.executable,
  252. os.path.join(topsrcdir, 'build',
  253. 'submit_telemetry_data.py'),
  254. get_state_dir()[0]],
  255. stdout=devnull, stderr=devnull)
  256. def populate_context(context, key=None):
  257. if key is None:
  258. return
  259. if key == 'state_dir':
  260. state_dir, is_environ = get_state_dir()
  261. if is_environ:
  262. if not os.path.exists(state_dir):
  263. print('Creating global state directory from environment variable: %s'
  264. % state_dir)
  265. os.makedirs(state_dir, mode=0o770)
  266. else:
  267. if not os.path.exists(state_dir):
  268. print(STATE_DIR_FIRST_RUN.format(userdir=state_dir))
  269. try:
  270. sys.stdin.readline()
  271. except KeyboardInterrupt:
  272. sys.exit(1)
  273. print('\nCreating default state directory: %s' % state_dir)
  274. os.makedirs(state_dir, mode=0o770)
  275. return state_dir
  276. if key == 'topdir':
  277. return topsrcdir
  278. if key == 'telemetry_handler':
  279. return telemetry_handler
  280. if key == 'post_dispatch_handler':
  281. return post_dispatch_handler
  282. raise AttributeError(key)
  283. mach = mach.main.Mach(os.getcwd())
  284. mach.populate_context_handler = populate_context
  285. if not mach.settings_paths:
  286. # default global machrc location
  287. mach.settings_paths.append(get_state_dir()[0])
  288. # always load local repository configuration
  289. mach.settings_paths.append(mozilla_dir)
  290. for category, meta in CATEGORIES.items():
  291. mach.define_category(category, meta['short'], meta['long'],
  292. meta['priority'])
  293. for path in MACH_MODULES:
  294. mach.load_commands_from_file(os.path.join(mozilla_dir, path))
  295. return mach
  296. # Hook import such that .pyc/.pyo files without a corresponding .py file in
  297. # the source directory are essentially ignored. See further below for details
  298. # and caveats.
  299. # Objdirs outside the source directory are ignored because in most cases, if
  300. # a .pyc/.pyo file exists there, a .py file will be next to it anyways.
  301. class ImportHook(object):
  302. def __init__(self, original_import):
  303. self._original_import = original_import
  304. # Assume the source directory is the parent directory of the one
  305. # containing this file.
  306. self._source_dir = os.path.normcase(os.path.abspath(
  307. os.path.dirname(os.path.dirname(__file__)))) + os.sep
  308. self._modules = set()
  309. def __call__(self, name, globals=None, locals=None, fromlist=None,
  310. level=-1):
  311. # name might be a relative import. Instead of figuring out what that
  312. # resolves to, which is complex, just rely on the real import.
  313. # Since we don't know the full module name, we can't check sys.modules,
  314. # so we need to keep track of which modules we've already seen to avoid
  315. # to stat() them again when they are imported multiple times.
  316. module = self._original_import(name, globals, locals, fromlist, level)
  317. # Some tests replace modules in sys.modules with non-module instances.
  318. if not isinstance(module, ModuleType):
  319. return module
  320. resolved_name = module.__name__
  321. if resolved_name in self._modules:
  322. return module
  323. self._modules.add(resolved_name)
  324. # Builtin modules don't have a __file__ attribute.
  325. if not hasattr(module, '__file__'):
  326. return module
  327. # Note: module.__file__ is not always absolute.
  328. path = os.path.normcase(os.path.abspath(module.__file__))
  329. # Note: we could avoid normcase and abspath above for non pyc/pyo
  330. # files, but those are actually rare, so it doesn't really matter.
  331. if not path.endswith(('.pyc', '.pyo')):
  332. return module
  333. # Ignore modules outside our source directory
  334. if not path.startswith(self._source_dir):
  335. return module
  336. # If there is no .py corresponding to the .pyc/.pyo module we're
  337. # loading, remove the .pyc/.pyo file, and reload the module.
  338. # Since we already loaded the .pyc/.pyo module, if it had side
  339. # effects, they will have happened already, and loading the module
  340. # with the same name, from another directory may have the same side
  341. # effects (or different ones). We assume it's not a problem for the
  342. # python modules under our source directory (either because it
  343. # doesn't happen or because it doesn't matter).
  344. if not os.path.exists(module.__file__[:-1]):
  345. os.remove(module.__file__)
  346. del sys.modules[module.__name__]
  347. module = self(name, globals, locals, fromlist, level)
  348. return module
  349. # Install our hook
  350. __builtin__.__import__ = ImportHook(__builtin__.__import__)