Debian Codegraph @

setup.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 import sys
4 import re
5 import shutil
6 import subprocess
7 import sysconfig
8 import time
9
10 from pathlib import Path
11 from setuptools import setup, Extension
12 from setuptools.command.build_ext import build_ext
13 from setuptools.command.build_py import build_py
14 from setuptools.command.sdist import sdist
15
16
17 def getVersion():
18 with open("VERSION") as f:
19 return f.read().strip()
20
21
22 def check_pkgcfg():
23 try:
24 proc = subprocess.run(["pkg-config", "--version"],
25 stdout=subprocess.DEVNULL,
26 stderr=subprocess.DEVNULL)
27 if proc.returncode != 0:
28 print("pkg-config binary does not appear to be functional")
29 sys.exit(1)
30 except FileNotFoundError:
31 print("pkg-config binary is required to compile libvirt-python")
32 sys.exit(1)
33
34
35 def check_minimum_libvirt_version():
36 subprocess.check_call(["pkg-config",
37 "--print-errors",
38 f"--atleast-version={MIN_LIBVIRT}",
39 "libvirt"])
40
41
42 def have_libvirt_lxc():
43 proc = subprocess.run(["pkg-config",
44 f"--atleast-version={MIN_LIBVIRT_LXC}",
45 "libvirt"])
46 if proc.returncode == 0:
47 return True
48 return False
49
50
51 def get_pkgconfig_data(args, mod, required=True):
52 """Run pkg-config to and return content associated with it"""
53
54 cmd = ["pkg-config"] + args + [mod]
55 output = subprocess.check_output(cmd, universal_newlines=True)
56 for line in output.splitlines():
57 if line == "":
58 if required:
59 args_str = " ".join(args)
60 raise Exception(f"Cannot determine '{args_str}' from "
61 "libvirt pkg-config file")
62 line = ""
63 return line.strip()
64
65
66 def get_api_xml_files():
67 """Check with pkg-config that libvirt is present and extract
68 the API XML file paths we need from it"""
69
70 libvirt_api = get_pkgconfig_data(["--variable", "libvirt_api"], "libvirt")
71
72 offset = libvirt_api.index("-api.xml")
73 libvirt_qemu_api = libvirt_api[0:offset] + "-qemu-api.xml"
74
75 offset = libvirt_api.index("-api.xml")
76 libvirt_lxc_api = libvirt_api[0:offset] + "-lxc-api.xml"
77
78 return (libvirt_api, libvirt_qemu_api, libvirt_lxc_api)
79
80
81 def get_module_lists():
82 """
83 Determine which modules we are actually building, and all their
84 required config
85 """
86 c_modules = []
87 py_modules = []
88 ldflags = get_pkgconfig_data(["--libs-only-L"], "libvirt", False).split()
89 cflags = get_pkgconfig_data(["--cflags"], "libvirt", False).split()
90
91 cflags += ["-Ibuild"]
92 # The limited API / stable ABI (abi3) is not supported in free-threaded
93 # Python versions: https://docs.python.org/3/c-api/stable.html#c.Py_LIMITED_API
94 # So the only way to build free-threaded Python modules is to drop abi3 support
95 # and use the legacy API instead.
96 #
97 # Platform | Python | C flags added | Result
98 # -------------+---------------------+-------------------------------------+-----------------------
99 # Linux | python3.13/3.14 | Py_LIMITED_API=0x03060000 | Stable ABI (abi3)
100 # Windows | python3.13/3.14 | Py_LIMITED_API=0x03060000 | Stable ABI (abi3)
101 # Linux | python3.13t/3.14t | none | Version-specific API
102 # Windows | python3.13t/3.14t | Py_GIL_DISABLED=1 | Version-specific API
103 # CPython 3.15+ will be compatible with abi3t ABI (from PEP-0803).
104 if sysconfig.get_config_var("Py_GIL_DISABLED"):
105 if sys.platform == "win32":
106 cflags += ["-DPy_GIL_DISABLED=1"]
107 else:
108 cflags += ["-Wp,-DPy_LIMITED_API=0x03060000"]
109
110 module = Extension("libvirtmod",
111 sources=[
112 "libvirt-override.c",
113 "build/libvirt.c",
114 "typewrappers.c",
115 "libvirt-utils.c"
116 ],
117 libraries=["virt"],
118 include_dirs=["."])
119 module.extra_compile_args.extend(cflags)
120 module.extra_link_args.extend(ldflags)
121
122 c_modules.append(module)
123 py_modules.append("libvirt")
124
125 moduleqemu = Extension("libvirtmod_qemu",
126 sources=[
127 "libvirt-qemu-override.c",
128 "build/libvirt-qemu.c",
129 "typewrappers.c",
130 "libvirt-utils.c"
131 ],
132 libraries=["virt-qemu", "virt"],
133 include_dirs=["."])
134 moduleqemu.extra_compile_args.extend(cflags)
135 moduleqemu.extra_link_args.extend(ldflags)
136
137 c_modules.append(moduleqemu)
138 py_modules.append("libvirt_qemu")
139
140 if have_libvirt_lxc():
141 modulelxc = Extension("libvirtmod_lxc",
142 sources=[
143 "libvirt-lxc-override.c",
144 "build/libvirt-lxc.c",
145 "typewrappers.c",
146 "libvirt-utils.c"
147 ],
148 libraries=["virt-lxc", "virt"],
149 include_dirs=["."])
150 modulelxc.extra_compile_args.extend(cflags)
151 modulelxc.extra_link_args.extend(ldflags)
152
153 c_modules.append(modulelxc)
154 py_modules.append("libvirt_lxc")
155
156 py_modules.append("libvirtaio")
157
158 return c_modules, py_modules
159
160
161 ###################
162 # Custom commands #
163 ###################
164
165 class my_build_ext(build_ext):
166
167 def run(self):
168 check_minimum_libvirt_version()
169 apis = get_api_xml_files()
170
171 subprocess.check_call([sys.executable, "generator.py", "libvirt", apis[0], "c"])
172 subprocess.check_call([sys.executable, "generator.py", "libvirt-qemu", apis[1], "c"])
173 if have_libvirt_lxc():
174 subprocess.check_call([sys.executable, "generator.py", "libvirt-lxc", apis[2], "c"])
175
176 build_ext.run(self)
177
178
179 class my_build_py(build_py):
180
181 def run(self):
182 check_minimum_libvirt_version()
183 apis = get_api_xml_files()
184
185 subprocess.check_call([sys.executable, "generator.py", "libvirt", apis[0], "py"])
186 subprocess.check_call([sys.executable, "generator.py", "libvirt-qemu", apis[1], "py"])
187 if have_libvirt_lxc():
188 subprocess.check_call([sys.executable, "generator.py", "libvirt-lxc", apis[2], "py"])
189 shutil.copy("libvirtaio.py", "build")
190
191 build_py.run(self)
192
193
194 class my_sdist(sdist):
195 user_options = sdist.user_options
196
197 description = "Update libvirt-python.spec; build sdist-tarball."
198
199 def initialize_options(self):
200 self.snapshot = None
201 sdist.initialize_options(self)
202
203 def finalize_options(self):
204 if self.snapshot is not None:
205 self.snapshot = 1
206 sdist.finalize_options(self)
207
208 @staticmethod
209 def _gen_from_in(file_in, file_out, replacements):
210 with open(file_in) as f_in, open(file_out, "w") as f_out:
211 for line in f_in:
212 for pattern, replace in replacements.items():
213 line = line.replace(pattern, replace)
214 f_out.write(line)
215
216 def gen_rpm_spec(self):
217 full_name = self.distribution.get_fullname()
218 dist_name = full_name[:full_name.rfind("-")]
219
220 return self._gen_from_in("libvirt-python.spec.in",
221 "libvirt-python.spec",
222 {"@VERSION@": getVersion(),
223 "@DIST_NAME@": dist_name})
224
225 def gen_authors(self):
226
227 cmd = ["git", "log", "--pretty=format:%aN <%aE>"]
228 output = subprocess.check_output(cmd, universal_newlines=True)
229 git_authors = {line.strip() for line in output.splitlines()}
230 authors = sorted(git_authors, key=str.lower)
231 authors = [" " + author for author in authors]
232 self._gen_from_in("AUTHORS.in",
233 "AUTHORS",
234 {"@AUTHORS@": "\n".join(authors)})
235
236 def gen_changelog(self):
237 cmd = ["git", "log", "--pretty=format:%H:%ct %an <%ae>%n%n%s%n%b%n"]
238 with open("ChangeLog", "w") as f_out:
239 output = subprocess.check_output(cmd, universal_newlines=True)
240 for line in output.splitlines():
241 m = re.match(r"([a-f0-9]+):(\d+)\s(.*)", line)
242 if m:
243 t = time.gmtime(int(m.group(2)))
244 fmt = "{: 04d}-{: 02d}-{: 02d} {}\n"
245 f_out.write(fmt.format(t.tm_year, t.tm_mon, t.tm_mday, m.group(3)))
246 else:
247 if re.match(r"Signed-off-by", line):
248 continue
249 f_out.write(" " + line.strip() + "\n")
250
251 def run(self):
252 if Path(".git").exists():
253 try:
254 self.gen_rpm_spec()
255 self.gen_authors()
256 self.gen_changelog()
257
258 sdist.run(self)
259
260 finally:
261 files = [
262 "libvirt-python.spec",
263 "AUTHORS",
264 "ChangeLog"
265 ]
266 for f in files:
267 try:
268 Path(f).unlink()
269 except FileNotFoundError:
270 pass
271 else:
272 sdist.run(self)
273
274
275 ##################
276 # Invoke setup() #
277 ##################
278
279 if sys.version_info < (3, 6):
280 print("libvirt-python requires Python >= 3.6 to build")
281 sys.exit(1)
282
283 MIN_LIBVIRT = "0.9.11"
284 MIN_LIBVIRT_LXC = "1.0.2"
285
286 # Hack to stop "pip install" failing with error
287 # about missing "build" dir.
288 Path("build").mkdir(exist_ok=True)
289
290 check_pkgcfg()
291
292 _c_modules, _py_modules = get_module_lists()
293
294 setup(
295 ext_modules=_c_modules,
296 py_modules=_py_modules,
297 package_dir={
298 '': 'build'
299 },
300 cmdclass={
301 "build_ext": my_build_ext,
302 "build_py": my_build_py,
303 "sdist": my_sdist,
304 },
305 )