-
Notifications
You must be signed in to change notification settings - Fork 998
Expand file tree
/
Copy pathsetup.py
More file actions
411 lines (361 loc) · 17 KB
/
setup.py
File metadata and controls
411 lines (361 loc) · 17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import importlib
import json
import os
import platform
import shutil
import subprocess
import sys
import sysconfig
from pathlib import Path
import pybind11
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
SETUP_DIR = Path(__file__).resolve().parent
if str(SETUP_DIR) not in sys.path:
sys.path.insert(0, str(SETUP_DIR))
get_host_engine_build_config = importlib.import_module(
"build_support.x86_profiles"
).get_host_engine_build_config
CMAKE_PATH = shutil.which("cmake") or "cmake"
C_COMPILER_PATH = shutil.which("gcc") or "gcc"
CXX_COMPILER_PATH = shutil.which("g++") or "g++"
ENGINE_SOURCE_DIR = "src/"
ENGINE_BUILD_CONFIG = get_host_engine_build_config(platform.machine())
class OpenVikingBuildExt(build_ext):
"""Build OpenViking runtime artifacts and Python native extensions."""
def run(self):
self.build_agfs_artifacts()
self.build_ov_cli_artifact()
self.cmake_executable = CMAKE_PATH
for ext in self.extensions:
self.build_extension(ext)
def _copy_artifact(self, src, dst):
"""Copy a build artifact into the package tree and preserve executability."""
print(f"Copying artifact from {src} to {dst}")
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(str(src), str(dst))
if sys.platform != "win32":
os.chmod(str(dst), 0o755)
def _copy_artifacts_to_build_lib(self, target_binary=None, target_lib=None):
"""Copy built artifacts into build_lib so wheel packaging can include them."""
if self.build_lib:
build_pkg_dir = Path(self.build_lib) / "openviking"
if target_binary and target_binary.exists():
self._copy_artifact(target_binary, build_pkg_dir / "bin" / target_binary.name)
if target_lib and target_lib.exists():
self._copy_artifact(target_lib, build_pkg_dir / "lib" / target_lib.name)
def _require_artifact(self, artifact_path, artifact_name, stage_name):
"""Abort the build immediately when a required artifact is missing."""
if artifact_path.exists():
return
raise RuntimeError(
f"{stage_name} did not produce required {artifact_name} at {artifact_path}"
)
def _run_stage_with_artifact_checks(
self, stage_name, build_fn, required_artifacts, on_success=None
):
"""Run a build stage and always validate its required outputs on normal return."""
build_fn()
for artifact_path, artifact_name in required_artifacts:
self._require_artifact(artifact_path, artifact_name, stage_name)
if on_success:
on_success()
def _resolve_cargo_target_dir(self, cargo_project_dir, env):
"""Resolve the Cargo target directory for workspace and overridden builds."""
configured_target_dir = env.get("CARGO_TARGET_DIR")
if configured_target_dir:
return Path(configured_target_dir).resolve()
try:
result = subprocess.run(
["cargo", "metadata", "--format-version", "1", "--no-deps"],
cwd=str(cargo_project_dir),
env=env,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
metadata = json.loads(result.stdout.decode("utf-8"))
target_directory = metadata.get("target_directory")
if target_directory:
return Path(target_directory).resolve()
except Exception as exc:
print(f"[Warning] Failed to resolve Cargo target directory via metadata: {exc}")
return cargo_project_dir.parents[1] / "target"
def build_agfs_artifacts(self):
"""Build or reuse the AGFS server binary and binding library."""
binary_name = "agfs-server.exe" if sys.platform == "win32" else "agfs-server"
if sys.platform == "win32":
lib_name = "libagfsbinding.dll"
elif sys.platform == "darwin":
lib_name = "libagfsbinding.dylib"
else:
lib_name = "libagfsbinding.so"
agfs_server_dir = Path("third_party/agfs/agfs-server").resolve()
agfs_bin_dir = Path("openviking/bin").resolve()
agfs_lib_dir = Path("openviking/lib").resolve()
agfs_target_binary = agfs_bin_dir / binary_name
agfs_target_lib = agfs_lib_dir / lib_name
self._run_stage_with_artifact_checks(
"AGFS build",
lambda: self._build_agfs_artifacts_impl(
agfs_server_dir,
binary_name,
lib_name,
agfs_target_binary,
agfs_target_lib,
),
[
(agfs_target_binary, binary_name),
(agfs_target_lib, lib_name),
],
on_success=lambda: self._copy_artifacts_to_build_lib(
agfs_target_binary, agfs_target_lib
),
)
def _build_agfs_artifacts_impl(
self, agfs_server_dir, binary_name, lib_name, agfs_target_binary, agfs_target_lib
):
"""Implement AGFS artifact building without final artifact checks."""
prebuilt_dir = os.environ.get("OV_PREBUILT_BIN_DIR")
if prebuilt_dir:
prebuilt_path = Path(prebuilt_dir).resolve()
print(f"Checking for pre-built AGFS artifacts in {prebuilt_path}...")
src_bin = prebuilt_path / binary_name
src_lib = prebuilt_path / lib_name
if src_bin.exists():
self._copy_artifact(src_bin, agfs_target_binary)
if src_lib.exists():
self._copy_artifact(src_lib, agfs_target_lib)
if agfs_target_binary.exists() and agfs_target_lib.exists():
print(f"[OK] Used pre-built AGFS artifacts from {prebuilt_dir}")
return
if os.environ.get("OV_SKIP_AGFS_BUILD") == "1":
if agfs_target_binary.exists() and agfs_target_lib.exists():
print("[OK] Skipping AGFS build, using existing artifacts")
return
print("[Warning] OV_SKIP_AGFS_BUILD=1 but artifacts are missing. Will try to build.")
if agfs_server_dir.exists() and shutil.which("go"):
print("Building AGFS artifacts from source...")
try:
print(f"Building AGFS server: {binary_name}")
env = os.environ.copy()
if "GOOS" in env or "GOARCH" in env:
print(f"Cross-compiling with GOOS={env.get('GOOS')} GOARCH={env.get('GOARCH')}")
build_args = (
["go", "build", "-o", f"build/{binary_name}", "cmd/server/main.go"]
if sys.platform == "win32"
else ["make", "build"]
)
result = subprocess.run(
build_args,
cwd=str(agfs_server_dir),
env=env,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.stdout:
print(f"Build stdout: {result.stdout.decode('utf-8', errors='replace')}")
if result.stderr:
print(f"Build stderr: {result.stderr.decode('utf-8', errors='replace')}")
agfs_built_binary = agfs_server_dir / "build" / binary_name
self._require_artifact(agfs_built_binary, binary_name, "AGFS server build")
self._copy_artifact(agfs_built_binary, agfs_target_binary)
print("[OK] AGFS server built successfully from source")
except Exception as exc:
error_msg = f"Failed to build AGFS server from source: {exc}"
if isinstance(exc, subprocess.CalledProcessError):
if exc.stdout:
error_msg += (
f"\nBuild stdout:\n{exc.stdout.decode('utf-8', errors='replace')}"
)
if exc.stderr:
error_msg += (
f"\nBuild stderr:\n{exc.stderr.decode('utf-8', errors='replace')}"
)
print(f"[Error] {error_msg}")
raise RuntimeError(error_msg)
try:
print(f"Building AGFS binding library: {lib_name}")
env = os.environ.copy()
env["CGO_ENABLED"] = "1"
result = subprocess.run(
["make", "build-lib"],
cwd=str(agfs_server_dir),
env=env,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.stdout:
print(f"Build stdout: {result.stdout.decode('utf-8', errors='replace')}")
if result.stderr:
print(f"Build stderr: {result.stderr.decode('utf-8', errors='replace')}")
agfs_built_lib = agfs_server_dir / "build" / lib_name
self._require_artifact(agfs_built_lib, lib_name, "AGFS binding build")
self._copy_artifact(agfs_built_lib, agfs_target_lib)
print("[OK] AGFS binding library built successfully")
except Exception as exc:
error_msg = f"Failed to build AGFS binding library: {exc}"
if isinstance(exc, subprocess.CalledProcessError):
if exc.stdout:
error_msg += (
f"\nBuild stdout: {exc.stdout.decode('utf-8', errors='replace')}"
)
if exc.stderr:
error_msg += (
f"\nBuild stderr: {exc.stderr.decode('utf-8', errors='replace')}"
)
print(f"[Error] {error_msg}")
raise RuntimeError(error_msg)
else:
if agfs_target_binary.exists() and agfs_target_lib.exists():
print("[Info] AGFS artifacts already exist locally. Skipping source build.")
elif not agfs_server_dir.exists():
print(f"[Warning] AGFS source directory not found at {agfs_server_dir}")
else:
print("[Warning] Go compiler not found. Cannot build AGFS from source.")
def build_ov_cli_artifact(self):
"""Build or reuse the ov Rust CLI binary."""
binary_name = "ov.exe" if sys.platform == "win32" else "ov"
ov_cli_dir = Path("crates/ov_cli").resolve()
ov_target_binary = Path("openviking/bin").resolve() / binary_name
self._run_stage_with_artifact_checks(
"ov CLI build",
lambda: self._build_ov_cli_artifact_impl(ov_cli_dir, binary_name, ov_target_binary),
[(ov_target_binary, binary_name)],
on_success=lambda: self._copy_artifacts_to_build_lib(ov_target_binary, None),
)
def _build_ov_cli_artifact_impl(self, ov_cli_dir, binary_name, ov_target_binary):
"""Implement ov CLI building without final artifact checks."""
prebuilt_dir = os.environ.get("OV_PREBUILT_BIN_DIR")
if prebuilt_dir:
src_bin = Path(prebuilt_dir).resolve() / binary_name
if src_bin.exists():
self._copy_artifact(src_bin, ov_target_binary)
return
if os.environ.get("OV_SKIP_OV_BUILD") == "1":
if ov_target_binary.exists():
print("[OK] Skipping ov CLI build, using existing binary")
return
print("[Warning] OV_SKIP_OV_BUILD=1 but binary is missing. Will try to build.")
if ov_cli_dir.exists() and shutil.which("cargo"):
print("Building ov CLI from source...")
try:
env = os.environ.copy()
build_args = ["cargo", "build", "--release"]
target = env.get("CARGO_BUILD_TARGET")
if target:
print(f"Cross-compiling with CARGO_BUILD_TARGET={target}")
build_args.extend(["--target", target])
result = subprocess.run(
build_args,
cwd=str(ov_cli_dir),
env=env,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if result.stdout:
print(f"Build stdout: {result.stdout.decode('utf-8', errors='replace')}")
if result.stderr:
print(f"Build stderr: {result.stderr.decode('utf-8', errors='replace')}")
cargo_target_dir = self._resolve_cargo_target_dir(ov_cli_dir, env)
if target:
built_bin = cargo_target_dir / target / "release" / binary_name
else:
built_bin = cargo_target_dir / "release" / binary_name
self._require_artifact(built_bin, binary_name, "ov CLI build")
self._copy_artifact(built_bin, ov_target_binary)
print("[OK] ov CLI built successfully from source")
except Exception as exc:
error_msg = f"Failed to build ov CLI from source: {exc}"
if isinstance(exc, subprocess.CalledProcessError):
if exc.stdout:
error_msg += (
f"\nBuild stdout: {exc.stdout.decode('utf-8', errors='replace')}"
)
if exc.stderr:
error_msg += (
f"\nBuild stderr: {exc.stderr.decode('utf-8', errors='replace')}"
)
print(f"[Error] {error_msg}")
raise RuntimeError(error_msg)
else:
if ov_target_binary.exists():
print("[Info] ov CLI binary already exists locally. Skipping source build.")
elif not ov_cli_dir.exists():
print(f"[Warning] ov CLI source directory not found at {ov_cli_dir}")
else:
print("[Warning] Cargo not found. Cannot build ov CLI from source.")
def build_extension(self, ext):
"""Build a single Python native extension artifact using CMake."""
if getattr(self, "_engine_extensions_built", False):
return
ext_fullpath = Path(self.get_ext_fullpath(ext.name))
ext_dir = ext_fullpath.parent.resolve()
build_dir = Path(self.build_temp) / "cmake_build"
build_dir.mkdir(parents=True, exist_ok=True)
self._run_stage_with_artifact_checks(
"CMake build",
lambda: self._build_extension_impl(ext_fullpath, ext_dir, build_dir),
[(ext_fullpath, f"native extension '{ext.name}'")],
)
self._engine_extensions_built = True
def _build_extension_impl(self, ext_fullpath, ext_dir, build_dir):
"""Invoke CMake to build the Python native extension."""
py_ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") or ext_fullpath.suffix
cmake_args = [
f"-S{Path(ENGINE_SOURCE_DIR).resolve()}",
f"-B{build_dir}",
"-DCMAKE_BUILD_TYPE=Release",
f"-DOV_PY_OUTPUT_DIR={ext_dir}",
f"-DOV_PY_EXT_SUFFIX={py_ext_suffix}",
f"-DOV_X86_BUILD_VARIANTS={';'.join(ENGINE_BUILD_CONFIG.cmake_variants)}",
"-DCMAKE_VERBOSE_MAKEFILE=ON",
"-DCMAKE_INSTALL_RPATH=$ORIGIN",
f"-DPython3_EXECUTABLE={sys.executable}",
f"-DPython3_INCLUDE_DIRS={sysconfig.get_path('include')}",
f"-DPython3_LIBRARIES={sysconfig.get_config_vars().get('LIBRARY')}",
f"-Dpybind11_DIR={pybind11.get_cmake_dir()}",
f"-DCMAKE_C_COMPILER={C_COMPILER_PATH}",
f"-DCMAKE_CXX_COMPILER={CXX_COMPILER_PATH}",
]
if sys.platform == "darwin":
cmake_args.append("-DCMAKE_OSX_DEPLOYMENT_TARGET=10.15")
target_arch = os.environ.get("CMAKE_OSX_ARCHITECTURES")
if target_arch:
cmake_args.append(f"-DCMAKE_OSX_ARCHITECTURES={target_arch}")
elif sys.platform == "win32":
cmake_args.extend(["-G", "MinGW Makefiles"])
self.spawn([self.cmake_executable] + cmake_args)
build_args = ["--build", str(build_dir), "--config", "Release", f"-j{os.cpu_count() or 4}"]
self.spawn([self.cmake_executable] + build_args)
setup(
# install_requires=[
# f"pyagfs @ file://localhost/{os.path.abspath('third_party/agfs/agfs-sdk/python')}"
# ],
ext_modules=[
Extension(
name=ENGINE_BUILD_CONFIG.primary_extension,
sources=[],
)
],
cmdclass={
"build_ext": OpenVikingBuildExt,
},
package_data={
"openviking": [
"bin/agfs-server",
"bin/agfs-server.exe",
"lib/libagfsbinding.so",
"lib/libagfsbinding.dylib",
"lib/libagfsbinding.dll",
"bin/ov",
"bin/ov.exe",
"storage/vectordb/engine/*.so",
"storage/vectordb/engine/*.pyd",
],
},
include_package_data=True,
)