-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathbuild.py
1600 lines (1377 loc) · 69.8 KB
/
build.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
import SCons
from SCons.Script import *
from SCons.Util import flatten
import io
import os
import re
import sys
import glob
import json
import shlex
import fnmatch
import requests
import subprocess
import multiprocessing
from buildscripts import errorcodes
from os.path import basename, splitext
my_dir = os.path.dirname(__file__)
def ospath(file):
return file.replace('/',os.path.sep)
def sibling(*file):
return os.path.normpath(os.path.join(my_dir, *file))
try:
import ninja_syntax
import touch_compiler_timestamps
except ImportError:
# Sometimes we can't import a sibling file. This makes it possible.
sys.path.append(my_dir)
import ninja_syntax
import touch_compiler_timestamps
split_lines_script = os.path.join(my_dir, 'split_lines.py')
subst_file_script = os.path.join(my_dir, 'subst_file.py')
test_list_script = os.path.join(my_dir, 'test_list.py')
touch_compiler_timestamps_script = os.path.join(my_dir, 'touch_compiler_timestamps.py')
verify_icecream_script = os.path.join(my_dir, 'darwin', 'verify_icecream.py')
icecc_create_env = os.path.join(my_dir, 'icecream', 'icecc-create-env')
def makeNinjaFile(target, source, env):
assert not source
ninja_file = NinjaFile(str(target[0]), env)
ninja_file.write()
def rglob(pattern, root='.') :
return [os.path.join(path, f)
for path, dirs, files in os.walk(root, followlinks=True)
for f in fnmatch.filter(files, pattern)]
def where_is(env, exe):
path = env.WhereIs(exe)
if not path:
# check a few places that are often on $PATH but scons hides.
if os.path.exists('/usr/local/bin/'+exe):
path = '/usr/local/bin/'+exe
elif os.path.exists(os.path.expanduser('~/bin/')+exe):
path = os.path.expanduser('~/bin/')+exe
elif os.path.exists('/opt/local/bin/'+exe):
path = '/opt/local/bin/'+exe
elif os.path.exists('/usr/lib/icecream/bin/'+exe):
path = '/usr/lib/icecream/bin/'+exe
# Normalize missing to '' rather than None
return path if path else ''
def strmap(node_list):
for node in node_list:
assert isinstance(node, (str, SCons.Node.FS.Base, SCons.Node.Alias.Alias))
return [str(node) for node in node_list]
def get_path(node):
"""
Return a fake path if necessary.
As an example Aliases use this as their target name in Ninja.
"""
if hasattr(node, "get_path"):
return node.get_path()
return str(node)
def src_file(node):
"""Returns the src code file if it exists."""
if hasattr(node, "srcnode"):
src = node.srcnode()
if src.stat() is not None:
return src
return get_path(node)
def get_dependencies(node, skip_sources=False):
"""Return a list of dependencies for node."""
if skip_sources:
return [
get_path(src_file(child))
for child in node.children()
if child not in node.sources
]
return [get_path(src_file(child)) for child in node.children()]
def fetch_icecream_tarball():
LINK_URL = 'http://mongodbtoolchain.build.10gen.cc/icecream/ubuntu1604/x86_64/latest'
NAME_FILE = 'build/icecc_envs/latest'
os.makedirs('build/icecc_envs', exist_ok = True)
response = requests.head(LINK_URL, allow_redirects=True)
if not response.ok:
if os.path.exists(NAME_FILE):
with open(NAME_FILE) as f:
local_file = f.read()
print("Can't fetch {}, assuming {} is up to date".format(LINK_URL, local_file))
return local_file
else:
print("error fetching url for latest icecream env: " + str(response))
Exit(1)
url = response.url
size = int(response.headers['Content-length'])
remote_file = url.split('/')[-1]
local_file = os.path.join('build', 'icecc_envs', remote_file)
if (os.path.exists(NAME_FILE)
and os.path.exists(local_file)
and os.stat(local_file).st_size == size):
with open(NAME_FILE) as f:
if f.read() == remote_file:
print("{} up to date".format(local_file))
return local_file
print("fetching {} ({}MB)".format(url, size // (1024*1024)))
response = requests.get(url)
if not response.ok:
print("error fetching latest icecream env: " + str(response))
Exit(1)
with open(local_file, "wb") as f:
f.write(response.content)
with open(NAME_FILE, 'w') as f:
f.write(local_file)
return local_file
def is_interesting_flatten_target(target):
return ("/bin/" in target or "\\bin\\" in target) and not "_test" in target and not "_bm" in target
class NinjaFile(object):
def __init__(self, name, env):
self.ninja_file = name
self.globalEnv = env
self.aliases = {}
self.vars = {}
self.overrides = {}
self.tool_commands = {}
self.tool_paths = set()
self.builds = []
self.built_targets = set()
self.generated_headers = set()
self.rc_files = []
self.unittest_shortcuts = {}
self.unittest_skipped_shortcuts = set()
self.setup_test_execution = not env.get('_NINJA_NO_TEST_EXECUTION', False)
self.flatten_install = GetOption('flatten_hygienic')
self.enable_dwarf64 = GetOption('enable_dwarf64')
self.init_idl_dependencies()
self.find_build_nodes()
self.find_aliases()
self.add_run_test_builds()
self.set_up_complier_upgrade_check()
# SCons no longer enforces this at build time so we should not either
# if env.get('_NINJA_USE_ERRCODE'):
# self.add_error_code_check()
if env.get('_NINJA_CCACHE'):
self.set_up_ccache()
if env.get('_NINJA_ICECC'):
if env.TargetOSIs('darwin'):
self.add_icecream_check()
self.set_up_icecc()
if GetOption('pch'):
self.enable_pch()
self.hide_slow_compile_latency()
assert 'COPY' not in self.vars
if self.globalEnv.TargetOSIs('windows'):
self.vars['COPY'] = 'cmd /c copy'
else:
self.vars['COPY'] = 'install' # install seems faster than cp.
assert 'PYTHON' not in self.vars
self.vars['PYTHON'] = self.globalEnv.WhereIs('$PYTHON')
def init_idl_dependencies(self):
# The IDL files depend on the python scripts so get a list of IDL related python files.
# This is done by idl_tool.py but we need to duplicate the logic since we do not run
# the scanner. We get the list once and cache it.
self.idl_deps = glob.glob('buildscripts/idl/*.py')
self.idl_deps.extend(glob.glob('buildscripts/idl/idl/*.py'))
def enable_pch(self):
assert not self.globalEnv.get('_NINJA_CCACHE')
pch_dir = ospath('build/%s/mongo/'%self.globalEnv.subst('$VARIANT_DIR'))
# Prefer CXX on MSVC since MSVC always has a SHCXX due to the MSI custom action dll.
pch_tool = ('SHCXX'
if 'SHCXX' in self.tool_commands and not self.globalEnv.ToolchainIs('msvc')
else 'CXX')
pchvars = {}
for build in self.builds:
if build['rule'] in ('CXX', 'SHCXX'):
if build['inputs'][0].startswith(ospath('src/mongo')):
if build['inputs'][0] == ospath('src/mongo/base/system_error.cpp'):
# HACK: this happens to be a good file to base the pch flags off of.
# It needs to be in an lib in an env that hasn't had too much injection.
pchvars = dict(**build['variables'])
is_test = 'test' in build['inputs'][0]
if ((is_test and build['rule'] == 'SHCXX')
or (not is_test and build['rule'] != pch_tool)):
continue # no pch for this file.
pch_file = 'test-pch.h' if is_test else 'pch.h'
if not self.globalEnv.ToolchainIs('msvc'):
# -include uses path to file
build['variables']['pch_flags'] = '-include ' + pch_dir + pch_file
build.setdefault('implicit', []).append(pch_dir + pch_file + '.$pch_suffix')
else:
# /FI and friends use the same rules for paths as #include
build['variables']['pch_flags'] = (
'/Fp{0}{1}.$pch_suffix /Yumongo/{1} /FImongo/{1}'
.format(pch_dir, pch_file))
# Ninja only knows about the .obj file and uses that, not the .pch file, to
# track header dependencies. This works around the ninja limitation that
# rules using 'deps' can't have builds with multiple outputs.
build.setdefault('implicit', []).append(pch_dir + pch_file + '.obj')
elif build['rule'] == 'LINK' and self.globalEnv.ToolchainIs('msvc'):
build.setdefault('inputs', []).extend([pch_dir+'pch.h.obj',
pch_dir+'test-pch.h.obj'])
self.vars['pch_flags'] = ''
self.vars['pch_suffix'] = 'gch' if self.globalEnv.ToolchainIs('gcc') else 'pch'
for tool in [t for t in ('CXX', 'SHCXX') if t in self.tool_commands]:
if not self.globalEnv.ToolchainIs('msvc'):
# position matters on non-msvc compilers
self.tool_commands[tool] = self.tool_commands[tool].replace(
'$out',
'$out $pch_flags')
else:
self.tool_commands[pch_tool] += ' $pch_flags'
for (pch_file, rule) in (('pch.h', pch_tool), ('test-pch.h', 'CXX')):
# Copy the pch headers to the build dir so the compiled pch is there rather than in the
# source tree. They need to be in the same directory.
self.builds.append(dict(
rule='INSTALL',
inputs=sibling(pch_file),
outputs=pch_dir + pch_file))
pchvars['description']= 'PCH_{} {}.$pch_suffix'.format(rule, pch_file)
if not self.globalEnv.ToolchainIs('msvc'):
pchvars['pch_flags']= '-x c++-header'
self.builds.append(dict(
rule=rule,
inputs=pch_dir + pch_file,
outputs=pch_dir + pch_file + '.$pch_suffix',
order_only='_generated_headers',
variables=pchvars,
))
else:
pchvars['_MSVC_OUTPUT_FLAG'] = '/Fo%s%s.obj'%(pch_dir, pch_file)
pchvars['pch_flags'] = '/Fp{0} /Yc{1} /FI{1}'.format(pch_dir + pch_file + '.pch',
'mongo/' + pch_file)
self.builds.append(dict(
rule=rule,
inputs=pch_dir + pch_file,
outputs=pch_dir + pch_file + '.obj',
order_only='_generated_headers',
variables=dict(pchvars), # copy it
# can't have multiple outputs.
#implicit_outputs=pch_dir + pch_file + '.pch',
))
def add_run_test_builds(self):
# Rules for executing tests where added upstream, if they're enabled this method is a no-op
if not self.setup_test_execution:
return
# For everything that gets installed to build/unittests, add a rule for +basename
# that runs the test from its original location.
paths = (
# Not including build/integration_tests since they need a server to run.
os.path.join('build', 'unittests'),
os.path.join('build', 'benchmark'),
)
for key in self.unittest_shortcuts:
self.builds.append(self.unittest_shortcuts[key])
# If we translated the newer scons generated @ rules to + rules, do not add duplicates
for build in self.builds:
for output in build['outputs']:
if output.startswith('+'):
return
def is_test_like(name):
return any(name.startswith(path) for path in paths)
tests = [flatten(build['inputs'])[0]
for build in self.builds
if build['rule'] == 'INSTALL'
and is_test_like(flatten(build['outputs'])[0])]
self.builds += [dict(outputs='+'+os.path.basename(test), inputs=test, rule='RUN_TEST')
for test in tests]
def set_up_complier_upgrade_check(self):
# This is based on a suggestion from the ninja mailing list. It creates two files, a
# then_file with the mtime of the compiler and a now_file with an mtime of the last time
# this task runs. This task depends on the compiler so that if it gets upgraded it will be
# newer than the then_file so this task will rerun and update both files. All compiles and
# the configure step depend on the now_file, so they get rerun whenever it is updated. This
# is all to work around the fact that package managers back-date the mtimes when installing
# to the time is was build rather than the time it was installed, so just depending on the
# compiler itself doesn't actually work.
cxx = self.globalEnv.WhereIs('$CXX')
cxx_escaped = cxx.replace('/', '_').replace('\\', '_').replace(':', '_')
now_file = os.path.join('build', 'compiler_timestamps', cxx_escaped + '.last_update')
then_file = os.path.join('build', 'compiler_timestamps', cxx_escaped + '.mtime')
self.compiler_timestamp_file = now_file
# Run it now if needed so that we don't need to reconfigure twice since the configure job
# depends on the timestamp.
touch_compiler_timestamps.run_if_needed(cxx, then_file, now_file)
self.builds.append(dict(
rule='COMPILER_TIMESTAMPS',
inputs=cxx,
outputs=[then_file, now_file]))
for build in self.builds:
if build['rule'] in ('CC', 'CXX', 'SHCC', 'SHCXX'):
build.setdefault('implicit', []).append(self.compiler_timestamp_file)
def add_error_code_check(self):
timestamp_file = os.path.join('build', 'compiler_timestamps', 'error_code_check.timestamp')
command = self.make_command(
'$PYTHON buildscripts/errorcodes.py -q --list-files \n ( echo "" > {} )'.format(
timestamp_file))
self.builds.append(dict(
rule='EXEC',
implicit=self.ninja_file,
outputs=timestamp_file,
variables=dict(
command=command,
description='Checking error codes and waiting for next compile to finish',
deps='msvc',
msvc_deps_prefix='scanning file: ',
)))
# Make this an order_only input to linking stages. This ensures that it happens on every
# build but is still allowed to happen in parallel with compilation. This should get it out
# of the critical path so that it doesn't actually affect build times, with the downside
# that it detects errors later.
for build in self.builds:
if build['rule'] in ('LINK', 'SHLINK', 'AR'):
build.setdefault('order_only', []).append(timestamp_file)
def add_icecream_check(self):
# Run the verification script on every build to warn the user if icecream is not running
dummy_target = '_verify_icecream_setup'
self.builds.append(dict(
rule='EXEC',
inputs='_ALWAYS_BUILD',
outputs=dummy_target,
variables=dict(
command='$PYTHON ' + verify_icecream_script,
description='Checking for a proper icecream setup',
)))
# Do this before trying to compile since it is very quick and we want to alert if we are in
# a bad state.
for build in self.builds:
if build['rule'] in ('ACC', 'CC', 'CXX', 'SHCC', 'SHCXX'):
build.setdefault('order_only', []).append(dummy_target)
def set_up_ccache(self):
for rule in ('CC', 'CXX', 'SHCC', 'SHCXX'):
if rule in self.tool_commands:
self.tool_commands[rule] = '{} {}'.format(
self.globalEnv['_NINJA_CCACHE'],
self.tool_commands[rule])
def set_up_icecc(self):
cc = self.globalEnv.WhereIs('$CC')
cxx = self.globalEnv.WhereIs('$CXX')
# This is a symlink that points to the real environment file with the md5sum name. This is
# important because icecream assumes that same-named environments are identical, but we need
# to give ninja a fixed name for dependency tracking.
version_file = 'build/icecc_envs/{}.tar.gz'.format(cc.replace('/', '_'))
env_flags = [
'CCACHE_PREFIX=' + self.globalEnv['_NINJA_ICECC'],
]
compile_flags = []
if self.globalEnv.ToolchainIs('clang'):
env_flags += [ 'ICECC_CLANG_REMOTE_CPP=1' ]
if self.globalEnv['_NINJA_CCACHE_VERSION'] >= [3, 4, 1]:
# This needs the fix for https://github.com/ccache/ccache/issues/185 to work.
env_flags += [ 'CCACHE_NOCPP2=1' ]
compile_flags += [ '-frewrite-includes' ]
if self.globalEnv.TargetOSIs("darwin"):
version_file = fetch_icecream_tarball()
assert os.path.exists(version_file)
env_flags += [ 'ICECC_VERSION=x86_64:%s' % version_file ]
else:
env_flags += [ 'ICECC_VERSION=$$(realpath "%s")' % version_file ]
self.builds.append(dict(
rule='MAKE_ICECC_ENV',
inputs=icecc_create_env,
outputs=version_file,
implicit=[cc, self.compiler_timestamp_file],
variables=dict(
cmd='{icecc_create_env} --clang {clang} {compiler_wrapper} {out}'.format(
icecc_create_env=icecc_create_env,
clang=os.path.realpath(cc),
compiler_wrapper='/bin/true', # we require a new enough iceccd.
out=version_file),
)
))
else:
env_flags += [ 'ICECC_VERSION=$$(realpath "%s")' % version_file ]
# CCACHE_NOCPP2 and GCC 11 do not work. Older versions of GCC work so disable it on GCC 11.
gcc_version_str = subprocess.check_output([self.globalEnv['CC'], '-dumpversion']).decode('utf8').strip()
dot_index = gcc_version_str.find(".")
gcc_version_int = int(gcc_version_str[0:dot_index]) if dot_index != -1 else int(gcc_version_str)
#if gcc_version_int == 8:
# env_flags += [ 'CCACHE_NOCPP2=1' ]
compile_flags += [ '-fdirectives-only' ]
self.builds.append(dict(
rule='MAKE_ICECC_ENV',
inputs=icecc_create_env,
outputs=version_file,
implicit=[cc, cxx, self.compiler_timestamp_file],
variables=dict(
cmd='{icecc_create_env} --gcc {gcc} {gxx} {out}'.format(
icecc_create_env=icecc_create_env,
gcc=os.path.realpath(cc),
gxx=os.path.realpath(cxx),
out=version_file),
)
))
for rule in ('CC', 'CXX', 'SHCC', 'SHCXX'):
if rule in self.tool_commands:
self.tool_commands[rule] = (
' '.join(env_flags + [self.tool_commands[rule]] + compile_flags))
for build in self.builds:
if build['rule'] in ('ACC', 'CC', 'CXX', 'SHCC', 'SHCXX'):
build.setdefault('order_only', []).append(version_file)
# Run links through icerun to inform the scheduler that we are busy and to prevent running
# hundreds of parallel links.
for rule in ('LINK', 'SHLINK'):
if rule in self.tool_commands:
self.tool_commands[rule] = '{} {}'.format(
self.globalEnv['_NINJA_ICERUN'],
self.tool_commands[rule])
def find_aliases(self):
flatten_install = GetOption('flatten_hygienic')
for alias in SCons.Node.Alias.default_ans.values():
if str(alias) in self.built_targets:
# For some reason we sometimes define a task then alias it to itself.
continue
if not alias.has_builder():
# Hygienic mode produces empty aliases
continue
if alias.get_builder() == SCons.Environment.AliasBuilder:
# "pure" aliases
sources = []
for alias_source in alias.sources:
alias_source_str = str(alias_source)
# Replace the dependency of the pure aliases on install/bin with the hardlink instead
# This means all install-* aliases work but also create hardlinks
if flatten_install and is_interesting_flatten_target(alias_source_str):
alias_source_str = os.path.basename(alias_source_str)
sources.append(alias_source_str)
self.aliases[str(alias)] = sources
pass
else:
# Ignore these for now
# list- targets are specific to hygienic
assert (str(alias) in ('dist', 'lint') or (str(alias).startswith("list-")))
# Fix integration_tests alias to point to files rather than directories.
# TODO remove after CR merged
integration_tests_dir = os.path.join('build', 'integration_tests')
if 'integration_tests' in self.aliases and integration_tests_dir in self.aliases['integration_tests']:
self.aliases['integration_tests']= [t for t in self.built_targets
if t.startswith(integration_tests_dir)]
def hide_slow_compile_latency(self):
# Some of our TUs take substantially longer to compile. Try to start them first to mask
# their high latency by compiling everything else while they are going. The list of TUs was
# determined empirically by timing each compile at -j1 (NINJA_STATUS='%e %p ' makes this
# easier). We should probably revisit this list periodically.
slow_tu_parts= [
"topology_coordinator_v1_test",
"storage_interface_impl_test",
"expression_convert_test",
"transaction_coordinator_futures_util_test",
"options_parser_test",
"future_test_future", # multiple slow TUs
"query_planner_test",
"replication_coordinator_impl_test",
"expression_test",
"transport_layer_asio", # not as quite slow as others, but orig order put it very late.
]
# This is a total hack. Ninja's "scheduler" that decides which task to run next relies on
# the order of a std::set<Edge*>. By ordering tasks higher, they seem to get lower pointer
# values, and therefore run earlier. Hopefully we can replace this with a proper priority
# system if ninja ever implements one.
def priority(build):
if build['rule'].endswith('CXX') and any(s in build['outputs'] for s in slow_tu_parts):
# Slowest tasks go first.
return 0
if build['rule'] == 'CXX':
# On average, CXX tasks take ~50% longer than SHCXX tasks, so they should be started
# earlier. OTOH, they are "leaf" jobs. On balance, doing them earlier seems to make
# builds go faster.
return 10
if build['rule'] in ('SHLINK', 'AR'):
# Link intermediate libs when ready rather than waiting until everything is ready.
return 20
if build['rule'] == 'LINK':
# Ditto final links.
return 30
if build['rule'] in ('SHCXX', 'SHCC', 'CC'):
# Do third_party first, both because the mozjs "unified" TUs are fairly slow, and to
# unblock links.
if 'third_party' in build['outputs']:
return 40
# All of our library code.
# TODO it may be worth ordering by LIBDEPS depth, deepest first.
return 50
# Everything else gets ordered early so they don't unnecessarily delay tasks that depend
# on them.
return -99
self.builds.sort(key=priority)
def find_build_nodes(self):
seen = set()
# Convert this to a list because SCons is still changing this
# dict when we start iterating which causes python to raise an
# exception
for n in list(self.globalEnv.fs.Top.root._lookupDict.values()):
if not SCons.Node.is_derived_node(n): continue
if isinstance(n, SCons.Node.FS.Dir):
must_skip_dir = True
dir_str = str(n)
if "librdkafka" in dir_str and dir_str.endswith("include/src"):
must_skip_dir = False
if must_skip_dir:
continue
# Filter for site_scons/site_tools/task_limiter.py from build nodes
if "-stream" in str(n) and not ".o" in str(n):
continue
if str(n.executor).startswith('write_uuid_to_file('): continue
if os.path.join('','sconf_temp','conftest') in str(n): continue
# We see each build task once per target, but we handle all targets the first time.
if id(n.executor) not in seen:
seen.add(id(n.executor))
try:
self.handle_build_node(n)
except:
print()
print("Failed on node:", n)
print("Failed on str node:", str(n.__class__))
print("Command:", n.executor)
print()
raise
for build in self.builds:
# Make everything build by scons depend on the ninja file. This makes them transitively
# depend on all of the scons dependencies so scons gets a chance to rebuild them
# whenever any scons files change.
if build['rule'] == 'SCONS':
build.setdefault('implicit', []).append(self.ninja_file)
def make_command(self, cmd):
cmd = cmd.replace("$?", "$$?")
lines = cmd.split('\n')
if len(lines) == 1:
return cmd # no changes needed
cmd = ' && '.join(lines)
if self.globalEnv.TargetOSIs('windows'):
cmd = 'cmd /c ' + cmd
return cmd
def handle_build_node(self, n):
# TODO break this function up
if n.executor.post_actions:
# We currently only use this to set the executable bits on files, but we do it in
# different ways in different places. For now, only support this usage.
assert len(n.executor.post_actions) == 1
assert len(n.executor.action_list) == 1
if n.executor.action_list[0] == SCons.Tool.textfile._subst_builder.action:
if str(n.executor.post_actions[0]) != 'chmod 755 $TARGET':
assert str(n.executor.post_actions[0]).startswith('Chmod(')
assert 'oug+x' in str(n.executor.post_actions[0]) or 'ugo+x' in str(n.executor.post_actions[0]) or '0755' in str(n.executor.post_actions[0])
elif isinstance(n.executor.action_list[0], SCons.Action.FunctionAction):
if str(n.executor.post_actions[0]) != 'chmod 755 $TARGET':
assert str(n.executor.post_actions[0]).startswith('Chmod(')
assert 'u+x' in str(n.executor.post_actions[0]) or 'oug+x' in str(n.executor.post_actions[0]) or '0755' in str(n.executor.post_actions[0])
else:
raise ValueError("Unknown post action: %s" % (n.executor.action_list[0]))
n.executor.post_actions = []
do_chmod = True
else:
do_chmod = False
assert n.has_builder()
assert not n.side_effect
# Filter for site_scons/site_tools/task_limiter.py in side_effects
if n.side_effects:
assert len(n.side_effects) == 1
assert "-stream" in str(n.side_effects[0])
assert n.builder.action
assert n.executor
assert not n.executor.post_actions
assert not n.executor.overridelist
action = n.executor.get_action_list()[0]
myEnv = n.executor.get_build_env()
targets = n.executor.get_all_targets()
sources = n.executor.get_all_sources()
implicit_deps = strmap(n.depends)
if len(n.executor.get_action_list()) > 2:
print("A1: " + str(n.executor.get_action_list()[0]))
print("A2: " + str(n.executor.get_action_list()[1]))
print("targets: " + str(targets))
print("sources: " + str(sources))
print("implicit_deps: " + str(implicit_deps))
assert len(n.executor.get_action_list()) == 1 or len(n.executor.get_action_list()) == 2
# Archives generated in hygienic defer their dependency generation so we need to call generator()
if isinstance(action, SCons.Action.CommandGeneratorAction) and \
"aib_make_archive.py" in str(n.executor):
cmd = action.generator(sources, targets, myEnv, for_signature=False)
n.executor.set_action_list([Action(cmd)])
for target in targets:
if target.always_build:
implicit_deps.append('_ALWAYS_BUILD')
target = str(target)
# This is handled explicitly in write_regenerator.
if target.endswith('.ninja'): return
self.built_targets.add(target)
if target.endswith('.h') or target.endswith('.hpp'):
self.generated_headers.add(target)
if action == SCons.Tool.install.install_action:
assert len(targets) == 1
assert len(sources) == 1
self.builds.append(dict(
rule='INSTALL',
outputs=strmap(targets),
inputs=strmap(sources),
implicit=get_dependencies(n)
))
target_str = strmap(targets)[0]
if self.flatten_install and is_interesting_flatten_target(target_str):
hardlink_map = [os.path.basename(target_str)]
self.builds.append(dict(
rule='SYMLINK',
outputs=hardlink_map,
inputs=strmap(targets),
implicit=implicit_deps
))
return
if action == SCons.Tool.textfile._subst_builder.action:
implicit_deps.append(subst_file_script)
args = dict(do_chmod=do_chmod, subs=myEnv['SUBST_DICT'])
self.builds.append(dict(
rule='SCRIPT_RSP',
outputs=strmap(targets),
inputs=strmap(sources),
implicit=implicit_deps,
variables={
'rspfile_content': ninja_syntax.escape(json.dumps(args)),
'script': subst_file_script,
}
))
return
if len(targets) == 1 and any(str(targets[0]).endswith(suffix)
for suffix in ['tests.txt', 'benchmarks.txt']):
if len(sources) == 1:
assert isinstance(sources[0], SCons.Node.Python.Value)
tests = sources[0].value
else:
# Unpatched builds put the list in sources.
#TODO remove after CR merged
tests = strmap(sources)
if not tests and "MONGO_TEST_REGISTRY" in myEnv:
# tests are now registered in a list in the Environment
tests = strmap(myEnv["MONGO_TEST_REGISTRY"][ str(targets[0]) ])
implicit_deps.extend([test_list_script, self.ninja_file])
self.builds.append(dict(
rule='SCRIPT_RSP',
outputs=strmap(targets),
inputs=[],
implicit=implicit_deps,
variables={
'rspfile_content': ninja_syntax.escape(json.dumps(tests)),
'script': test_list_script,
}
))
return
if str(targets[0]) == 'compile_commands.json' and self.globalEnv['NINJA']:
assert len(targets) == 1
# Use ninja to generate the compile db rather than scons.
self.builds.append(dict(
rule='COMPILE_DB',
outputs=strmap(targets),
inputs=self.ninja_file,
order_only=['generated-sources'], # These should be updated along with the compdb.
))
return
if isinstance(action, SCons.Action.ListAction):
lines = str(n.executor).split('\n')
if len(action.list) == 2:
if lines[1] == 'noop_action(target, source, env)':
# Remove the noop_action we attach to thin archive builds.
n.executor.set_action_list(action.list[0])
assert len(n.executor.get_action_list()) == 1
action = n.executor.get_action_list()[0]
elif lines[1] == 'embedManifestExeCheck(target, source, env)':
# We don't use this.
assert not myEnv.get('WINDOWS_EMBED_MANIFEST')
n.executor.set_action_list(action.list[0])
assert len(n.executor.get_action_list()) == 1
action = n.executor.get_action_list()[0]
# Strip out the functions from shared library builds.
if '$SHLINK' in str(n.executor):
# Linux or Windows
assert len(lines) == 3 or len(lines) == 5 or len(lines) == 7
# Run the check now. It doesn't need to happen at runtime.
assert lines[0] == 'SharedFlagChecker(target, source, env)'
SCons.Defaults.SharedFlagChecker(targets, sources, myEnv)
# We don't need this right now, so just assert that we don't. It can be added if we
# ever need it.
assert lines[2] == 'LibSymlinksActionFunction(target, source, env)' or \
lines[4] == 'LibSymlinksActionFunction(target, source, env)'
for target in targets:
assert not getattr(getattr(targets[0],'attributes', None), 'shliblinks', None)
# TODO: Windows - remove .def from from sources
# and extend _LIBFLAGS with /def:
# Now just make it the "real" action.
n.executor.set_action_list(action.list[1])
assert len(n.executor.get_action_list()) == 1
action = n.executor.get_action_list()[0]
if str(n.executor) == 'jsToH(target, source, env)':
# Patch over the function to do it outside of scons.
#TODO remove after CR merged
cmd = '$PYTHON site_scons/site_tools/jstoh.py $TARGET $SOURCES'
implicit_deps.append('site_scons/site_tools/jstoh.py')
n.executor.set_action_list([Action(cmd)])
assert len(n.executor.get_action_list()) == 1
action = n.executor.get_action_list()[0]
if any(str(n.executor).startswith('${TEMPFILE('+quote) for quote in ('"', "'")):
# Capture the real action under the tempfile.
cmd_list = []
def TEMPFILE(cmd_, comstr=None):
cmd_list.append(cmd_)
myEnv['TEMPFILE'] = TEMPFILE
myEnv.subst(str(n.executor), executor=n.executor)
cmd = cmd_list[0]
assert '(' not in cmd
n.executor.set_action_list([Action(cmd)])
assert len(n.executor.get_action_list()) == 1
action = n.executor.get_action_list()[0]
if str(n.executor).endswith('${TEMPFILE(SOURCES[1:])}'):
assert len(targets) == 1
prefix = str(n.executor)[:-len('${TEMPFILE(SOURCES[1:])}')]
cmd = myEnv.subst(prefix, executor=n.executor) + (' @%s.rsp'%targets[0])
self.builds.append(dict(
rule='EXEC_RSP',
outputs=strmap(targets),
inputs=strmap(sources[1:]),
implicit=implicit_deps + [str(sources[0])],
variables = {'command': cmd},
))
return
# TODO find a better way to find things that are functions
# August 17, 2021 - master now generates unit test executions with:
# $( $ICERUN $) ${SOURCES[0]} -fileNameFilter $TEST_SOURCE_FILE_NAME $UNITTEST_FLAGS
needs_scons = (isinstance(n.executor.get_action_list()[0], SCons.Action.FunctionAction)
or ('(' in str(n.executor) and not "$( $ICERUN $)" in str(n.executor)))
if needs_scons:
sources = [s for s in sources if not isinstance(s, SCons.Node.Python.Value)]
self.builds.append(dict(
rule='SCONS',
outputs=strmap(targets),
inputs=strmap(sources),
implicit=implicit_deps
))
return
tool = str(n.executor).split(None, 1)[0]
if tool == '$IDLC' and myEnv.get('IDL_HAS_INLINE_DEPENDENCIES'):
if n.implicit:
implicit_deps += strmap(n.implicit)
# Important:
# Originally we ran the IDL scanner during build.ninja file generation but this is
# single-thread and slow as the number of IDL files has grown to greater then 100.
# Now, we let IDL tell Ninja its dependencies. Unfortunately, IDL does not have a good
# way to this with its implicit dependency caching and multiple outputs due to a
# limitation in ninja.
# See https://github.com/ninja-build/ninja/pull/1534
#
# Instead we split IDL file generation into "two" phases:
# 1. Generate the header and the cpp file as normal but only tell Ninja about the header
# 2. "Generate" the cpp file by telling Ninja it depends on the header file via a
# phony rule
#
idl_cpp_file = strmap(targets)[0]
idl_header_file = strmap(targets)[1]
# Append --write-dependencies-inline so that IDL generates a list of dependencies when
# it runs
idl_command = self.make_command(myEnv.subst(str(n.executor), executor=n.executor) \
+ " --write-dependencies-inline")
implicit_deps.extend(self.idl_deps)
# Lie to Ninja by saying it only generates a header
self.builds.append(dict(
rule='EXEC',
outputs=[idl_header_file],
inputs=strmap(sources),
implicit=implicit_deps,
variables={
'command' : idl_command,
'deps' : 'msvc',
'msvc_deps_prefix' : 'import file:',
}
))
# Tell Ninja the cpp file is "generated" from the header file
self.builds.append(dict(
rule='phony',
outputs=[ idl_cpp_file ],
inputs=[ idl_header_file ],
))
return
elif tool not in ('$CC', '$CXX', '$SHCC', '$SHCXX', '$LINK', '$SHLINK', '$AR', '$RC'):
list_targets = strmap(targets)
list_sources = strmap(sources)
n.scan() # We need this for IDL.
implicit_deps += strmap(n.implicit)
self.builds.append(dict(
rule='EXEC',
outputs=list_targets,
inputs=list_sources,
implicit=implicit_deps,
variables={
'command': self.make_command(myEnv.subst(str(n.executor), executor=n.executor)),
}
))
# Starting in SERVER-43047, there is no more install rules for unittests but there is a
# rule for running them with @. Use that rule as a guideline to build our own "+" rule.
# The plus rule is surperior since it uses the console logger to avoid interlacing of
# tests.
if list_targets[0].startswith("@"):
test_name = list_targets[0]
test_name = '+' + test_name[1:]
# These take priority over unit test shortcut names.
self.unittest_skipped_shortcuts.add(test_name)
if test_name in self.unittest_shortcuts.keys():
del self.unittest_shortcuts[test_name]
self.builds.append(dict(
rule='RUN_TEST',
outputs=test_name,
inputs=list_sources
))
# Add shortcuts for this unit test.
for unit_test_source_file in \
n.executor.get_all_children()[0].executor.get_all_sources():
test_file_name = splitext(basename(str(unit_test_source_file)))[0]
if "_test" in test_file_name:
# Add suffix to tests on Windows to match other unit tests
suffix = ".exe" if self.globalEnv.TargetOSIs('windows') else ""
test_file_name = '+' + test_file_name + suffix
if (test_file_name not in self.unittest_shortcuts and test_file_name not
in self.unittest_skipped_shortcuts):
# Add a shortcut for the given unit test file name.
self.unittest_shortcuts[test_file_name] = dict(
rule='phony',
outputs=test_file_name,
inputs=test_name
)
elif test_file_name in self.unittest_shortcuts:
# There are multiple unit tests with the same file name. So we cannot
# create a shortcut for this test name.
print('*** Duplicate test file name detected. No alias has been created for it, recommend renaming:', test_file_name[1:] + '.cpp')
del self.unittest_shortcuts[test_file_name]
self.unittest_skipped_shortcuts.add(test_file_name)
return
self.tool_paths.add(myEnv.WhereIs(tool))
tool = tool.strip('${}')
# This is only designed for tools that use $TARGET and $SOURCES not $TARGETS or $SOURCE.
cmd = self.make_command(str(n.executor).replace('$TARGET.windows', '$out')
.replace('$TARGET','$out')
.replace('$CHANGED_SOURCES', '$in')
.replace('$SOURCES.windows', '$in')
.replace('$_SHLINK_TARGETS', '$out')
.replace('$_SHLINK_SOURCES', '$in')
.replace('$SOURCES','$in'))
# C compiler can be used to compile .c files and .S files, we create a separate rule for .S files
if tool == "CC" and "ASPPFLAGS" in cmd:
tool = "ACC"
assert 'TARGET' not in cmd
assert 'SOURCE' not in cmd
if tool in self.tool_commands:
if cmd != self.tool_commands[tool]:
print("ERROR: same tool (%s) with different parameters %s -- %s " % (tool, cmd, self.tool_commands[tool]))
assert cmd == self.tool_commands[tool]