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