Исходный код СУБД 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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
#![allow(dead_code)]
 
use std::{
    borrow::Cow,
    env, fs,
    io::{self, Read, Write},
    path::{Path, PathBuf},
    str::FromStr,
};
 
// use cmake::build;
 
use anyhow::{anyhow, Context, Result};
 
/// Base Url from which to download pre-built releases/
const ORT_RELEASE_BASE_URL: &str = "https://github.com/microsoft/onnxruntime/releases/download";
 
/// Environment variable selecting which strategy to use for finding the library
/// Possibilities:
/// * "download": Download a pre-built library. This is the default if `ORT_STRATEGY` is not set.
/// * "system": Use installed library. Use `ORT_LIB_LOCATION` to point to proper location.
/// * "compile": Download source and compile (TODO).
const ORT_RUST_ENV_STRATEGY: &str = "ORT_RUST_STRATEGY";
 
/// Name of environment variable that, if present, contains the location of a pre-built library.
/// Only used if `ORT_STRATEGY=system`.
const ORT_RUST_ENV_SYSTEM_LIB_LOCATION: &str = "ORT_RUST_LIB_LOCATION";
/// Optional path to an ONNX Runtime source/install include directory or onnxruntime_c_api.h.
const ORT_RUST_ENV_HEADER_LOCATION: &str = "ORT_RUST_HEADER_LOCATION";
/// Optional ONNX Runtime release version used by the download strategy.
const ORT_RUST_ENV_VERSION: &str = "ORT_RUST_VERSION";
/// Name of environment variable that, if present, controls whether to use CUDA or not.
const ORT_RUST_ENV_GPU: &str = "ORT_RUST_USE_CUDA";
 
/// Subdirectory (of the 'target' directory) into which to extract the prebuilt library.
const ORT_PREBUILT_EXTRACT_DIR: &str = "onnxruntime";
 
fn main() -> Result<()> {
    let libort_install_dir = prepare_libort_dir().context("preparing libort directory")?;
 
    let include_dir = libort_install_dir.join("include");
    let lib_dir = libort_install_dir.join("lib");
 
    println!("Include directory: {:?}", include_dir);
    println!("Lib directory: {:?}", lib_dir);
 
    // Tell cargo to tell rustc to link onnxruntime shared library.
    println!("cargo:rustc-link-lib=onnxruntime");
    println!("cargo:rustc-link-search=native={}", lib_dir.display());
 
    println!("cargo:rerun-if-env-changed={}", ORT_RUST_ENV_STRATEGY);
    println!("cargo:rerun-if-env-changed={}", ORT_RUST_ENV_GPU);
    println!(
        "cargo:rerun-if-env-changed={}",
        ORT_RUST_ENV_SYSTEM_LIB_LOCATION
    );
    println!(
        "cargo:rerun-if-env-changed={}",
        ORT_RUST_ENV_HEADER_LOCATION
    );
    println!("cargo:rerun-if-env-changed={}", ORT_RUST_ENV_VERSION);
 
    generate_bindings(&include_dir)?;
    Ok(())
}
 
fn generate_bindings(include_dir: &Path) -> Result<()> {
    let path = find_header(include_dir)?;
    let header_dir = path
        .parent()
        .context("onnxruntime_c_api.h has no parent directory")?;
    let clang_args = [
        format!("-I{}", include_dir.display()),
        format!("-I{}", header_dir.display()),
        format!(
            "-I{}",
            include_dir
                .join("onnxruntime")
                .join("core")
                .join("session")
                .display()
        ),
    ];
 
    println!("Using ONNX Runtime header: {}", path.display());
    println!("cargo:rerun-if-changed={}", path.display());
 
    // The bindgen::Builder is the main entry point
    // to bindgen, and lets you build up options for
    // the resulting bindings.
    let bindings = bindgen::Builder::default()
        // The input header we would like to generate
        // bindings for.
        .header(path.to_string_lossy().to_string())
        // The current working directory is 'onnxruntime-sys'
        .clang_args(clang_args)
        // Tell cargo to invalidate the built crate whenever any of the
        // included header files changed.
        .parse_callbacks(Box::new(bindgen::CargoCallbacks))
        .dynamic_library_name("onnxruntime")
        .allowlist_type("Ort.*")
        .allowlist_type("Onnx.*")
        .allowlist_type("ONNX.*")
        .allowlist_function("Ort.*")
        .allowlist_var("ORT.*")
        // Set `size_t` to be translated to `usize` for win32 compatibility.
        .size_t_is_usize(true)
        // Format using rustfmt
        .rustfmt_bindings(true)
        .rustified_enum(".*")
        // Finish the builder and generate the bindings.
        .generate()
        // Unwrap the Result and panic on failure.
        .context("generating ONNX Runtime bindings")?;
 
    let generated_file =
        PathBuf::from(env::var("OUT_DIR").context("OUT_DIR is not set")?).join("bindings.rs");
    bindings
        .write_to_file(generated_file)
        .context("writing ONNX Runtime bindings")?;
 
    Ok(())
}
 
