Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
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
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
 
"""
Packages ONNX Runtime Java artifacts by combining native libraries from
various platform builds into final Java archive (JAR) files using 7z.
"""
 
import argparse
import glob
import os
import re
import shutil
import subprocess
import sys
import zipfile
from pathlib import Path
from typing import Any
 
# Add semver as a dependency
try:
    import semver
except ImportError:
    print("Error: The 'semver' package is not installed. Please add it to your requirements.txt.", file=sys.stderr)
    sys.exit(1)
 
# --- Helper Functions for Archiving ---
 
 
def find_7z_executable():
    """Finds the 7z executable, checking the system PATH and default installation locations."""
    # 1. Check if '7z' is in the PATH
    seven_zip_exe = shutil.which("7z")
    if seven_zip_exe:
        return seven_zip_exe
 
    # 2. Check if '7za' is in the PATH (common on Linux systems)
    seven_zip_exe = shutil.which("7za")
    if seven_zip_exe:
        return seven_zip_exe
 
    # 3. Check the default installation directory under Program Files
    program_files = os.environ.get("ProgramFiles")  # noqa: SIM112
    if program_files:
        default_path = Path(program_files) / "7-Zip" / "7z.exe"
        if default_path.is_file():
            return str(default_path)
 
    return None
 
 
SEVEN_ZIP_EXE = find_7z_executable()
 
 
def add_file_to_archive(archive_path: Path, file_to_add: Path, description: str, archive_name: str | None = None):
    """Appends a single file to a zip archive (JAR file)."""
    print(f"  -> {description}...")
    try:
        if archive_name:
            with zipfile.ZipFile(archive_path, "a") as archive:
                archive.write(file_to_add, archive_name)
            return
        if not SEVEN_ZIP_EXE:
            raise FileNotFoundError
        # Run 7z from the file's parent directory to ensure a clean archive path.
        subprocess.run(
            [SEVEN_ZIP_EXE, "a", str(archive_path), file_to_add.name],
            check=True,
            cwd=file_to_add.parent,
            capture_output=True,
            text=True,
        )
    except FileNotFoundError:
        print(
            "Error: '7z' command not found. Please ensure 7-Zip is installed and in your PATH, or in the default location 'C:\\Program Files\\7-Zip'.",
            file=sys.stderr,
        )
        raise
    except subprocess.CalledProcessError as e:
        print(f"Error: 7z failed to archive '{file_to_add.name}' to '{archive_path.name}'.", file=sys.stderr)
        print(f"Reason: {e.stderr}", file=sys.stderr)
        raise
 
 
def archive_directory_contents(archive_path: Path, source_dir: Path, description: str):
    """Archives a directory into a zip file (JAR file) using 7z, preserving its top-level name."""
    print(f"  -> {description}...")
    try:
        if not SEVEN_ZIP_EXE:
            raise FileNotFoundError
        # Run 7z from the parent of the source directory to ensure the source directory
        # itself is added to the archive, preserving the path structure (e.g., 'ai/...').
        subprocess.run(
            [SEVEN_ZIP_EXE, "a", str(archive_path), source_dir.name],
            check=True,
            cwd=source_dir.parent,
            capture_output=True,
            text=True,
        )
    except FileNotFoundError:
        print(
            "Error: '7z' command not found. Please ensure 7-Zip is installed and in your PATH, or in the default location 'C:\\Program Files\\7-Zip'.",
            file=sys.stderr,
        )
        raise
    except subprocess.CalledProcessError as e:
        print(f"Error: 7z failed to archive directory '{source_dir.name}' to '{archive_path.name}'.", file=sys.stderr)
        print(f"Reason: {e.stderr}", file=sys.stderr)
        raise
 
 
# --- Validation Helpers ---
 
 
def validate_version(version_string: str):
    """Validates if the version string conforms to the project's format."""
    print(f"Validating version string: {version_string}...")
    try:
        version_info = semver.Version.parse(version_string)
        if version_info.prerelease:
            prerelease_tag = version_info.prerelease
            allowed_tags_pattern = r"^(alpha|beta|rc)\d+$"
            if not re.match(allowed_tags_pattern, str(prerelease_tag)):
                raise ValueError(f"Pre-release tag '{prerelease_tag}' is not an allowed type.")
    except ValueError as e:
        print(f"Error: Version '{version_string}' is not valid. Reason: {e}", file=sys.stderr)
        print("Expected format is 'X.Y.Z' or 'X.Y.Z-(alpha|beta|rc)N'.", file=sys.stderr)
        sys.exit(1)
    print("Version format is valid.")
 
 
