Imported Upstream version 1.24.3
[platform/upstream/grpc.git] / setup.py
1 # Copyright 2015 gRPC authors.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 """A setup module for the GRPC Python package."""
16 from distutils import cygwinccompiler
17 from distutils import extension as _extension
18 from distutils import util
19 import os
20 import os.path
21 import pkg_resources
22 import platform
23 import re
24 import shlex
25 import shutil
26 import sys
27 import sysconfig
28
29 import setuptools
30 from setuptools.command import egg_info
31
32 import subprocess
33 from subprocess import PIPE
34
35 # Redirect the manifest template from MANIFEST.in to PYTHON-MANIFEST.in.
36 egg_info.manifest_maker.template = 'PYTHON-MANIFEST.in'
37
38 PY3 = sys.version_info.major == 3
39 PYTHON_STEM = os.path.join('src', 'python', 'grpcio')
40 CORE_INCLUDE = ('include', '.',)
41 ADDRESS_SORTING_INCLUDE = (os.path.join('third_party', 'address_sorting', 'include'),)
42 CARES_INCLUDE = (
43     os.path.join('third_party', 'cares'),
44     os.path.join('third_party', 'cares', 'cares'),)
45 if 'darwin' in sys.platform:
46   CARES_INCLUDE += (os.path.join('third_party', 'cares', 'config_darwin'),)
47 if 'freebsd' in sys.platform:
48   CARES_INCLUDE += (os.path.join('third_party', 'cares', 'config_freebsd'),)
49 if 'linux' in sys.platform:
50   CARES_INCLUDE += (os.path.join('third_party', 'cares', 'config_linux'),)
51 if 'openbsd' in sys.platform:
52   CARES_INCLUDE += (os.path.join('third_party', 'cares', 'config_openbsd'),)
53 SSL_INCLUDE = (os.path.join('third_party', 'boringssl', 'include'),)
54 UPB_INCLUDE = (os.path.join('third_party', 'upb'),)
55 UPB_GRPC_GENERATED_INCLUDE = (os.path.join('src', 'core', 'ext', 'upb-generated'),)
56 ZLIB_INCLUDE = (os.path.join('third_party', 'zlib'),)
57 README = os.path.join(PYTHON_STEM, 'README.rst')
58
59 # Ensure we're in the proper directory whether or not we're being used by pip.
60 os.chdir(os.path.dirname(os.path.abspath(__file__)))
61 sys.path.insert(0, os.path.abspath(PYTHON_STEM))
62
63 # Break import-style to ensure we can actually find our in-repo dependencies.
64 import _parallel_compile_patch
65 import _spawn_patch
66 import commands
67 import grpc_core_dependencies
68 import grpc_version
69
70 _parallel_compile_patch.monkeypatch_compile_maybe()
71 _spawn_patch.monkeypatch_spawn()
72
73 LICENSE = 'Apache License 2.0'
74
75 CLASSIFIERS = [
76     'Development Status :: 5 - Production/Stable',
77     'Programming Language :: Python',
78     'Programming Language :: Python :: 2',
79     'Programming Language :: Python :: 2.7',
80     'Programming Language :: Python :: 3',
81     'Programming Language :: Python :: 3.4',
82     'Programming Language :: Python :: 3.5',
83     'Programming Language :: Python :: 3.6',
84     'Programming Language :: Python :: 3.7',
85     'Programming Language :: Python :: 3.8',
86     'License :: OSI Approved :: Apache Software License',
87 ]
88
89 # Environment variable to determine whether or not the Cython extension should
90 # *use* Cython or use the generated C files. Note that this requires the C files
91 # to have been generated by building first *with* Cython support. Even if this
92 # is set to false, if the script detects that the generated `.c` file isn't
93 # present, then it will still attempt to use Cython.
94 BUILD_WITH_CYTHON = os.environ.get('GRPC_PYTHON_BUILD_WITH_CYTHON', False)
95
96
97 # Export this variable to use the system installation of openssl. You need to
98 # have the header files installed (in /usr/include/openssl) and during
99 # runtime, the shared library must be installed
100 BUILD_WITH_SYSTEM_OPENSSL = os.environ.get('GRPC_PYTHON_BUILD_SYSTEM_OPENSSL',
101                                            False)
102
103 # Export this variable to use the system installation of zlib. You need to
104 # have the header files installed (in /usr/include/) and during
105 # runtime, the shared library must be installed
106 BUILD_WITH_SYSTEM_ZLIB = os.environ.get('GRPC_PYTHON_BUILD_SYSTEM_ZLIB',
107                                         False)
108
109 # Export this variable to use the system installation of cares. You need to
110 # have the header files installed (in /usr/include/) and during
111 # runtime, the shared library must be installed
112 BUILD_WITH_SYSTEM_CARES = os.environ.get('GRPC_PYTHON_BUILD_SYSTEM_CARES',
113                                          False)
114
115 # For local development use only: This skips building gRPC Core and its
116 # dependencies, including protobuf and boringssl. This allows "incremental"
117 # compilation by first building gRPC Core using make, then building only the
118 # Python/Cython layers here.
119 #
120 # Note that this requires libboringssl.a in the libs/{dbg,opt}/ directory, which
121 # may require configuring make to not use the system openssl implementation:
122 #
123 #    make HAS_SYSTEM_OPENSSL_ALPN=0
124 #
125 # TODO(ericgribkoff) Respect the BUILD_WITH_SYSTEM_* flags alongside this option
126 USE_PREBUILT_GRPC_CORE = os.environ.get(
127     'GRPC_PYTHON_USE_PREBUILT_GRPC_CORE', False)
128
129
130 # If this environmental variable is set, GRPC will not try to be compatible with
131 # libc versions old than the one it was compiled against.
132 DISABLE_LIBC_COMPATIBILITY = os.environ.get('GRPC_PYTHON_DISABLE_LIBC_COMPATIBILITY', False)
133
134 # Environment variable to determine whether or not to enable coverage analysis
135 # in Cython modules.
136 ENABLE_CYTHON_TRACING = os.environ.get(
137     'GRPC_PYTHON_ENABLE_CYTHON_TRACING', False)
138
139 # Environment variable specifying whether or not there's interest in setting up
140 # documentation building.
141 ENABLE_DOCUMENTATION_BUILD = os.environ.get(
142     'GRPC_PYTHON_ENABLE_DOCUMENTATION_BUILD', False)
143
144 def check_linker_need_libatomic():
145   """Test if linker on system needs libatomic."""
146   code_test = (b'#include <atomic>\n' +
147                b'int main() { return std::atomic<int64_t>{}; }')
148   cc_test = subprocess.Popen(['cc', '-x', 'c++', '-std=c++11', '-'],
149                              stdin=PIPE,
150                              stdout=PIPE,
151                              stderr=PIPE)
152   cc_test.communicate(input=code_test)
153   return cc_test.returncode != 0
154
155 # There are some situations (like on Windows) where CC, CFLAGS, and LDFLAGS are
156 # entirely ignored/dropped/forgotten by distutils and its Cygwin/MinGW support.
157 # We use these environment variables to thus get around that without locking
158 # ourselves in w.r.t. the multitude of operating systems this ought to build on.
159 # We can also use these variables as a way to inject environment-specific
160 # compiler/linker flags. We assume GCC-like compilers and/or MinGW as a
161 # reasonable default.
162 EXTRA_ENV_COMPILE_ARGS = os.environ.get('GRPC_PYTHON_CFLAGS', None)
163 EXTRA_ENV_LINK_ARGS = os.environ.get('GRPC_PYTHON_LDFLAGS', None)
164 if EXTRA_ENV_COMPILE_ARGS is None:
165   EXTRA_ENV_COMPILE_ARGS = ' -std=c++11'
166   if 'win32' in sys.platform:
167     if sys.version_info < (3, 5):
168       EXTRA_ENV_COMPILE_ARGS += ' -D_hypot=hypot'
169       # We use define flags here and don't directly add to DEFINE_MACROS below to
170       # ensure that the expert user/builder has a way of turning it off (via the
171       # envvars) without adding yet more GRPC-specific envvars.
172       # See https://sourceforge.net/p/mingw-w64/bugs/363/
173       if '32' in platform.architecture()[0]:
174         EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime32 -D_timeb=__timeb32 -D_ftime_s=_ftime32_s'
175       else:
176         EXTRA_ENV_COMPILE_ARGS += ' -D_ftime=_ftime64 -D_timeb=__timeb64'
177     else:
178       # We need to statically link the C++ Runtime, only the C runtime is
179       # available dynamically
180       EXTRA_ENV_COMPILE_ARGS += ' /MT'
181   elif "linux" in sys.platform:
182     EXTRA_ENV_COMPILE_ARGS += ' -std=gnu99 -fvisibility=hidden -fno-wrapv -fno-exceptions'
183   elif "darwin" in sys.platform:
184     EXTRA_ENV_COMPILE_ARGS += ' -stdlib=libc++ -fvisibility=hidden -fno-wrapv -fno-exceptions'
185
186 if EXTRA_ENV_LINK_ARGS is None:
187   EXTRA_ENV_LINK_ARGS = ''
188   if "linux" in sys.platform or "darwin" in sys.platform:
189     EXTRA_ENV_LINK_ARGS += ' -lpthread'
190     if check_linker_need_libatomic():
191       EXTRA_ENV_LINK_ARGS += ' -latomic'
192   elif "win32" in sys.platform and sys.version_info < (3, 5):
193     msvcr = cygwinccompiler.get_msvcr()[0]
194     # TODO(atash) sift through the GCC specs to see if libstdc++ can have any
195     # influence on the linkage outcome on MinGW for non-C++ programs.
196     EXTRA_ENV_LINK_ARGS += (
197         ' -static-libgcc -static-libstdc++ -mcrtdll={msvcr}'
198         ' -static'.format(msvcr=msvcr))
199   if "linux" in sys.platform:
200     EXTRA_ENV_LINK_ARGS += ' -Wl,-wrap,memcpy -static-libgcc'
201
202 EXTRA_COMPILE_ARGS = shlex.split(EXTRA_ENV_COMPILE_ARGS)
203 EXTRA_LINK_ARGS = shlex.split(EXTRA_ENV_LINK_ARGS)
204
205 CYTHON_EXTENSION_PACKAGE_NAMES = ()
206
207 CYTHON_EXTENSION_MODULE_NAMES = ('grpc._cython.cygrpc',)
208
209 CYTHON_HELPER_C_FILES = ()
210
211 CORE_C_FILES = tuple(grpc_core_dependencies.CORE_SOURCE_FILES)
212 if "win32" in sys.platform:
213   CORE_C_FILES = filter(lambda x: 'third_party/cares' not in x, CORE_C_FILES)
214
215 if BUILD_WITH_SYSTEM_OPENSSL:
216   CORE_C_FILES = filter(lambda x: 'third_party/boringssl' not in x, CORE_C_FILES)
217   CORE_C_FILES = filter(lambda x: 'src/boringssl' not in x, CORE_C_FILES)
218   SSL_INCLUDE = (os.path.join('/usr', 'include', 'openssl'),)
219
220 if BUILD_WITH_SYSTEM_ZLIB:
221   CORE_C_FILES = filter(lambda x: 'third_party/zlib' not in x, CORE_C_FILES)
222   ZLIB_INCLUDE = (os.path.join('/usr', 'include'),)
223
224 if BUILD_WITH_SYSTEM_CARES:
225   CORE_C_FILES = filter(lambda x: 'third_party/cares' not in x, CORE_C_FILES)
226   CARES_INCLUDE = (os.path.join('/usr', 'include'),)
227
228 EXTENSION_INCLUDE_DIRECTORIES = (
229     (PYTHON_STEM,) +
230     CORE_INCLUDE +
231     ADDRESS_SORTING_INCLUDE +
232     CARES_INCLUDE +
233     SSL_INCLUDE +
234     UPB_INCLUDE +
235     UPB_GRPC_GENERATED_INCLUDE +
236     ZLIB_INCLUDE)
237
238 EXTENSION_LIBRARIES = ()
239 if "linux" in sys.platform:
240   EXTENSION_LIBRARIES += ('rt',)
241 if not "win32" in sys.platform:
242   EXTENSION_LIBRARIES += ('m',)
243 if "win32" in sys.platform:
244   EXTENSION_LIBRARIES += ('advapi32', 'ws2_32',)
245 if BUILD_WITH_SYSTEM_OPENSSL:
246   EXTENSION_LIBRARIES += ('ssl', 'crypto',)
247 if BUILD_WITH_SYSTEM_ZLIB:
248   EXTENSION_LIBRARIES += ('z',)
249 if BUILD_WITH_SYSTEM_CARES:
250   EXTENSION_LIBRARIES += ('cares',)
251
252 DEFINE_MACROS = (('OPENSSL_NO_ASM', 1), ('_WIN32_WINNT', 0x600))
253 if not DISABLE_LIBC_COMPATIBILITY:
254   DEFINE_MACROS += (('GPR_BACKWARDS_COMPATIBILITY_MODE', 1),)
255 if "win32" in sys.platform:
256   # TODO(zyc): Re-enable c-ares on x64 and x86 windows after fixing the
257   # ares_library_init compilation issue
258   DEFINE_MACROS += (('WIN32_LEAN_AND_MEAN', 1), ('CARES_STATICLIB', 1),
259                     ('GRPC_ARES', 0), ('NTDDI_VERSION', 0x06000000),
260                     ('NOMINMAX', 1),)
261   if '64bit' in platform.architecture()[0]:
262     DEFINE_MACROS += (('MS_WIN64', 1),)
263   elif sys.version_info >= (3, 5):
264     # For some reason, this is needed to get access to inet_pton/inet_ntop
265     # on msvc, but only for 32 bits
266     DEFINE_MACROS += (('NTDDI_VERSION', 0x06000000),)
267 else:
268   DEFINE_MACROS += (('HAVE_CONFIG_H', 1), ('GRPC_ENABLE_FORK_SUPPORT', 1),)
269
270 LDFLAGS = tuple(EXTRA_LINK_ARGS)
271 CFLAGS = tuple(EXTRA_COMPILE_ARGS)
272 if "linux" in sys.platform or "darwin" in sys.platform:
273   pymodinit_type = 'PyObject*' if PY3 else 'void'
274   pymodinit = 'extern "C" __attribute__((visibility ("default"))) {}'.format(pymodinit_type)
275   DEFINE_MACROS += (('PyMODINIT_FUNC', pymodinit),)
276   DEFINE_MACROS += (('GRPC_POSIX_FORK_ALLOW_PTHREAD_ATFORK', 1),)
277
278 # By default, Python3 distutils enforces compatibility of
279 # c plugins (.so files) with the OSX version Python3 was built with.
280 # For Python3.4, this is OSX 10.6, but we need Thread Local Support (__thread)
281 if 'darwin' in sys.platform and PY3:
282   mac_target = sysconfig.get_config_var('MACOSX_DEPLOYMENT_TARGET')
283   if mac_target and (pkg_resources.parse_version(mac_target) <
284                      pkg_resources.parse_version('10.7.0')):
285     os.environ['MACOSX_DEPLOYMENT_TARGET'] = '10.7'
286     os.environ['_PYTHON_HOST_PLATFORM'] = re.sub(
287         r'macosx-[0-9]+\.[0-9]+-(.+)',
288         r'macosx-10.7-\1',
289         util.get_platform())
290
291 def cython_extensions_and_necessity():
292   cython_module_files = [os.path.join(PYTHON_STEM,
293                                name.replace('.', '/') + '.pyx')
294                   for name in CYTHON_EXTENSION_MODULE_NAMES]
295   config = os.environ.get('CONFIG', 'opt')
296   prefix = 'libs/' + config + '/'
297   if USE_PREBUILT_GRPC_CORE:
298     extra_objects = [prefix + 'libares.a',
299                      prefix + 'libboringssl.a',
300                      prefix + 'libgpr.a',
301                      prefix + 'libgrpc.a']
302     core_c_files = []
303   else:
304     core_c_files = list(CORE_C_FILES)
305     extra_objects = []
306   extensions = [
307       _extension.Extension(
308           name=module_name,
309           sources=[module_file] + list(CYTHON_HELPER_C_FILES) + core_c_files,
310           include_dirs=list(EXTENSION_INCLUDE_DIRECTORIES),
311           libraries=list(EXTENSION_LIBRARIES),
312           define_macros=list(DEFINE_MACROS),
313           extra_objects=extra_objects,
314           extra_compile_args=list(CFLAGS),
315           extra_link_args=list(LDFLAGS),
316       ) for (module_name, module_file) in zip(list(CYTHON_EXTENSION_MODULE_NAMES), cython_module_files)
317   ]
318   need_cython = BUILD_WITH_CYTHON
319   if not BUILD_WITH_CYTHON:
320     need_cython = need_cython or not commands.check_and_update_cythonization(extensions)
321   return commands.try_cythonize(extensions, linetracing=ENABLE_CYTHON_TRACING, mandatory=BUILD_WITH_CYTHON), need_cython
322
323 CYTHON_EXTENSION_MODULES, need_cython = cython_extensions_and_necessity()
324
325 PACKAGE_DIRECTORIES = {
326     '': PYTHON_STEM,
327 }
328
329 INSTALL_REQUIRES = (
330     "six>=1.5.2",
331     "futures>=2.2.0; python_version<'3.2'",
332     "enum34>=1.0.4; python_version<'3.4'",
333 )
334
335 SETUP_REQUIRES = INSTALL_REQUIRES + (
336     'Sphinx~=1.8.1',
337     'six>=1.10',
338   ) if ENABLE_DOCUMENTATION_BUILD else ()
339
340 try:
341   import Cython
342 except ImportError:
343   if BUILD_WITH_CYTHON:
344     sys.stderr.write(
345       "You requested a Cython build via GRPC_PYTHON_BUILD_WITH_CYTHON, "
346       "but do not have Cython installed. We won't stop you from using "
347       "other commands, but the extension files will fail to build.\n")
348   elif need_cython:
349     sys.stderr.write(
350         'We could not find Cython. Setup may take 10-20 minutes.\n')
351     SETUP_REQUIRES += ('cython>=0.23',)
352
353 COMMAND_CLASS = {
354     'doc': commands.SphinxDocumentation,
355     'build_project_metadata': commands.BuildProjectMetadata,
356     'build_py': commands.BuildPy,
357     'build_ext': commands.BuildExt,
358     'gather': commands.Gather,
359 }
360
361 # Ensure that package data is copied over before any commands have been run:
362 credentials_dir = os.path.join(PYTHON_STEM, 'grpc', '_cython', '_credentials')
363 try:
364   os.mkdir(credentials_dir)
365 except OSError:
366   pass
367 shutil.copyfile(os.path.join('etc', 'roots.pem'),
368                 os.path.join(credentials_dir, 'roots.pem'))
369
370 PACKAGE_DATA = {
371     # Binaries that may or may not be present in the final installation, but are
372     # mentioned here for completeness.
373     'grpc._cython': [
374         '_credentials/roots.pem',
375         '_windows/grpc_c.32.python',
376         '_windows/grpc_c.64.python',
377     ],
378 }
379 PACKAGES = setuptools.find_packages(PYTHON_STEM)
380
381 setuptools.setup(
382   name='grpcio',
383   version=grpc_version.VERSION,
384   description='HTTP/2-based RPC framework',
385   author='The gRPC Authors',
386   author_email='grpc-io@googlegroups.com',
387   url='https://grpc.io',
388   license=LICENSE,
389   classifiers=CLASSIFIERS,
390   long_description=open(README).read(),
391   ext_modules=CYTHON_EXTENSION_MODULES,
392   packages=list(PACKAGES),
393   package_dir=PACKAGE_DIRECTORIES,
394   package_data=PACKAGE_DATA,
395   install_requires=INSTALL_REQUIRES,
396   setup_requires=SETUP_REQUIRES,
397   cmdclass=COMMAND_CLASS,
398 )