fn find_header(include_dir: &Path) -> Result<PathBuf> {
    if let Ok(location) = env::var(ORT_RUST_ENV_HEADER_LOCATION) {
        let path = PathBuf::from(location);
        return find_header_under(&path).with_context(|| {
            format!(
                "finding onnxruntime_c_api.h under {} from {}",
                path.display(),
                ORT_RUST_ENV_HEADER_LOCATION
            )
        });
    }
 
    let manifest_dir =
        PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("CARGO_MANIFEST_DIR is not set")?);
    let repository_include = manifest_dir.join("../../include");
    if let Ok(path) = find_header_under(&repository_include) {
        return Ok(path);
    }
 
    find_header_under(include_dir).with_context(|| {
        format!(
            "finding onnxruntime_c_api.h in installed include directory {}",
            include_dir.display()
        )
    })
}
 
fn find_header_under(path: &Path) -> Result<PathBuf> {
    if path.is_file() {
        return (path.file_name().and_then(|name| name.to_str()) == Some("onnxruntime_c_api.h"))
            .then(|| path.to_path_buf())
            .ok_or_else(|| anyhow!("header override is not onnxruntime_c_api.h"));
    }
 
    [
        path.join("onnxruntime_c_api.h"),
        path.join("onnxruntime").join("onnxruntime_c_api.h"),
        path.join("onnxruntime")
            .join("core")
            .join("session")
            .join("onnxruntime_c_api.h"),
    ]
    .iter()
    .find(|candidate| candidate.is_file())
    .cloned()
    .ok_or_else(|| anyhow!("onnxruntime_c_api.h was not found"))
}
 
fn ort_version() -> Result<String> {
    if let Ok(version) = env::var(ORT_RUST_ENV_VERSION) {
        return Ok(version);
    }
 
    let manifest_dir =
        PathBuf::from(env::var("CARGO_MANIFEST_DIR").context("CARGO_MANIFEST_DIR is not set")?);
    for path in [
        manifest_dir.join("../../VERSION_NUMBER"),
        manifest_dir.join("vendor/onnxruntime-src/VERSION_NUMBER"),
    ] {
        if let Ok(version) = fs::read_to_string(&path) {
            println!("cargo:rerun-if-changed={}", path.display());
            return Ok(version.trim().to_owned());
        }
    }
 
    Err(anyhow!(
        "ONNX Runtime version was not found; set {} explicitly",
        ORT_RUST_ENV_VERSION
    ))
}
 
fn download<P>(source_url: &str, target_file: P)
where
    P: AsRef<Path>,
{
    let resp = ureq::get(source_url)
        .timeout(std::time::Duration::from_secs(300))
        .call()
        .unwrap_or_else(|err| panic!("ERROR: Failed to download {}: {:?}", source_url, err));
 
    let len = resp
        .header("Content-Length")
        .and_then(|s| s.parse::<usize>().ok())
        .unwrap();
    let mut reader = resp.into_reader();
    // FIXME: Save directly to the file
    let mut buffer = vec![];
    let read_len = reader.read_to_end(&mut buffer).unwrap();
    assert_eq!(buffer.len(), len);
    assert_eq!(buffer.len(), read_len);
 
    let f = fs::File::create(&target_file).unwrap();
    let mut writer = io::BufWriter::new(f);
    writer.write_all(&buffer).unwrap();
}
 
fn extract_archive(filename: &Path, output: &Path) {
    match filename.extension().map(std::ffi::OsStr::to_str) {
        Some(Some("zip")) => extract_zip(filename, output),
        Some(Some("tgz")) => extract_tgz(filename, output),
        _ => unimplemented!(),
    }
}
 
fn extract_tgz(filename: &Path, output: &Path) {
    let file = fs::File::open(filename).unwrap();
    let buf = io::BufReader::new(file);
    let tar = flate2::read::GzDecoder::new(buf);
    let mut archive = tar::Archive::new(tar);
    archive.unpack(output).unwrap();
}
 