def validate_companion_jars(base_jar_path: Path):
    """Ensures that -sources.jar and -javadoc.jar files exist."""
    print("Validating presence of companion -sources.jar and -javadoc.jar...")
    base_stem = base_jar_path.stem
    directory = base_jar_path.parent
    sources_jar_path = directory / f"{base_stem}-sources.jar"
 
    if not sources_jar_path.is_file():
        print(f"Error: Missing companion sources JAR. Expected: {sources_jar_path.name}", file=sys.stderr)
        sys.exit(1)
 
    if not list(directory.glob(f"{base_stem}-javadoc*.jar")):
        print(f"Error: Missing companion javadoc JAR. Expected file like: {base_stem}-javadoc.jar", file=sys.stderr)
        sys.exit(1)
    print("Companion JARs are present.")
 
 
# --- Core Logic Function ---
 
 
def process_platform_archive(
    platform_path: Path,
    main_archive_file: Path,
    test_archive_file: Path,
    custom_lib_file: str,
    archive_custom_lib: bool,
    test_lib_file: str,
    test_lib_archive_path: str = "",
):
    """Processes a single platform directory, adding only the 'ai' subdirectory to the main JAR."""
    print(f"Processing platform: {platform_path}...")
 
    # 1. Handle the custom op library.
    custom_lib_full_path = platform_path / custom_lib_file
    if custom_lib_file and custom_lib_full_path.is_file():
        if archive_custom_lib:
            add_file_to_archive(test_archive_file, custom_lib_full_path, f"Archiving '{custom_lib_file}' to test JAR")
        # Always remove the lib after processing to prevent it from being in the main JAR.
        print(f"  -> Removing '{custom_lib_file}' from source directory...")
        custom_lib_full_path.unlink()
    elif archive_custom_lib:
        # If we expected to archive the file but it wasn't there, it's a fatal error.
        print(f"Error: Expected custom op library '{custom_lib_file}' not found in {platform_path}", file=sys.stderr)
        sys.exit(1)
 
    # 1b. Handle the JNI unit test helper library (onnxruntime4j_jni_test). It is only built when
    #     onnxruntime_BUILD_UNIT_TESTS is ON, so its absence is a warning rather than a fatal error.
    test_lib_full_path = platform_path / test_lib_file
    if test_lib_file and test_lib_full_path.is_file():
        add_file_to_archive(
            test_archive_file,
            test_lib_full_path,
            f"Archiving '{test_lib_file}' to test JAR",
            test_lib_archive_path or None,
        )
        print(f"  -> Removing '{test_lib_file}' from source directory...")
        test_lib_full_path.unlink()
    elif test_lib_file:
        print(f"Warning: JNI test library '{test_lib_file}' not found in {platform_path}. Skipping (not fatal).")
 
    # 2. Archive only the native library directory ('ai/...') to the main JAR.
    #    This explicitly excludes other files or folders like '_manifest'.
    native_lib_root = platform_path / "ai"
    if native_lib_root.is_dir():
        archive_directory_contents(
            main_archive_file, native_lib_root, f"Archiving native libs from '{native_lib_root.name}' to main JAR"
        )
    else:
        print(f"Warning: Native library path 'ai/' not found in {platform_path}. Skipping main archive step.")
 
    print(f"Finished platform: {platform_path}")
    print("--------------------------------")
 
 
