Source code

Revision control

Other Tools

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
5
from __future__ import print_function, unicode_literals
6
7
import errno
8
import json
9
import os
10
import platform
11
import subprocess
12
import sys
13
import uuid
14
if sys.version_info[0] < 3:
15
import __builtin__ as builtins
16
else:
17
import builtins
18
19
from types import ModuleType
20
21
22
STATE_DIR_FIRST_RUN = '''
23
mach and the build system store shared state in a common directory on the
24
filesystem. The following directory will be created:
25
26
{userdir}
27
28
If you would like to use a different directory, hit CTRL+c and set the
29
MOZBUILD_STATE_PATH environment variable to the directory you would like to
30
use and re-run mach. For this change to take effect forever, you'll likely
31
want to export this environment variable from your shell's init scripts.
32
33
Press ENTER/RETURN to continue or CTRL+c to abort.
34
'''.lstrip()
35
36
37
# Individual files providing mach commands.
38
MACH_MODULES = [
39
'build/valgrind/mach_commands.py',
40
'devtools/shared/css/generated/mach_commands.py',
41
'dom/bindings/mach_commands.py',
42
'layout/tools/reftest/mach_commands.py',
43
'mobile/android/mach_commands.py',
44
'python/mach/mach/commands/commandinfo.py',
45
'python/mach/mach/commands/settings.py',
46
'python/mach_commands.py',
47
'python/mozboot/mozboot/mach_commands.py',
48
'python/mozbuild/mozbuild/artifact_commands.py',
49
'python/mozbuild/mozbuild/backend/mach_commands.py',
50
'python/mozbuild/mozbuild/build_commands.py',
51
'python/mozbuild/mozbuild/code-analysis/mach_commands.py',
52
'python/mozbuild/mozbuild/compilation/codecomplete.py',
53
'python/mozbuild/mozbuild/frontend/mach_commands.py',
54
'python/mozbuild/mozbuild/mach_commands.py',
55
'python/mozrelease/mozrelease/mach_commands.py',
56
'python/safety/mach_commands.py',
57
'remote/mach_commands.py',
58
'taskcluster/mach_commands.py',
59
'testing/awsy/mach_commands.py',
60
'testing/firefox-ui/mach_commands.py',
61
'testing/geckodriver/mach_commands.py',
62
'testing/mach_commands.py',
63
'testing/marionette/mach_commands.py',
64
'testing/mochitest/mach_commands.py',
65
'testing/mozharness/mach_commands.py',
66
'testing/raptor/mach_commands.py',
67
'testing/talos/mach_commands.py',
68
'testing/tps/mach_commands.py',
69
'testing/web-platform/mach_commands.py',
70
'testing/xpcshell/mach_commands.py',
71
'toolkit/components/telemetry/tests/marionette/mach_commands.py',
72
'tools/browsertime/mach_commands.py',
73
'tools/compare-locales/mach_commands.py',
74
'tools/docs/mach_commands.py',
75
'tools/lint/mach_commands.py',
76
'tools/mach_commands.py',
77
'tools/power/mach_commands.py',
78
'tools/tryselect/mach_commands.py',
79
'tools/vcs/mach_commands.py',
80
]
81
82
83
CATEGORIES = {
84
'build': {
85
'short': 'Build Commands',
86
'long': 'Interact with the build system',
87
'priority': 80,
88
},
89
'post-build': {
90
'short': 'Post-build Commands',
91
'long': 'Common actions performed after completing a build.',
92
'priority': 70,
93
},
94
'testing': {
95
'short': 'Testing',
96
'long': 'Run tests.',
97
'priority': 60,
98
},
99
'ci': {
100
'short': 'CI',
101
'long': 'Taskcluster commands',
102
'priority': 59,
103
},
104
'devenv': {
105
'short': 'Development Environment',
106
'long': 'Set up and configure your development environment.',
107
'priority': 50,
108
},
109
'build-dev': {
110
'short': 'Low-level Build System Interaction',
111
'long': 'Interact with specific parts of the build system.',
112
'priority': 20,
113
},
114
'misc': {
115
'short': 'Potpourri',
116
'long': 'Potent potables and assorted snacks.',
117
'priority': 10,
118
},
119
'release': {
120
'short': 'Release automation',
121
'long': 'Commands for used in release automation.',
122
'priority': 5,
123
},
124
'disabled': {
125
'short': 'Disabled',
126
'long': 'The disabled commands are hidden by default. Use -v to display them. '
127
'These commands are unavailable for your current context, '
128
'run "mach <command>" to see why.',
129
'priority': 0,
130
},
131
}
132
133
134
def search_path(mozilla_dir, packages_txt):
135
with open(os.path.join(mozilla_dir, packages_txt)) as f:
136
packages = [line.rstrip().split(':') for line in f]
137
138
def handle_package(package):
139
if package[0] == 'optional':
140
try:
141
for path in handle_package(package[1:]):
142
yield path
143
except Exception:
144
pass
145
146
if package[0] in ('windows', '!windows'):
147
for_win = not package[0].startswith('!')
148
is_win = sys.platform == 'win32'
149
if is_win == for_win:
150
for path in handle_package(package[1:]):
151
yield path
152
153
if package[0] in ('python2', 'python3'):
154
for_python3 = package[0].endswith('3')
155
is_python3 = sys.version_info[0] > 2
156
if is_python3 == for_python3:
157
for path in handle_package(package[1:]):
158
yield path
159
160
if package[0] == 'packages.txt':
161
assert len(package) == 2
162
for p in search_path(mozilla_dir, package[1]):
163
yield os.path.join(mozilla_dir, p)
164
165
if package[0].endswith('.pth'):
166
assert len(package) == 2
167
yield os.path.join(mozilla_dir, package[1])
168
169
for package in packages:
170
for path in handle_package(package):
171
yield path
172
173
174
def bootstrap(topsrcdir, mozilla_dir=None):
175
if mozilla_dir is None:
176
mozilla_dir = topsrcdir
177
178
# Ensure we are running Python 2.7 or 3.5+. We put this check here so we
179
# generate a user-friendly error message rather than a cryptic stack trace
180
# on module import.
181
major, minor = sys.version_info[:2]
182
if (major == 2 and minor < 7) or (major == 3 and minor < 5):
183
print('Python 2.7 or Python 3.5+ is required to run mach.')
184
print('You are running Python', platform.python_version())
185
sys.exit(1)
186
187
# Global build system and mach state is stored in a central directory. By
188
# default, this is ~/.mozbuild. However, it can be defined via an
189
# environment variable. We detect first run (by lack of this directory
190
# existing) and notify the user that it will be created. The logic for
191
# creation is much simpler for the "advanced" environment variable use
192
# case. For default behavior, we educate users and give them an opportunity
193
# to react. We always exit after creating the directory because users don't
194
# like surprises.
195
sys.path[0:0] = [os.path.join(mozilla_dir, path)
196
for path in search_path(mozilla_dir,
197
'build/virtualenv_packages.txt')]
198
import mach.base
199
import mach.main
200
from mach.util import setenv
201
from mozboot.util import get_state_dir
202
203
from mozbuild.util import patch_main
204
patch_main()
205
206
def resolve_repository():
207
import mozversioncontrol
208
209
try:
210
# This API doesn't respect the vcs binary choices from configure.
211
# If we ever need to use the VCS binary here, consider something
212
# more robust.
213
return mozversioncontrol.get_repository_object(path=mozilla_dir)
214
except (mozversioncontrol.InvalidRepoPath,
215
mozversioncontrol.MissingVCSTool):
216
return None
217
218
def should_skip_telemetry_submission(handler):
219
# The user is performing a maintenance command.
220
if handler.name in ('bootstrap', 'doctor', 'mach-commands', 'vcs-setup',
221
# We call mach environment in client.mk which would cause the
222
# data submission to block the forward progress of make.
223
'environment'):
224
return True
225
226
# Never submit data when running in automation or when running tests.
227
if any(e in os.environ for e in ('MOZ_AUTOMATION', 'TASK_ID', 'MACH_TELEMETRY_NO_SUBMIT')):
228
return True
229
230
return False
231
232
def post_dispatch_handler(context, handler, instance, result,
233
start_time, end_time, depth, args):
234
"""Perform global operations after command dispatch.
235
236
237
For now, we will use this to handle build system telemetry.
238
"""
239
# Don't write telemetry data if this mach command was invoked as part of another
240
# mach command.
241
if depth != 1 or os.environ.get('MACH_MAIN_PID') != str(os.getpid()):
242
return
243
244
# Don't write telemetry data for 'mach' when 'DISABLE_TELEMETRY' is set.
245
if os.environ.get('DISABLE_TELEMETRY') == '1':
246
return
247
248
# We have not opted-in to telemetry
249
if not context.settings.build.telemetry:
250
return
251
252
from mozbuild.telemetry import gather_telemetry
253
from mozbuild.base import MozbuildObject
254
import mozpack.path as mozpath
255
256
if not isinstance(instance, MozbuildObject):
257
instance = MozbuildObject.from_environment()
258
259
try:
260
substs = instance.substs
261
except Exception:
262
substs = {}
263
264
command_attrs = getattr(context, 'command_attrs', {})
265
266
# We gather telemetry for every operation.
267
paths = {
268
instance.topsrcdir: '$topsrcdir/',
269
instance.topobjdir: '$topobjdir/',
270
mozpath.normpath(os.path.expanduser('~')): '$HOME/',
271
}
272
# This might override one of the existing entries, that's OK.
273
# We don't use a sigil here because we treat all arguments as potentially relative
274
# paths, so we'd like to get them back as they were specified.
275
paths[mozpath.normpath(os.getcwd())] = ''
276
data = gather_telemetry(command=handler.name, success=(result == 0),
277
start_time=start_time, end_time=end_time,
278
mach_context=context, substs=substs,
279
command_attrs=command_attrs, paths=paths)
280
if data:
281
telemetry_dir = os.path.join(get_state_dir(), 'telemetry')
282
try:
283
os.mkdir(telemetry_dir)
284
except OSError as e:
285
if e.errno != errno.EEXIST:
286
raise
287
outgoing_dir = os.path.join(telemetry_dir, 'outgoing')
288
try:
289
os.mkdir(outgoing_dir)
290
except OSError as e:
291
if e.errno != errno.EEXIST:
292
raise
293
294
with open(os.path.join(outgoing_dir, str(uuid.uuid4()) + '.json'),
295
'w') as f:
296
json.dump(data, f, sort_keys=True)
297
298
if should_skip_telemetry_submission(handler):
299
return True
300
301
state_dir = get_state_dir()
302
303
machpath = os.path.join(instance.topsrcdir, 'mach')
304
with open(os.devnull, 'wb') as devnull:
305
subprocess.Popen([sys.executable, machpath, 'python',
306
'--no-virtualenv',
307
os.path.join(topsrcdir, 'build',
308
'submit_telemetry_data.py'),
309
state_dir],
310
stdout=devnull, stderr=devnull)
311
312
def populate_context(context, key=None):
313
if key is None:
314
return
315
if key == 'state_dir':
316
state_dir = get_state_dir()
317
if state_dir == os.environ.get('MOZBUILD_STATE_PATH'):
318
if not os.path.exists(state_dir):
319
print('Creating global state directory from environment variable: %s'
320
% state_dir)
321
os.makedirs(state_dir, mode=0o770)
322
else:
323
if not os.path.exists(state_dir):
324
if not os.environ.get('MOZ_AUTOMATION'):
325
print(STATE_DIR_FIRST_RUN.format(userdir=state_dir))
326
try:
327
sys.stdin.readline()
328
except KeyboardInterrupt:
329
sys.exit(1)
330
331
print('\nCreating default state directory: %s' % state_dir)
332
os.makedirs(state_dir, mode=0o770)
333
334
return state_dir
335
336
if key == 'local_state_dir':
337
return get_state_dir(srcdir=True)
338
339
if key == 'topdir':
340
return topsrcdir
341
342
if key == 'post_dispatch_handler':
343
return post_dispatch_handler
344
345
if key == 'repository':
346
return resolve_repository()
347
348
raise AttributeError(key)
349
350
# Note which process is top-level so that recursive mach invocations can avoid writing
351
# telemetry data.
352
if 'MACH_MAIN_PID' not in os.environ:
353
setenv('MACH_MAIN_PID', str(os.getpid()))
354
355
driver = mach.main.Mach(os.getcwd())
356
driver.populate_context_handler = populate_context
357
358
if not driver.settings_paths:
359
# default global machrc location
360
driver.settings_paths.append(get_state_dir())
361
# always load local repository configuration
362
driver.settings_paths.append(mozilla_dir)
363
364
for category, meta in CATEGORIES.items():
365
driver.define_category(category, meta['short'], meta['long'],
366
meta['priority'])
367
368
repo = resolve_repository()
369
370
for path in MACH_MODULES:
371
# Sparse checkouts may not have all mach_commands.py files. Ignore
372
# errors from missing files.
373
try:
374
driver.load_commands_from_file(os.path.join(mozilla_dir, path))
375
except mach.base.MissingFileError:
376
if not repo or not repo.sparse_checkout_present():
377
raise
378
379
return driver
380
381
382
# Hook import such that .pyc/.pyo files without a corresponding .py file in
383
# the source directory are essentially ignored. See further below for details
384
# and caveats.
385
# Objdirs outside the source directory are ignored because in most cases, if
386
# a .pyc/.pyo file exists there, a .py file will be next to it anyways.
387
class ImportHook(object):
388
def __init__(self, original_import):
389
self._original_import = original_import
390
# Assume the source directory is the parent directory of the one
391
# containing this file.
392
self._source_dir = os.path.normcase(os.path.abspath(
393
os.path.dirname(os.path.dirname(__file__)))) + os.sep
394
self._modules = set()
395
396
def __call__(self, name, globals=None, locals=None, fromlist=None,
397
level=-1):
398
if sys.version_info[0] >= 3 and level < 0:
399
level = 0
400
401
# name might be a relative import. Instead of figuring out what that
402
# resolves to, which is complex, just rely on the real import.
403
# Since we don't know the full module name, we can't check sys.modules,
404
# so we need to keep track of which modules we've already seen to avoid
405
# to stat() them again when they are imported multiple times.
406
module = self._original_import(name, globals, locals, fromlist, level)
407
408
# Some tests replace modules in sys.modules with non-module instances.
409
if not isinstance(module, ModuleType):
410
return module
411
412
resolved_name = module.__name__
413
if resolved_name in self._modules:
414
return module
415
self._modules.add(resolved_name)
416
417
# Builtin modules don't have a __file__ attribute.
418
if not hasattr(module, '__file__'):
419
return module
420
421
# Note: module.__file__ is not always absolute.
422
path = os.path.normcase(os.path.abspath(module.__file__))
423
# Note: we could avoid normcase and abspath above for non pyc/pyo
424
# files, but those are actually rare, so it doesn't really matter.
425
if not path.endswith(('.pyc', '.pyo')):
426
return module
427
428
# Ignore modules outside our source directory
429
if not path.startswith(self._source_dir):
430
return module
431
432
# If there is no .py corresponding to the .pyc/.pyo module we're
433
# loading, remove the .pyc/.pyo file, and reload the module.
434
# Since we already loaded the .pyc/.pyo module, if it had side
435
# effects, they will have happened already, and loading the module
436
# with the same name, from another directory may have the same side
437
# effects (or different ones). We assume it's not a problem for the
438
# python modules under our source directory (either because it
439
# doesn't happen or because it doesn't matter).
440
if not os.path.exists(module.__file__[:-1]):
441
if os.path.exists(module.__file__):
442
os.remove(module.__file__)
443
del sys.modules[module.__name__]
444
module = self(name, globals, locals, fromlist, level)
445
446
return module
447
448
449
# Install our hook
450
builtins.__import__ = ImportHook(builtins.__import__)