fn extract_zip(filename: &Path, outpath: &Path) {
    let file = fs::File::open(filename).unwrap();
    let buf = io::BufReader::new(file);
    let mut archive = zip::ZipArchive::new(buf).unwrap();
    for i in 0..archive.len() {
        let mut file = archive.by_index(i).unwrap();
        #[allow(deprecated)]
        let outpath = outpath.join(file.sanitized_name());
        if !file.name().ends_with('/') {
            println!(
                "File {} extracted to \"{}\" ({} bytes)",
                i,
                outpath.as_path().display(),
                file.size()
            );
            if let Some(p) = outpath.parent() {
                if !p.exists() {
                    fs::create_dir_all(p).unwrap();
                }
            }
            let mut outfile = fs::File::create(&outpath).unwrap();
            io::copy(&mut file, &mut outfile).unwrap();
        }
    }
}
 
trait OnnxPrebuiltArchive {
    fn as_onnx_str(&self) -> Cow<str>;
}
 
#[derive(Debug)]
enum Architecture {
    X86,
    X86_64,
    Arm,
    Arm64,
}
 
impl FromStr for Architecture {
    type Err = anyhow::Error;
 
    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "x86" => Ok(Architecture::X86),
            "x86_64" => Ok(Architecture::X86_64),
            "arm" => Ok(Architecture::Arm),
            "aarch64" => Ok(Architecture::Arm64),
            _ => Err(anyhow!("Unsupported architecture: {s}")),
        }
    }
}
 
impl OnnxPrebuiltArchive for Architecture {
    fn as_onnx_str(&self) -> Cow<str> {
        match self {
            Architecture::X86 => Cow::from("x86"),
            Architecture::X86_64 => Cow::from("x64"),
            Architecture::Arm => Cow::from("arm"),
            Architecture::Arm64 => Cow::from("arm64"),
        }
    }
}
 
#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum Os {
    Windows,
    Linux,
    MacOs,
}
 
impl Os {
    fn archive_extension(&self) -> &'static str {
        match self {
            Os::Windows => "zip",
            Os::Linux => "tgz",
            Os::MacOs => "tgz",
        }
    }
}
 
impl FromStr for Os {
    type Err = anyhow::Error;
 
    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "windows" => Ok(Os::Windows),
            "macos" => Ok(Os::MacOs),
            "linux" => Ok(Os::Linux),
            _ => Err(anyhow!("Unsupported os: {s}")),
        }
    }
}
 
impl OnnxPrebuiltArchive for Os {
    fn as_onnx_str(&self) -> Cow<str> {
        match self {
            Os::Windows => Cow::from("win"),
            Os::Linux => Cow::from("linux"),
            Os::MacOs => Cow::from("osx"),
        }
    }
}
 
#[derive(Debug, PartialEq, Eq)]
enum Accelerator {
    Cpu,
    Cuda,
}
 
impl FromStr for Accelerator {
    type Err = anyhow::Error;
 
    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "1" | "yes" | "true" | "on" => Ok(Accelerator::Cuda),
            _ => Ok(Accelerator::Cpu),
        }
    }
}
 
impl OnnxPrebuiltArchive for Accelerator {
    fn as_onnx_str(&self) -> Cow<str> {
        match self {
            Accelerator::Cpu => Cow::from(""),
            Accelerator::Cuda => Cow::from("gpu"),
        }
    }
}
 
#[derive(Debug)]
struct Triplet {
    os: Os,
    arch: Architecture,
    accelerator: Accelerator,
}
 
impl OnnxPrebuiltArchive for Triplet {
    fn as_onnx_str(&self) -> Cow<str> {
        match (&self.os, &self.arch, &self.accelerator) {
            // onnxruntime-win-x86-1.11.1.zip
            // onnxruntime-win-x64-1.11.1.zip
            // onnxruntime-win-arm-1.11.1.zip
            // onnxruntime-win-arm64-1.11.1.zip
            // onnxruntime-linux-x64-1.11.1.tgz
            // onnxruntime-osx-x86_64-1.11.1.tgz
            // onnxruntime-osx-arm64-1.11.1.tgz
            (
                Os::Windows,
                Architecture::X86 | Architecture::X86_64 | Architecture::Arm | Architecture::Arm64,
                Accelerator::Cpu,
            )
            | (Os::MacOs, Architecture::Arm64, Accelerator::Cpu)
            | (Os::Linux, Architecture::X86_64, Accelerator::Cpu) => Cow::from(format!(
                "{}-{}",
                self.os.as_onnx_str(),
                self.arch.as_onnx_str()
            )),
            (Os::MacOs, Architecture::X86_64, Accelerator::Cpu) => Cow::from(format!(
                "{}-x86_{}",
                self.os.as_onnx_str(),
                self.arch.as_onnx_str().trim_start_matches('x')
            )),
            // onnxruntime-win-x64-gpu-1.11.1.zip
            // onnxruntime-linux-x64-gpu-1.11.1.tgz
            (Os::Linux | Os::Windows, Architecture::X86_64, Accelerator::Cuda) => {
                Cow::from(format!(
                    "{}-{}-{}",
                    self.os.as_onnx_str(),
                    self.arch.as_onnx_str(),
                    self.accelerator.as_onnx_str(),
                ))
            }
            _ => {
                panic!(
                    "Unsupported prebuilt triplet: {:?}, {:?}, {:?}. Please use {}=system and {}=/path/to/onnxruntime",
                    self.os, self.arch, self.accelerator, ORT_RUST_ENV_STRATEGY, ORT_RUST_ENV_SYSTEM_LIB_LOCATION
                );
            }
        }
    }
}
 