def run_packaging(package_type: str, build_dir: str):
    """The main logic for the packaging process, refactored to be callable."""
    artifacts_base_dir = Path(build_dir) / "java-artifact"
    primary_package_dir = artifacts_base_dir / "onnxruntime-java-win-x64"
    if not primary_package_dir.is_dir():
        print(f"Error: Primary package directory not found at '{primary_package_dir}'", file=sys.stderr)
        sys.exit(1)
 
    # --- Version Discovery ---
    print(f"Discovering version from JAR files in '{primary_package_dir}'...")
    jar_pattern = str(primary_package_dir / "onnxruntime*-*.jar")
    jar_files = [Path(f) for f in glob.glob(jar_pattern) if "-sources" not in f and "-javadoc" not in f]
    if not jar_files:
        print(
            f"Error: Could not find a main JAR file in '{primary_package_dir}' to determine the version.",
            file=sys.stderr,
        )
        sys.exit(1)
 
    main_jar_file = jar_files[0]
    validate_companion_jars(main_jar_file)
 
    version = ""
    stem = main_jar_file.stem
    try:
        # Per user feedback, the version is everything after the first dash.
        _, version = stem.split("-", 1)
    except ValueError:
        # This will happen if there is no dash in the filename, which is unexpected.
        print(
            f"Error: Could not parse version from JAR file '{main_jar_file.name}'. Expected format <artifactId>-<version>.jar",
            file=sys.stderr,
        )
        sys.exit(1)
 
    if not version:
        print(
            f"Error: Could not parse version from JAR file '{main_jar_file.name}'. Version part is empty.",
            file=sys.stderr,
        )
        sys.exit(1)
 
    print(f"Version discovered: {version}")
    validate_version(version)
 
    # --- Package Definitions ---
    package_definitions: dict[str, dict[str, Any]] = {
        "cpu": {
            "platforms": [
                {
                    "path": "onnxruntime-java-linux-x64",
                    "lib": "libcustom_op_library.so",
                    "archive_lib": True,
                    "test_lib": "libonnxruntime4j_jni_test.so",
                },
                {
                    "path": "onnxruntime-java-linux-aarch64",
                    "lib": "libcustom_op_library.so",
                    "archive_lib": False,
                    "test_lib": "libonnxruntime4j_jni_test.so",
                    # Keep this separate from the x64 helper, which has the same basename.
                    "test_lib_archive_path": "linux-aarch64/libonnxruntime4j_jni_test.so",
                },
                {
                    "path": "onnxruntime-java-osx-arm64",
                    "lib": "libcustom_op_library.dylib",
                    "archive_lib": True,
                    "test_lib": "libonnxruntime4j_jni_test.dylib",
                },
            ]
        },
        "gpu": {
            "platforms": [
                {
                    "path": "onnxruntime-java-linux-x64",
                    "lib": "libcustom_op_library.so",
                    "archive_lib": True,
                    "test_lib": "libonnxruntime4j_jni_test.so",
                }
            ]
        },
    }
 
    # --- Processing Loop ---
    print(f"\n## Configuring for {package_type.upper()} package build...")
 
    final_main_archive = main_jar_file
    final_test_archive = primary_package_dir / "testing.jar"
 
    print(f"Using '{final_main_archive.name}' as the base for in-place packaging.")
 
    if not final_test_archive.is_file():
        print(f"Error: Base 'testing.jar' not found at '{final_test_archive}'.", file=sys.stderr)
        sys.exit(1)
 
    platforms_to_process = package_definitions[package_type]["platforms"]
 
    for platform in platforms_to_process:
        platform_full_path = artifacts_base_dir / platform["path"]
        if not platform_full_path.is_dir():
            print(f"Error: Required platform artifact directory not found: {platform_full_path}", file=sys.stderr)
            sys.exit(1)
 
        process_platform_archive(
            platform_path=platform_full_path,
            main_archive_file=final_main_archive,
            test_archive_file=final_test_archive,
            custom_lib_file=platform["lib"],
            archive_custom_lib=platform["archive_lib"],
            test_lib_file=platform.get("test_lib", ""),
            test_lib_archive_path=platform.get("test_lib_archive_path", ""),
        )
 
    print("\nScript completed successfully.")
 
 
def main():
    """Main script entry point for command-line execution."""
    if sys.platform != "win32":
        print("Error: This script is intended to be run on Windows.", file=sys.stderr)
        sys.exit(1)
 
    parser = argparse.ArgumentParser(description="Package ONNX Runtime Java artifacts.")
    parser.add_argument(
        "--package_type",
        type=str,
        choices=["cpu", "gpu"],
        default="cpu",
        help="The type of package to build ('cpu' or 'gpu').",
    )
    parser.add_argument(
        "--build_dir",
        type=str,
        help="The build directory containing the java-artifact folder.",
    )
    args = parser.parse_args()
 
    build_dir = args.build_dir
    if not build_dir:
        try:
            build_dir = os.environ["BUILD_BINARIESDIRECTORY"]
        except KeyError:
            print(
                "Error: Environment variable BUILD_BINARIESDIRECTORY is not set and --build_dir is not provided.",
                file=sys.stderr,
            )
            sys.exit(1)
 
    run_packaging(args.package_type, build_dir)
 
 
if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"\nAn unhandled error occurred: {e}", file=sys.stderr)
        sys.exit(1)