forked from unbit/uwsgi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uwsgiconfig.py
1706 lines (1456 loc) · 62.5 KB
/
uwsgiconfig.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
# uWSGI build system
uwsgi_version = '2.1-dev'
import os
import re
import time
uwsgi_os = os.environ.get('UWSGI_FORCE_OS', os.uname()[0])
uwsgi_os_k = re.split('[-+_]', os.uname()[2])[0]
uwsgi_os_v = os.uname()[3]
uwsgi_cpu = os.uname()[4]
import sys
import subprocess
from threading import Thread, Lock
from optparse import OptionParser
try:
from queue import Queue
except ImportError:
from Queue import Queue
from distutils import sysconfig
try:
import ConfigParser
except ImportError:
import configparser as ConfigParser
try:
from shlex import quote
except ImportError:
from pipes import quote
PY3 = sys.version_info[0] == 3
if uwsgi_os == 'Darwin':
GCC = os.environ.get('CC', 'clang')
else:
GCC = os.environ.get('CC', sysconfig.get_config_var('CC'))
if not GCC:
GCC = 'gcc'
def get_preprocessor():
if 'clang' in GCC:
return 'clang -xc core/clang_fake.c'
return 'cpp'
CPP = os.environ.get('CPP', get_preprocessor())
try:
CPUCOUNT = int(os.environ.get('CPUCOUNT', -1))
except ValueError:
CPUCOUNT = -1
if CPUCOUNT < 1:
try:
import multiprocessing
CPUCOUNT = multiprocessing.cpu_count()
except (ImportError, NotImplementedError):
try:
CPUCOUNT = os.sysconf('SC_NPROCESSORS_ONLN')
# AttributeError means os.syconf function is not available and
# ValueError means the name passed to it is not supported
except (AttributeError, ValueError):
CPUCOUNT = 1
# force single cpu in cygwin mode
if uwsgi_os.startswith('CYGWIN'):
CPUCOUNT = 1
binary_list = []
started_at = time.time()
# this is used for reporting (at the end of the build)
# the server configuration
report = {
'kernel': False,
'execinfo': False,
'ifaddrs': False,
'locking': False,
'event': False,
'timer': False,
'filemonitor': False,
'pcre': False,
'routing': False,
'capabilities': False,
'yaml': False,
'json': False,
'ssl': False,
'xml': False,
'debug': False,
'plugin_dir': False,
'zlib': False,
'ucontext': False,
}
verbose_build = False
def print_compilation_output(default_str, verbose_str):
if verbose_build:
print(verbose_str)
elif default_str is not None:
print(default_str)
compile_queue = None
print_lock = None
thread_compilers = []
def thread_compiler(num):
while True:
(objfile, cmdline) = compile_queue.get()
if objfile:
print_lock.acquire()
print_compilation_output("[thread %d][%s] %s" % (num, GCC, objfile), "[thread %d] %s" % (num, cmdline))
print_lock.release()
ret = subprocess.call(cmdline, shell=True)
if ret != 0:
os._exit(1)
elif cmdline:
print_lock.acquire()
print(cmdline)
print_lock.release()
else:
return
def binarize(name):
return name.replace('/', '_').replace('.', '_').replace('-', '_')
def strip_prefix(prefix, string):
if string.startswith(prefix):
return string[len(prefix):]
return string
def spcall(cmd):
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=open('uwsgibuild.log', 'w'))
if p.wait() == 0:
if sys.version_info[0] > 2:
return p.stdout.read().rstrip().decode()
return p.stdout.read().rstrip()
else:
return None
# commodity function to remove -W* duplicates
def uniq_warnings(elements):
new_elements = []
for element in elements:
if element.startswith('-W'):
if element not in new_elements:
new_elements.append(element)
else:
new_elements.append(element)
return new_elements
if uwsgi_version.endswith('-dev') and os.path.exists('%s/.git' % os.path.dirname(os.path.abspath(__file__))):
try:
uwsgi_version += '-%s' % spcall('git rev-parse --short HEAD')
except Exception:
pass
def spcall2(cmd):
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
if p.wait() == 0:
if sys.version_info[0] > 2:
return p.stderr.read().rstrip().decode()
return p.stderr.read().rstrip()
else:
return None
def test_snippet(snippet, CFLAGS=[], LDFLAGS=[], LIBS=[]):
"""Compile a C snippet to see if features are available at build / link time."""
cflags = " ".join(CFLAGS)
ldflags = " ".join(LDFLAGS)
libs = " ".join(LIBS)
if sys.version_info[0] >= 3 or (sys.version_info[0] == 2 and sys.version_info[1] > 5):
if not isinstance(snippet, bytes):
if PY3:
snippet = bytes(snippet, sys.getdefaultencoding())
else:
snippet = bytes(snippet)
cmd = "{0} {1} -xc - {2} {3} -o /dev/null".format(GCC, cflags, ldflags, libs)
else:
cmd = " ".join([GCC, cflags, "-xc -", ldflags, libs, "-o /dev/null"])
p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
p.communicate(snippet)
return p.returncode == 0
def has_usable_ucontext():
if uwsgi_os in ('OpenBSD', 'Haiku'):
return False
if uwsgi_os.startswith('CYGWIN'):
return False
if uwsgi_os == 'Darwin' and uwsgi_os_k.startswith('8'):
return False
if uwsgi_cpu[0:3] == 'arm':
return False
# check for ucontext.h functions definitions, musl has only declarations
return test_snippet("""#include <ucontext.h>
int main()
{
ucontext_t uc;
getcontext(&uc);
return 0;
}""")
def spcall3(cmd):
p = subprocess.Popen(cmd, shell=True, stdin=open('/dev/null'), stderr=subprocess.PIPE, stdout=subprocess.PIPE)
(out, err) = p.communicate()
if p.returncode == 0:
if sys.version_info[0] > 2:
return err.rstrip().decode()
return err.rstrip()
else:
return None
def add_o(x):
if x == 'uwsgi':
x = 'main'
elif x.endswith('.a') or x.endswith('.o') or x.startswith('-'):
return x
x = x + '.o'
return x
def push_print(msg):
if not compile_queue:
print(msg)
else:
compile_queue.put((None, msg))
def push_command(objfile, cmdline):
if not compile_queue:
print_compilation_output("[%s] %s" % (GCC, objfile), cmdline)
ret = subprocess.call(cmdline, shell=True)
if ret != 0:
sys.exit(1)
else:
compile_queue.put((objfile, cmdline))
def uwsgi_compile(cflags, last_cflags_ts, objfile, srcfile):
source_stat = os.stat(srcfile)
header_stat = os.stat('uwsgi.h')
try:
if os.environ.get('UWSGI_FORCE_REBUILD', None):
raise
if source_stat[8] >= last_cflags_ts:
raise
if header_stat[8] >= last_cflags_ts:
raise
object_stat = os.stat(objfile)
if object_stat[8] <= source_stat[8]:
raise
if object_stat[8] <= header_stat[8]:
raise
for profile in os.listdir('buildconf'):
profile_stat = os.stat('buildconf/%s' % profile)
if object_stat[8] <= profile_stat[8]:
raise
print("%s is up to date" % objfile)
return
except Exception:
pass
cmdline = "%s -c %s -o %s %s" % (GCC, cflags, objfile, srcfile)
push_command(objfile, cmdline)
def build_uwsgi(uc, print_only=False, gcll=None):
global print_lock, compile_queue, thread_compilers
if CPUCOUNT > 1:
print_lock = Lock()
compile_queue = Queue(maxsize=CPUCOUNT)
for i in range(0, CPUCOUNT):
t = Thread(target=thread_compiler, args=(i,))
t.daemon = True
t.start()
thread_compilers.append(t)
if not gcll:
gcc_list, cflags, ldflags, libs = uc.get_gcll()
else:
gcc_list, cflags, ldflags, libs = gcll
if 'UWSGI_EMBED_PLUGINS' in os.environ:
ep = uc.get('embedded_plugins')
if ep:
uc.set('embedded_plugins', ep + ',' + os.environ['UWSGI_EMBED_PLUGINS'])
else:
uc.set('embedded_plugins', os.environ['UWSGI_EMBED_PLUGINS'])
if uc.get('embedded_plugins'):
ep = uc.get('embedded_plugins').split(',')
epc = "-DUWSGI_DECLARE_EMBEDDED_PLUGINS=\""
eplc = "-DUWSGI_LOAD_EMBEDDED_PLUGINS=\""
for item in ep:
# allow name=path syntax
kv = item.split('=')
p = kv[0]
p = p.strip()
if not p or p == 'None':
continue
if p == 'ugreen':
if not report['ucontext']:
continue
epc += "UDEP(%s);" % p
eplc += "ULEP(%s);" % p
epc += "\""
eplc += "\""
cflags.append(epc)
cflags.append(eplc)
if print_only:
print(' '.join(cflags))
sys.exit(0)
if 'APPEND_CFLAGS' in os.environ:
cflags += os.environ['APPEND_CFLAGS'].split()
print("detected CPU cores: %d" % CPUCOUNT)
print("configured CFLAGS: %s" % ' '.join(cflags))
if sys.version_info[0] >= 3:
import binascii
uwsgi_cflags = binascii.b2a_hex(' '.join(cflags).encode('ascii')).decode('ascii')
else:
uwsgi_cflags = ' '.join(cflags).encode('hex')
last_cflags_ts = 0
if os.path.exists('uwsgibuild.lastcflags'):
ulc = open('uwsgibuild.lastcflags')
last_cflags = ulc.read()
ulc.close()
if uwsgi_cflags != last_cflags:
os.environ['UWSGI_FORCE_REBUILD'] = '1'
else:
last_cflags_ts = os.stat('uwsgibuild.lastcflags')[8]
ulc = open('uwsgibuild.lastcflags', 'w')
ulc.write(uwsgi_cflags)
ulc.close()
# embed uwsgi.h in the server binary. It increases the binary size, but will be very useful
# for various tricks (like cffi integration)
# if possible, the blob is compressed
if sys.version_info[0] >= 3:
uwsgi_dot_h_content = open('uwsgi.h', 'rb').read()
else:
uwsgi_dot_h_content = open('uwsgi.h').read()
if report['zlib']:
import zlib
# maximum level of compression
uwsgi_dot_h_content = zlib.compress(uwsgi_dot_h_content, 9)
if sys.version_info[0] >= 3:
import binascii
uwsgi_dot_h = binascii.b2a_hex(uwsgi_dot_h_content).decode('ascii')
else:
uwsgi_dot_h = uwsgi_dot_h_content.encode('hex')
open('core/dot_h.c', 'w').write('char *uwsgi_dot_h = "%s";\n' % uwsgi_dot_h)
gcc_list.append('core/dot_h')
# embed uwsgiconfig.py in the server binary. It increases the binary size, but will be very useful
# if possible, the blob is compressed
if sys.version_info[0] >= 3:
uwsgi_config_py_content = open('uwsgiconfig.py', 'rb').read()
else:
uwsgi_config_py_content = open('uwsgiconfig.py').read()
if report['zlib']:
import zlib
# maximum level of compression
uwsgi_config_py_content = zlib.compress(uwsgi_config_py_content, 9)
if sys.version_info[0] >= 3:
import binascii
uwsgi_config_py = binascii.b2a_hex(uwsgi_config_py_content).decode('ascii')
else:
uwsgi_config_py = uwsgi_config_py_content.encode('hex')
open('core/config_py.c', 'w').write('char *uwsgi_config_py = "%s";\n' % uwsgi_config_py)
gcc_list.append('core/config_py')
additional_sources = os.environ.get('UWSGI_ADDITIONAL_SOURCES')
if not additional_sources:
additional_sources = uc.get('additional_sources')
if additional_sources:
for item in additional_sources.split(','):
gcc_list.append(item)
if uc.filename.endswith('coverity.ini'):
cflags.append('-DUWSGI_CFLAGS=\\"\\"')
else:
cflags.append('-DUWSGI_CFLAGS=\\"%s\\"' % uwsgi_cflags)
build_date = int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))
cflags.append('-DUWSGI_BUILD_DATE="\\"%s\\""' % time.strftime("%d %B %Y %H:%M:%S", time.gmtime(build_date)))
post_build = []
push_print("*** uWSGI compiling server core ***")
for file in gcc_list:
objfile = file
if objfile == 'uwsgi':
objfile = 'main'
if not objfile.endswith('.a') and not objfile.endswith('.o'):
if objfile.endswith('.c') or objfile.endswith('.cc') or objfile.endswith('.m') or objfile.endswith('.go'):
if objfile.endswith('.go'):
cflags.append('-Wno-error')
uwsgi_compile(' '.join(cflags), last_cflags_ts, objfile + '.o', file)
if objfile.endswith('.go'):
cflags.pop()
else:
if objfile == 'core/dot_h':
cflags.append('-g')
uwsgi_compile(' '.join(cflags), last_cflags_ts, objfile + '.o', file + '.c')
if objfile == 'core/dot_h':
cflags.pop()
if uc.get('embedded_plugins'):
ep = uc.get('embedded_plugins').split(',')
if len(ep) > 0:
push_print("*** uWSGI compiling embedded plugins ***")
for item in ep:
# allows name=path syntax
kv = item.split('=')
if len(kv) > 1:
p = kv[1]
p = p.strip()
if is_remote_plugin(p):
p = get_remote_plugin(p)
path = os.path.abspath(p)
else:
p = kv[0]
p = p.strip()
path = 'plugins/%s' % p
if not p or p == 'None':
continue
if p == 'ugreen':
if not report['ucontext']:
continue
path = path.rstrip('/')
path, up = get_plugin_up(path)
p_cflags = cflags[:]
p_cflags += up['CFLAGS']
if uwsgi_os.startswith('CYGWIN'):
try:
p_cflags.remove('-fstack-protector')
except ValueError:
pass
if GCC in ('clang',):
try:
p_cflags.remove('-fno-fast-math')
p_cflags.remove('-ggdb3')
except ValueError:
pass
p_cflags_blacklist = (
'-Wdeclaration-after-statement',
'-Werror=declaration-after-statement',
'-Wwrite-strings',
'-Werror=write-strings',
)
for cflag in p_cflags_blacklist:
try:
p_cflags.remove(cflag)
except ValueError:
pass
try:
if up['post_build']:
post_build.append(up['post_build'])
except Exception:
pass
for cfile in up['GCC_LIST']:
if cfile.endswith('.a'):
gcc_list.append(cfile)
elif cfile.endswith('.o'):
gcc_list.append('%s/%s' % (path, cfile))
elif not cfile.endswith('.c') and not cfile.endswith('.cc') and not cfile.endswith('.go') and not cfile.endswith('.m'):
uwsgi_compile(' '.join(uniq_warnings(p_cflags)), last_cflags_ts,
path + '/' + cfile + '.o', path + '/' + cfile + '.c')
gcc_list.append('%s/%s' % (path, cfile))
else:
if cfile.endswith('.go'):
p_cflags.append('-Wno-error')
uwsgi_compile(' '.join(uniq_warnings(p_cflags)), last_cflags_ts,
path + '/' + cfile + '.o', path + '/' + cfile)
gcc_list.append('%s/%s' % (path, cfile))
for bfile in up.get('BINARY_LIST', []):
try:
binary_link_cmd = "ld -r -b binary -o %s/%s.o %s/%s" % (path, bfile[1], path, bfile[1])
print(binary_link_cmd)
if subprocess.call(binary_link_cmd, shell=True) != 0:
raise Exception('unable to link binary file')
for kind in ('start', 'end'):
objcopy_cmd = "objcopy --redefine-sym _binary_%s_%s=%s_%s %s/%s.o" % (binarize('%s/%s' % (path, bfile[1])), kind, bfile[0], kind, path, bfile[1])
print(objcopy_cmd)
if subprocess.call(objcopy_cmd, shell=True) != 0:
raise Exception('unable to link binary file')
gcc_list.append('%s/%s.o' % (path, bfile[1]))
except Exception:
if uwsgi_os == 'Darwin':
gcc_list.append('-sectcreate __DATA %s %s/%s' % (strip_prefix('_uwsgi_', bfile[0]), path, bfile[1]))
libs += up['LIBS']
if uwsgi_os == 'Darwin':
found_arch = False
sanitized_ldflags = []
for flag in up['LDFLAGS']:
if flag == '-arch':
found_arch = True
continue
if found_arch:
found_arch = False
continue
sanitized_ldflags.append(flag)
ldflags += sanitized_ldflags
else:
ldflags += up['LDFLAGS']
if uc.get('plugins'):
plugins = uc.get('plugins').split(',')
if len(plugins) > 0:
push_print("*** uWSGI building plugins ***")
for p in plugins:
p = p.strip()
push_print("*** building plugin: %s ***" % p)
build_plugin("plugins/%s" % p, uc, cflags, ldflags, libs)
bin_name = os.environ.get('UWSGI_BIN_NAME', uc.get('bin_name'))
if uc.embed_config:
gcc_list.append("%s.o" % binarize(uc.embed_config))
for ef in binary_list:
gcc_list.append("%s.o" % ef)
if compile_queue:
for t in thread_compilers:
compile_queue.put((None, None))
for t in thread_compilers:
t.join()
print("*** uWSGI linking ***")
if '--static' in ldflags:
ldline = 'ar cru %s %s' % (
quote(bin_name),
' '.join(map(add_o, gcc_list))
)
else:
ldline = "%s -o %s %s %s %s" % (
GCC,
quote(bin_name),
' '.join(uniq_warnings(ldflags)),
' '.join(map(add_o, gcc_list)),
' '.join(uniq_warnings(libs))
)
print(ldline)
ret = subprocess.call(ldline, shell=True)
if ret != 0:
print("*** error linking uWSGI ***")
sys.exit(1)
print("################# uWSGI configuration #################")
print("")
for report_key in report:
print("%s = %s" % (report_key, report[report_key]))
print("")
print("############## end of uWSGI configuration #############")
print("total build time: %d seconds" % (time.time() - started_at))
if bin_name.find("/") < 0:
bin_name = './' + bin_name
if uc.get('as_shared_library'):
print("*** uWSGI shared library (%s) is ready, move it to a library directory ***" % bin_name)
else:
print("*** uWSGI is ready, launch it with %s ***" % bin_name)
for pb in post_build:
pb(uc)
def open_profile(filename):
if filename.startswith('https://') or filename.startswith('https://') or filename.startswith('ftp:https://'):
wrapped = False
try:
import urllib2
except ImportError:
import urllib.request
wrapped = True
if wrapped:
import io
return io.TextIOWrapper(urllib.request.urlopen(filename), encoding='utf-8')
return urllib2.urlopen(filename)
return open(filename)
class uConf(object):
def __init__(self, filename, mute=False):
global GCC
self.filename = filename
self.config = ConfigParser.ConfigParser()
if not mute:
print("using profile: %s" % filename)
if os.path.exists('uwsgibuild.lastprofile'):
ulp = open('uwsgibuild.lastprofile')
last_profile = ulp.read()
ulp.close()
if last_profile != filename:
os.environ['UWSGI_FORCE_REBUILD'] = '1'
ulp = open('uwsgibuild.lastprofile', 'w')
ulp.write(filename)
ulp.close()
if hasattr(self.config, 'read_file'):
self.config.read_file(open_profile(filename))
else:
self.config.readfp(open_profile(filename))
self.gcc_list = [
'core/utils', 'core/protocol', 'core/socket', 'core/logging',
'core/master', 'core/master_utils', 'core/emperor', 'core/notify',
'core/mule', 'core/subscription', 'core/stats', 'core/sendfile',
'core/async', 'core/master_checks', 'core/fifo', 'core/offload',
'core/io', 'core/static', 'core/websockets', 'core/spooler',
'core/snmp', 'core/exceptions', 'core/config', 'core/setup_utils',
'core/clock', 'core/init', 'core/buffer', 'core/reader',
'core/writer', 'core/alarm', 'core/cron', 'core/hooks',
'core/plugins', 'core/lock', 'core/cache', 'core/daemons',
'core/errors', 'core/hash', 'core/master_events', 'core/chunked',
'core/queue', 'core/event', 'core/signal', 'core/strings',
'core/progress', 'core/timebomb', 'core/ini', 'core/fsmon',
'core/mount', 'core/metrics', 'core/plugins_builder',
'core/sharedarea', 'core/fork_server', 'core/webdav', 'core/zeus',
'core/rpc', 'core/gateway', 'core/loop', 'core/cookie',
'core/querystring', 'core/rb_timers', 'core/transformations',
'core/uwsgi',
]
# add protocols
self.gcc_list.append('proto/base')
self.gcc_list.append('proto/uwsgi')
self.gcc_list.append('proto/http')
self.gcc_list.append('proto/fastcgi')
self.gcc_list.append('proto/scgi')
self.gcc_list.append('proto/puwsgi')
self.include_path = []
if 'UWSGI_INCLUDES' in os.environ:
self.include_path += os.environ['UWSGI_INCLUDES'].split(',')
self.cflags = [
'-O2',
'-I.',
'-Wall',
'-Werror',
'-D_LARGEFILE_SOURCE',
'-D_FILE_OFFSET_BITS=64'
] + os.environ.get("CFLAGS", "").split() + self.get('cflags', '').split()
python_venv_include = os.path.join(sys.prefix, 'include', 'site',
'python{0}.{1}'.format(*sys.version_info))
if os.path.isdir(python_venv_include):
self.cflags += ['-I' + python_venv_include]
report['kernel'] = uwsgi_os
if uwsgi_os == 'Linux':
if uwsgi_cpu != 'ia64':
self.gcc_list.append('lib/linux_ns')
try:
lk_ver = uwsgi_os_k.split('.')
if int(lk_ver[0]) <= 2 and int(lk_ver[1]) <= 6 and int(lk_ver[2]) <= 9:
self.cflags.append('-DOBSOLETE_LINUX_KERNEL')
report['kernel'] = 'Old Linux'
except Exception:
pass
if uwsgi_os == 'GNU':
self.cflags.append('-D__HURD__')
gcc_version = spcall("%s -dumpversion" % GCC)
if not gcc_version and GCC.startswith('gcc'):
if uwsgi_os == 'Darwin':
GCC = 'llvm-' + GCC
else:
GCC = 'gcc'
gcc_version = spcall("%s -dumpversion" % GCC)
try:
add_it = False
cpp_include_list = str(spcall3("%s -v" % CPP)).split("\n")
for line in cpp_include_list:
if line.startswith('#include <...> search starts here:'):
add_it = True
elif line.startswith('End of search list.'):
add_it = False
elif add_it:
self.include_path.append(line.strip().split()[0])
if not self.include_path:
raise
except Exception:
self.include_path = ['/usr/include', '/usr/local/include']
additional_include_paths = self.get('additional_include_paths')
if additional_include_paths:
for ipath in additional_include_paths.split():
self.include_path.append(ipath)
if 'UWSGI_REMOVE_INCLUDES' in os.environ:
for inc in os.environ['UWSGI_REMOVE_INCLUDES'].split(','):
try:
self.include_path.remove(inc)
except ValueError:
pass
if not mute:
print("detected include path: %s" % self.include_path)
try:
gcc_version_components = gcc_version.split('.')
gcc_major = int(gcc_version_components[0])
if len(gcc_version_components) > 1:
gcc_minor = int(gcc_version_components[1])
else:
# gcc 5.0 is represented as simply "5"
gcc_minor = 0
except Exception:
raise Exception("you need a C compiler to build uWSGI")
# add -fno-strict-aliasing only on python2 and gcc < 4.3
if (sys.version_info[0] == 2) or (gcc_major < 4) or (gcc_major == 4 and gcc_minor < 3):
self.cflags += ['-fno-strict-aliasing']
if gcc_major >= 4:
self.cflags += ['-Wextra', '-Wno-unused-parameter', '-Wno-missing-field-initializers']
if gcc_major == 4 and gcc_minor < 9:
self.cflags.append('-Wno-format -Wno-format-security')
self.ldflags = os.environ.get("LDFLAGS", "").split()
self.libs = ['-lpthread', '-lm', '-rdynamic']
if uwsgi_os in ('Linux', 'GNU', 'GNU/kFreeBSD'):
self.libs.append('-ldl')
if uwsgi_os == 'GNU/kFreeBSD':
self.cflags.append('-D__GNU_kFreeBSD__')
self.libs.append('-lbsd')
# check for inherit option
inherit = self.get('inherit')
if inherit:
if '/' not in inherit:
inherit = 'buildconf/%s' % inherit
if not inherit.endswith('.ini'):
inherit = '%s.ini' % inherit
interpolations = {}
for option in self.config.options('uwsgi'):
interpolations[option] = self.get(option, default='')
iconfig = ConfigParser.ConfigParser(interpolations)
if hasattr(self.config, 'read_file'):
iconfig.read_file(open_profile(inherit))
else:
iconfig.readfp(open_profile(inherit))
for opt in iconfig.options('uwsgi'):
if not self.config.has_option('uwsgi', opt):
self.set(opt, iconfig.get('uwsgi', opt))
elif self.get(opt):
if self.get(opt).startswith('+'):
self.set(opt, iconfig.get('uwsgi', opt) + self.get(opt)[1:])
elif self.get(opt) == 'null':
self.config.remove_option('uwsgi', opt)
def set(self, key, value):
self.config.set('uwsgi', key, value)
def get(self, key, default=None):
try:
value = self.config.get('uwsgi', key)
if value == "" or value == "false":
return default
return value
except Exception:
if default is not None:
return default
return None
def depends_on(self, what, dep):
for d in dep:
if not self.get(d):
print("%s needs %s support." % (what, d))
sys.exit(1)
def has_include(self, what):
for include in self.include_path:
if os.path.exists("%s/%s" % (include, what)):
return True
return False
def get_gcll(self):
global uwsgi_version
kvm_list = ['FreeBSD', 'OpenBSD', 'NetBSD', 'DragonFly']
if 'UWSGI_PROFILE_OVERRIDE' in os.environ:
for item in os.environ['UWSGI_PROFILE_OVERRIDE'].split(';'):
k, v = item.split('=', 1)
self.set(k, v)
if 'UWSGI_AS_LIB' in os.environ:
self.set('as_shared_library', 'true')
self.set('bin_name', os.environ['UWSGI_AS_LIB'])
if self.has_include('ifaddrs.h'):
self.cflags.append('-DUWSGI_HAS_IFADDRS')
report['ifaddrs'] = True
if uwsgi_os in ('FreeBSD', 'DragonFly', 'OpenBSD'):
if self.has_include('execinfo.h') or os.path.exists('/usr/local/include/execinfo.h'):
if os.path.exists('/usr/local/include/execinfo.h'):
self.cflags.append('-I/usr/local/include')
self.ldflags.append('-L/usr/local/lib')
self.cflags.append('-DUWSGI_HAS_EXECINFO')
self.libs.append('-lexecinfo')
report['execinfo'] = True
if uwsgi_os == 'GNU/kFreeBSD':
if self.has_include('execinfo.h'):
self.cflags.append('-DUWSGI_HAS_EXECINFO')
report['execinfo'] = True
if self.has_include('zlib.h'):
self.cflags.append('-DUWSGI_ZLIB')
self.libs.append('-lz')
self.gcc_list.append('core/zlib')
report['zlib'] = True
if uwsgi_os == 'OpenBSD':
try:
obsd_major = uwsgi_os_k.split('.')[0]
obsd_minor = uwsgi_os_k.split('.')[1]
obsd_ver = int(obsd_major + obsd_minor)
if obsd_ver > 50:
self.cflags.append('-DUWSGI_NEW_OPENBSD')
report['kernel'] = 'New OpenBSD'
except Exception:
pass
if uwsgi_os == 'SunOS':
self.libs.append('-lsendfile')
self.libs.append('-lrt')
self.gcc_list.append('lib/sun_fixes')
sunos_major = int(uwsgi_os_k.split('.')[0])
sunos_minor = int(uwsgi_os_k.split('.')[1])
# solaris < 11 does not have sethostname declared in unistd
if not (sunos_major == 5 and sunos_minor > 10):
self.cflags.append('-DUWSGI_SUNOS_EXTERN_SETHOSTNAME')
self.ldflags.append('-L/lib')
if not uwsgi_os_v.startswith('Nexenta'):
self.libs.remove('-rdynamic')
if uwsgi_os == 'GNU/kFreeBSD':
if self.has_include('kvm.h'):
kvm_list.append('GNU/kFreeBSD')
if uwsgi_os in kvm_list:
self.libs.append('-lkvm')
if uwsgi_os == 'Haiku':
self.libs.remove('-rdynamic')
self.libs.remove('-lpthread')
self.libs.append('-lroot')
if uwsgi_os == 'Darwin':
if uwsgi_os_k.startswith('8'):
self.cflags.append('-DUNSETENV_VOID')
self.cflags.append('-DNO_SENDFILE')
self.cflags.append('-DNO_EXECINFO')
self.cflags.append('-DOLD_REALPATH')
darwin_major = int(uwsgi_os_k.split('.')[0])
# MacOS High Sierra and above: since XCode 10 there's no libgcc_s.10.5
if darwin_major >= 17:
self.cflags.append('-mmacosx-version-min=10.9')
else:
self.cflags.append('-mmacosx-version-min=10.5')
if GCC in ('clang',):
self.libs.remove('-rdynamic')
if uwsgi_os.startswith('CYGWIN'):
self.libs.remove('-rdynamic')
# compile extras
extras = self.get('extras', None)
if extras:
for extra in extras.split(','):
self.gcc_list.append(extra)
# check for usable ucontext
report['ucontext'] = has_usable_ucontext()
# set locking subsystem
locking_mode = self.get('locking', 'auto')
if locking_mode == 'auto':
if uwsgi_os == 'Linux' or uwsgi_os == 'SunOS':
locking_mode = 'pthread_mutex'
# FreeBSD umtx is still not ready for process shared locking
# starting from FreeBSD 9 posix semaphores can be shared between processes
elif uwsgi_os in ('FreeBSD', 'GNU/kFreeBSD'):
try:
fbsd_major = int(uwsgi_os_k.split('.')[0])
if fbsd_major >= 9:
locking_mode = 'posix_sem'
except Exception:
pass
elif uwsgi_os == 'GNU':
locking_mode = 'posix_sem'
elif uwsgi_os == 'Darwin':
locking_mode = 'osx_spinlock'
elif uwsgi_os.startswith('CYGWIN'):
locking_mode = 'windows_mutex'
if locking_mode == 'pthread_mutex':
self.cflags.append('-DUWSGI_LOCK_USE_MUTEX')
# FreeBSD umtx is still not ready for process shared locking
elif locking_mode == 'posix_sem':
self.cflags.append('-DUWSGI_LOCK_USE_POSIX_SEM')
elif locking_mode == 'osx_spinlock':
self.cflags.append('-DUWSGI_LOCK_USE_OSX_SPINLOCK')
elif locking_mode == 'windows_mutex':
self.cflags.append('-DUWSGI_LOCK_USE_WINDOWS_MUTEX')
else:
self.cflags.append('-DUWSGI_IPCSEM_ATEXIT')
if locking_mode == 'auto':
report['locking'] = 'sysv semaphores'
else:
report['locking'] = locking_mode
# set event subsystem
event_mode = self.get('event', 'auto')
if event_mode == 'auto':
if uwsgi_os == 'Linux':
event_mode = 'epoll'
if uwsgi_os == 'SunOS':
event_mode = 'devpoll'
sun_major, sun_minor = uwsgi_os_k.split('.')
if int(sun_major) >= 5:
if int(sun_minor) >= 10:
event_mode = 'port'
elif uwsgi_os in ('Darwin', 'FreeBSD', 'GNU/kFreeBSD', 'OpenBSD', 'NetBSD', 'DragonFly'):
event_mode = 'kqueue'
elif uwsgi_os.startswith('CYGWIN') or uwsgi_os == 'GNU':
event_mode = 'poll'
if event_mode == 'epoll':
self.cflags.append('-DUWSGI_EVENT_USE_EPOLL')
elif event_mode == 'kqueue':
self.cflags.append('-DUWSGI_EVENT_USE_KQUEUE')
elif event_mode == 'devpoll':
self.cflags.append('-DUWSGI_EVENT_USE_DEVPOLL')
elif event_mode == 'port':
self.cflags.append('-DUWSGI_EVENT_USE_PORT')
elif event_mode == 'poll':
self.cflags.append('-DUWSGI_EVENT_USE_POLL')