fn prebuilt_archive_url() -> Result<(PathBuf, String)> {
    let triplet = Triplet {
        os: env::var("CARGO_CFG_TARGET_OS")
            .expect("Unable to get TARGET_OS")
            .parse()
            .unwrap(),
        arch: env::var("CARGO_CFG_TARGET_ARCH")
            .expect("Unable to get TARGET_ARCH")
            .parse()
            .unwrap(),
        accelerator: env::var(ORT_RUST_ENV_GPU)
            .unwrap_or_default()
            .parse()
            .unwrap(),
    };
    let ort_version = ort_version()?;
 
    let prebuilt_archive = format!(
        "onnxruntime-{}-{}.{}",
        triplet.as_onnx_str(),
        ort_version,
        triplet.os.archive_extension()
    );
    let prebuilt_url = format!(
        "{}/v{}/{}",
        ORT_RELEASE_BASE_URL, ort_version, prebuilt_archive
    );
 
    Ok((PathBuf::from(prebuilt_archive), prebuilt_url))
}
 
fn prepare_libort_dir_prebuilt() -> Result<PathBuf> {
    let (prebuilt_archive, prebuilt_url) = prebuilt_archive_url()?;
 
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let extract_dir = out_dir.join(ORT_PREBUILT_EXTRACT_DIR);
    let downloaded_file = out_dir.join(&prebuilt_archive);
    let extracted_dir = extract_dir.join(prebuilt_archive.file_stem().unwrap());
 
    println!("cargo:rerun-if-changed={}", downloaded_file.display());
 
    if !downloaded_file.exists() {
        println!("Creating directory {:?}", out_dir);
        fs::create_dir_all(&out_dir).unwrap();
 
        println!(
            "Downloading {} into {}",
            prebuilt_url,
            downloaded_file.display()
        );
        download(&prebuilt_url, &downloaded_file);
    }
 
    if !extracted_dir.exists() {
        println!("Extracting to {}...", extract_dir.display());
        extract_archive(&downloaded_file, &extract_dir);
    }
 
    Ok(extracted_dir)
}
 
fn prepare_libort_dir() -> Result<PathBuf> {
    let strategy = env::var(ORT_RUST_ENV_STRATEGY);
    println!(
        "strategy: {:?}",
        strategy.as_ref().map_or_else(|_| "unknown", String::as_str)
    );
    match strategy.as_ref().map(String::as_str) {
        Ok("download") => prepare_libort_dir_prebuilt(),
        Ok("system") => {
            let location = env::var(ORT_RUST_ENV_SYSTEM_LIB_LOCATION).context(format!(
                "Could not get value of environment variable {:?}",
                ORT_RUST_ENV_SYSTEM_LIB_LOCATION
            ))?;
            Ok(PathBuf::from(location))
        }
        Ok("compile") | Err(_) => prepare_libort_dir_compiled(),
        _ => Err(anyhow!("Unknown value for {:?}", ORT_RUST_ENV_STRATEGY)),
    }
}
 
fn prepare_libort_dir_compiled() -> Result<PathBuf> {
    let manifest_dir_string = env::var("CARGO_MANIFEST_DIR").unwrap();
    let mut config = cmake::Config::new(format!(
        "{manifest_dir_string}/vendor/onnxruntime-src/cmake"
    ));
 
    config.define("onnxruntime_BUILD_SHARED_LIB", "ON");
 
    if let Ok(Accelerator::Cuda) = env::var(ORT_RUST_ENV_GPU).unwrap_or_default().parse() {
        config.define("onnxruntime_USE_CUDA", "ON");
    };
 
    Ok(config.build())
}