Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / pybind / rados / setup.py
1 from __future__ import print_function
2
3 import os
4 import pkgutil
5 import shutil
6 import subprocess
7 import sys
8 import tempfile
9 import textwrap
10
11 if not pkgutil.find_loader('setuptools'):
12     from distutils.core import setup
13     from distutils.extension import Extension
14 else:
15     from setuptools import setup
16     from setuptools.extension import Extension
17
18 from distutils.ccompiler import new_compiler
19 from distutils.errors import CompileError, LinkError
20 from distutils.sysconfig import customize_compiler
21
22 # PEP 440 versioning of the Rados package on PyPI
23 # Bump this version, after every changeset
24 # NOTE: This version is not the same as get_ceph_version()
25
26 __version__ = '2.0.0'
27
28
29 def get_ceph_version():
30     try:
31         for line in open(os.path.join(os.path.dirname(__file__), "..", "..", "ceph_ver.h")):
32             if "CEPH_GIT_NICE_VER" in line:
33                 return line.split()[2].strip('"')
34         else:
35             return "0"
36     except IOError:
37         return "0"
38
39
40 def get_python_flags():
41     cflags = {'I': [], 'extras': []}
42     ldflags = {'l': [], 'L': [], 'extras': []}
43
44     if os.environ.get('VIRTUAL_ENV', None):
45         python = "python"
46     else:
47         python = 'python' + str(sys.version_info.major) + '.' + str(sys.version_info.minor)
48
49     python_config = python + '-config'
50
51     for cflag in subprocess.check_output(
52             [python_config, "--cflags"]
53     ).strip().decode('utf-8').split():
54         if cflag.startswith('-I'):
55             cflags['I'].append(cflag.replace('-I', ''))
56         else:
57             cflags['extras'].append(cflag)
58
59     for ldflag in subprocess.check_output(
60             [python_config, "--ldflags"]
61     ).strip().decode('utf-8').split():
62         if ldflag.startswith('-l'):
63             ldflags['l'].append(ldflag.replace('-l', ''))
64         if ldflag.startswith('-L'):
65             ldflags['L'].append(ldflag.replace('-L', ''))
66         else:
67             ldflags['extras'].append(ldflag)
68
69     return {
70         'cflags': cflags,
71         'ldflags': ldflags
72     }
73
74
75 def check_sanity():
76     """
77     Test if development headers and library for rados is available by compiling a dummy C program.
78     """
79     CEPH_SRC_DIR = os.path.join(
80         os.path.dirname(os.path.abspath(__file__)),
81         '..',
82         '..'
83     )
84
85     tmp_dir = tempfile.mkdtemp(dir=os.environ.get('TMPDIR', os.path.dirname(__file__)))
86     tmp_file = os.path.join(tmp_dir, 'rados_dummy.c')
87
88     with open(tmp_file, 'w') as fp:
89         dummy_prog = textwrap.dedent("""
90         #include <rados/librados.h>
91
92         int main(void) {
93             rados_t cluster;
94             rados_create(&cluster, NULL);
95             return 0;
96         }
97         """)
98         fp.write(dummy_prog)
99
100     compiler = new_compiler()
101     customize_compiler(compiler)
102
103     if {'MAKEFLAGS', 'MFLAGS', 'MAKELEVEL'}.issubset(set(os.environ.keys())):
104         # The setup.py has been invoked by a top-level Ceph make.
105         # Set the appropriate CFLAGS and LDFLAGS
106
107         compiler.set_include_dirs([os.path.join(CEPH_SRC_DIR, 'include')])
108         compiler.set_library_dirs([os.environ.get('CEPH_LIBDIR')])
109
110     try:
111         link_objects = compiler.compile(
112             sources=[tmp_file],
113             output_dir=tmp_dir
114         )
115         compiler.link_executable(
116             objects=link_objects,
117             output_progname=os.path.join(tmp_dir, 'rados_dummy'),
118             libraries=['rados'],
119             output_dir=tmp_dir,
120         )
121
122     except CompileError:
123         print('\nCompile Error: RADOS development headers not found', file=sys.stderr)
124         return False
125     except LinkError:
126         print('\nLink Error: RADOS library not found', file=sys.stderr)
127         return False
128     else:
129         return True
130     finally:
131         shutil.rmtree(tmp_dir)
132
133
134 if 'BUILD_DOC' in os.environ.keys():
135     pass
136 elif check_sanity():
137     pass
138 else:
139     sys.exit(1)
140
141 cmdclass = {}
142 try:
143     from Cython.Build import cythonize
144     from Cython.Distutils import build_ext
145
146     cmdclass = {'build_ext': build_ext}
147 except ImportError:
148     print("WARNING: Cython is not installed.")
149
150     if not os.path.isfile('rados.c'):
151         print('ERROR: Cannot find Cythonized file rados.c', file=sys.stderr)
152         sys.exit(1)
153     else:
154         def cythonize(x, **kwargs):
155             return x
156
157         source = "rados.c"
158 else:
159     source = "rados.pyx"
160
161 # Disable cythonification if we're not really building anything
162 if (len(sys.argv) >= 2 and
163         any(i in sys.argv[1:] for i in ('--help', 'clean', 'egg_info', '--version')
164             )):
165     def cythonize(x, **kwargs):
166         return x
167
168 flags = get_python_flags()
169
170 setup(
171     name='rados',
172     version=__version__,
173     description="Python bindings for the Ceph librados library",
174     long_description=(
175         "This package contains Python bindings for interacting with Ceph's "
176         "RADOS library. RADOS is a reliable, autonomic distributed object "
177         "storage cluster developed as part of the Ceph distributed storage "
178         "system. This is a shared library allowing applications to access "
179         "the distributed object store using a simple file-like interface."
180     ),
181     url='https://github.com/ceph/ceph/tree/master/src/pybind/rados',
182     license='LGPLv2+',
183     platforms='Linux',
184     ext_modules=cythonize(
185         [
186             Extension(
187                 "rados",
188                 [source],
189                 include_dirs=flags['cflags']['I'],
190                 library_dirs=flags['ldflags']['L'],
191                 libraries=["rados"] + flags['ldflags']['l'],
192                 extra_compile_args=flags['cflags']['extras'] + flags['ldflags']['extras'],
193             )
194         ], build_dir=os.environ.get("CYTHON_BUILD_DIR", None)
195     ),
196     classifiers=[
197         'Intended Audience :: Developers',
198         'Intended Audience :: System Administrators',
199         'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)',
200         'Operating System :: POSIX :: Linux',
201         'Programming Language :: Cython',
202         'Programming Language :: Python :: 2.7',
203         'Programming Language :: Python :: 3.4',
204         'Programming Language :: Python :: 3.5'
205     ],
206     cmdclass=cmdclass,
207 )