CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
setup.py
Go to the documentation of this file.
1"""Build the cmsdk3 wheel: the full CMSDK SWIG binding (_cmsdk3 + cmsdk3.py) as one stable-ABI (abi3)
2extension per platform, so `pip install cmsdk3` works on Python 3.10 and every later 3.x.
3
4The extension is compiled from the CMSDK C++ sources directly (no prebuilt libCMSDK.a), with a SWIG
5wrapper generated here for the target OS (the committed src/cmsdk3_wrap.cxx is LP64/Linux-flavoured).
6SWIG comes from the PyPI `swig` package (build requirement), so the same recipe runs on Linux, macOS and
7Windows. Used by cibuildwheel (see pyproject.toml), or locally: `pip wheel CMSDK/python-wheel`.
8
9Environment knobs:
10 CMSDK_ROOT path to the CMSDK tree (default: the parent dir, or ./cmsdk-src in an sdist)
11 CMSDK_NO_SSL=1 build without OpenSSL (no https/wss/SSL connections in the binding)
12 CMSDK_OPENSSL_DIR OpenSSL prefix (include/ + lib/) when it is not on the default paths
13 CMSDK_OPENSSL_INCLUDE, CMSDK_OPENSSL_LIB separate include and lib dirs (e.g. Windows release-static/lib)
14 CMSDK_JOBS parallel compile jobs (default: CPU count)
15"""
16import os
17import platform
18import shutil
19import subprocess
20import sys
21from concurrent.futures import ThreadPoolExecutor
22
23from setuptools import Extension, setup
24from setuptools.command.build_ext import build_ext
25
26HERE = os.path.dirname(os.path.abspath(__file__))
27PY_LIMITED_API = "0x030A0000" # Python 3.10, as PYTHON3ABI in CMSDK/Makefile.sys
28
29
31 for cand in (os.environ.get("CMSDK_ROOT"), os.path.join(HERE, "cmsdk-src"), os.path.dirname(HERE)):
32 if cand and os.path.isfile(os.path.join(cand, "cmsdk.i")):
33 return os.path.abspath(cand)
34 sys.exit("cmsdk3 wheel: CMSDK sources not found (set CMSDK_ROOT)")
35
36
37ROOT = find_root()
38GEN = os.path.join(HERE, "build", "swig") # generated wrapper + cmsdk3.py
39SRC = os.path.join(HERE, "build", "cmsdk") # copy of ROOT/src + ROOT/include, so every source path is relative
40
41# Same file list as CPPFILES in CMSDK/Makefile (the static library), minus nothing: the wrapper may reach
42# any exported class.
43CPPFILES = """
44ComponentMemory.cpp ConsoleOutput.cpp
45DataMapsMemory.cpp DataMessage.cpp MemoryController.cpp TemporalMemory.cpp HTML.cpp
46MemoryRequestConnection.cpp MemoryRequestServer.cpp MemoryRequestQueues.cpp
47MemoryCommander.cpp MemoryManager.cpp NetworkConnections.cpp
48NetworkManager.cpp NetworkProtocols.cpp ProcessMemory.cpp ProcessMemoryFuzz.cpp ProcessMemoryConcFuzz.cpp PsyAPI.cpp
49PsyInternal.cpp PsySpace.cpp PsySSL.cpp PsyTime.cpp Subscriptions.cpp
50ThreadManager.cpp MovingAverage.cpp UnitTest_CMSDK.cpp UnitTestFramework.cpp Utils.cpp Stats.cpp
51xml_parser.cpp MessageIndex.cpp jsmn.cpp Bitmap.cpp Base64.cpp Observations.cpp VantagePoints.cpp
52LLMConnection.cpp
53RequestGateway.cpp RequestClient.cpp RequestExecutor.cpp RESTAPI.cpp MathClasses.cpp MessagePlayer.cpp
54hash/keccak.cpp hash/sha3.cpp hash/crc32.cpp hash/md5.cpp hash/sha1.cpp hash/sha256.cpp hash/HashTest.cpp
55""".split()
56
57IS_WIN = sys.platform == "win32"
58IS_MAC = sys.platform == "darwin"
59IS_LINUX = sys.platform.startswith("linux")
60USE_SSL = os.environ.get("CMSDK_NO_SSL", "") not in ("1", "true", "yes")
61
62
64 exe = shutil.which("swig")
65 if exe:
66 return exe
67 try: # PyPI `swig` package: the binary lives inside the package
68 import swig # noqa: F401
69 exe = os.path.join(os.path.dirname(swig.__file__), "data", "bin", "swig.exe" if IS_WIN else "swig")
70 if os.path.isfile(exe):
71 return exe
72 except ImportError:
73 pass
74 sys.exit("cmsdk3 wheel: swig not found (pip install swig)")
75
76
78 """Run SWIG for this OS and make the wrapper limited-API clean (as `make swig3` does)."""
79 os.makedirs(GEN, exist_ok=True)
80 wrap = os.path.join(GEN, "cmsdk3_wrap.cxx")
81 py = os.path.join(GEN, "cmsdk3.py")
82 iface = os.path.join(ROOT, "cmsdk.i")
83 if os.path.isfile(wrap) and os.path.isfile(py) and os.path.getmtime(wrap) >= os.path.getmtime(iface):
84 return wrap
85 cmd = [find_swig(), "-c++", "-python"]
86 # int64 is 'long' only on 64-bit Linux (LP64 + CMSDK Types.h); see SWIGWORDFLAG in Makefile.sys
87 if IS_LINUX and sys.maxsize > 2**32:
88 cmd.append("-DSWIGWORDSIZE64")
89 cmd += ["-module", "cmsdk3", "-I" + os.path.join(ROOT, "include"), "-outdir", GEN, "-o", wrap, iface]
90 print("cmsdk3 wheel: " + " ".join(cmd), flush=True)
91 subprocess.check_call(cmd)
92 subprocess.check_call([sys.executable, os.path.join(ROOT, "tools", "swig_limited_api.py"), wrap])
93 return wrap
94
95
97 inc, lib = [], []
98 if os.environ.get("CMSDK_OPENSSL_INCLUDE") or os.environ.get("CMSDK_OPENSSL_LIB"):
99 return ([os.environ["CMSDK_OPENSSL_INCLUDE"]] if os.environ.get("CMSDK_OPENSSL_INCLUDE") else [],
100 [os.environ["CMSDK_OPENSSL_LIB"]] if os.environ.get("CMSDK_OPENSSL_LIB") else [])
101 pref = os.environ.get("CMSDK_OPENSSL_DIR")
102 if not pref and IS_MAC:
103 for f in ("openssl@3", "openssl"):
104 try:
105 pref = subprocess.check_output(["brew", "--prefix", f], text=True, stderr=subprocess.DEVNULL).strip()
106 break
107 except Exception:
108 pass
109 if pref:
110 inc.append(os.path.join(pref, "include"))
111 lib.append(os.path.join(pref, "lib64" if os.path.isdir(os.path.join(pref, "lib64")) else "lib"))
112 return inc, lib
113
114
116 """Mirror ROOT/src and ROOT/include under build/cmsdk: setuptools refuses absolute source paths, and a
117 relative path with '..' would put object files outside the build dir (or fail across Windows drives)."""
118 for d in ("src", "include"):
119 shutil.copytree(os.path.join(ROOT, d), os.path.join(SRC, d), dirs_exist_ok=True,
120 ignore=shutil.ignore_patterns("*.o", "*.obj", "__pycache__"))
121
122
124 wrap = generate_wrapper()
126 files = CPPFILES + (["direntwin.cpp"] if IS_WIN else []) # opendir/readdir for Windows (CMSDK.vs2022.vcxproj)
127 sources = [os.path.relpath(p, HERE) for p in [wrap] + [os.path.join(SRC, "src", f) for f in files]]
128 macros = [("Py_LIMITED_API", PY_LIMITED_API), ("SWIG_PYTHON_INTERPRETER_NO_DEBUG", None), ("PSYPRO", None)]
129 include_dirs = [os.path.relpath(os.path.join(SRC, "include"), HERE)]
130 library_dirs, libraries, cflags, ldflags = [], [], [], []
131 if IS_WIN:
132 macros += [("WIN32", None), ("NDEBUG", None), ("_WINDOWS", None), ("_WINDLL", None), ("PSYNCL", None)]
133 libraries += ["Ws2_32", "Psapi", "Rpcrt4", "IPHlpApi", "Advapi32", "User32", "Crypt32"] # Crypt32: static OpenSSL
134 cflags += ["/EHsc", "/O2", "/bigobj"]
135 else:
136 macros += [("Darwin" if IS_MAC else "Linux", None), ("_GNU_SOURCE", None), ("_REENTRANT", None),
137 ("_THREAD_SAFE", None)]
138 cflags += ["-O2", "-std=c++11", "-Wno-parentheses", "-Wno-unused-variable", "-Wno-sign-compare"]
139 cflags += ["-g0"] # no debug info: the .so is ~44 MB with the interpreter's default -g
140 if IS_LINUX:
141 ldflags += ["-Wl,-s"]
142 if IS_MAC:
143 cflags += ["-Wno-invalid-source-encoding"]
144 if USE_SSL:
145 macros.append(("_USE_SSL_", None))
146 inc, lib = ssl_paths()
147 include_dirs += inc
148 library_dirs += lib
149 libraries += ["libssl", "libcrypto"] if IS_WIN else ["ssl", "crypto"]
150 if IS_LINUX and any(os.path.isfile(os.path.join(d, "libssl.a")) and
151 not os.path.exists(os.path.join(d, "libssl.so")) for d in lib):
152 # static OpenSSL (ci/build_openssl.sh): keep its symbols private to _cmsdk3, so they never clash
153 # with the libssl that Python's own _ssl module loads into the same process
154 ldflags += ["-Wl,--exclude-libs,ALL"]
155 if IS_LINUX:
156 libraries += ["pthread", "dl", "rt"] # after ssl/crypto: libcrypto.a needs them
157 return Extension(
158 "_cmsdk3", sources=sources, include_dirs=include_dirs, define_macros=macros,
159 library_dirs=library_dirs, libraries=libraries, extra_compile_args=cflags, extra_link_args=ldflags,
160 language="c++", py_limited_api=True,
161 )
162
163
164class ParallelBuildExt(build_ext):
165 """Compile the ~55 CMSDK sources in parallel (setuptools compiles one extension's sources serially)."""
166
167 def build_extension(self, ext):
168 jobs = int(os.environ.get("CMSDK_JOBS", "0") or 0) or os.cpu_count() or 2
169 orig = self.compiler.compile
170
171 def pcompile(sources, *args, **kw):
172 if len(sources) <= 1 or jobs <= 1:
173 return orig(sources, *args, **kw)
174 objs = orig(sources[:1], *args, **kw) # first one alone: MSVC initialises lazily
175 with ThreadPoolExecutor(jobs) as pool:
176 for r in pool.map(lambda s: orig([s], *args, **kw), sources[1:]):
177 objs += r
178 return objs
179
180 self.compiler.compile = pcompile
181 try:
182 super().build_extension(ext)
183 finally:
184 self.compiler.compile = orig
185
186
188setup(
189 ext_modules=[ext],
190 py_modules=["cmsdk3"],
191 package_dir={"": os.path.relpath(GEN, HERE)},
192 cmdclass={"build_ext": ParallelBuildExt},
193 options={"bdist_wheel": {"py_limited_api": "cp310"}},
194)
build_extension(self, ext)
Definition setup.py:167
Definition setup.py:1
make_extension()
Definition setup.py:123
find_swig()
Definition setup.py:63
ssl_paths()
Definition setup.py:96
copy_sources()
Definition setup.py:115
generate_wrapper()
Definition setup.py:77
find_root()
Definition setup.py:30