Исходный код СУБД 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
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// Portions Copyright (c) Microsoft Corporation
 
#pragma once
 
#include <iosfwd>
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <gsl/gsl>
 
#include "core/common/common.h"
#include "core/common/path_string.h"
#include "core/platform/env_time.h"
#include "core/platform/telemetry.h"
#include "core/session/onnxruntime_c_api.h"
 
#ifndef _WIN32
#include <sys/types.h>
#include <unistd.h>
#endif
namespace Eigen {
class ThreadPoolInterface;
}
namespace onnxruntime {
 
#ifdef _WIN32
using PIDType = unsigned long;
using FileOffsetType = int64_t;
#else
using PIDType = pid_t;
using FileOffsetType = off_t;
#endif
 
class EnvThread {
 public:
  virtual ~EnvThread() = default;
 
 protected:
  OrtCustomCreateThreadFn custom_create_thread_fn = nullptr;
  void* custom_thread_creation_options = nullptr;
  OrtCustomJoinThreadFn custom_join_thread_fn = nullptr;
  OrtCustomThreadHandle custom_thread_handle = nullptr;
};
 
/// Type that holds a collection of logical processors IDs used for setting affinities.
using LogicalProcessors = std::vector<int>;
 
// Parameters that are required to create a set of threads for a thread pool
struct ThreadOptions {
  // Stack size for a new thread. If it is 0, the operating system uses the same value as the stack that's specified for
  // the main thread, which is usually set in the main executable(not controlled by onnxruntime.dll).
  unsigned int stack_size = 0;
 
  // Thread affinity means a thread can only run on the logical processor(s) that the thread is allowed to run on.
  // If the vector is not empty, then set the affinity of each thread to logical cpus ids within the LogicalProcessors.
  // For example, the first thread in the pool will be bound to the logical processors contained in affinity[0].
  // If the vector is empty, the thread can run on all the processors its process can run on.
  // NOTE: When hyperthreading is enabled, for example, on a 4 cores we would have 8 logical processors,
  // processor group [0,1,2,3] may only occupy up some of the physical cores. There might be more than 2 logical
  // processor per physical core on a given computer. Physical cores assigned to a given VM may contain
  // logical processor indices that do not start with 0 and possibly go beyond the number of bits in an integer.
  //
  // If the size of the TP is not specified, ORT creates thread pools with a number of threads that are equal
  // to the number of visible physical cores. The threads affinities are set to all of the logical processors
  // that are contained in a given physical core with the same index as the thread. ORT does not set any affinity
  // to the thread that is considered main (the thread that initiates the creation of the TP).
  // The process that owns the thread may consider setting its affinity.
  std::vector<LogicalProcessors> affinities;
 
  // Set or unset denormal as zero.
  bool set_denormal_as_zero = false;
 
  OrtCustomCreateThreadFn custom_create_thread_fn = nullptr;
  void* custom_thread_creation_options = nullptr;
  OrtCustomJoinThreadFn custom_join_thread_fn = nullptr;
  int dynamic_block_base_ = 0;
 
#ifdef ORT_ENABLE_SESSION_THREADPOOL_CALLBACKS
  // Optional callbacks for thread pool work scheduling.
  // The pointed-to struct must remain valid until the ThreadPool constructor returns
  // (the constructor copies the callback values).
  const OrtThreadPoolCallbacksConfig* work_callbacks = nullptr;
#endif
};
 
std::ostream& operator<<(std::ostream& os, const LogicalProcessors&);
std::ostream& operator<<(std::ostream& os, gsl::span<const LogicalProcessors>);
 
/// <summary>
/// Get errno and the corresponding error message.
/// </summary>
/// <returns>errno and the error message string if errno indicates an error.</returns>
std::pair<int, std::string> GetErrnoInfo();
 
/**
 * An owned open file supporting concurrent positional reads.
 *
 * Reads, mappings, length queries, and canonical-path queries refer to the same file even if its pathname is replaced.
 * This is not a snapshot: callers must not modify the file in place while reading it.
 * Keep the object alive until all callers have finished. Its destruction closes the file.
 */
class RandomAccessFile {
 public:
  struct MappedMemoryDeleter {
    using UnmapFn = void (*)(void* mapped_base, size_t mapped_length) noexcept;
 
    void* mapped_base{};
    size_t mapped_length{};
    UnmapFn unmap{};
 
    void operator()(char*) const noexcept {
      if (unmap != nullptr) {
        unmap(mapped_base, mapped_length);
      }
    }
  };
 
  using MappedMemoryPtr = std::unique_ptr<char[], MappedMemoryDeleter>;
 
  virtual ~RandomAccessFile() = default;
 
  // Query the open file, leaving length unchanged on failure.
  virtual common::Status GetLength(uint64_t& length) const = 0;
 
  // Return the canonical path of this open file handle.
  virtual common::Status GetCanonicalPath(PathString& path) const = 0;
 
  // Map bytes from this open file without reopening its pathname.
  virtual common::Status Map(FileOffsetType offset, size_t length, MappedMemoryPtr& mapped_memory) const = 0;
 
  /**
   * Fill buffer starting at offset without changing a shared file position.
   * Concurrent calls must use disjoint buffers. Returns only after all I/O has completed.
   * Negative offsets, unrepresentable ranges, and unexpected EOF are errors.
   * An empty buffer succeeds for any nonnegative offset. On failure, buffer may be partially written.
   */
  virtual common::Status Read(FileOffsetType offset, gsl::span<char> buffer) const = 0;
 
 protected:
  RandomAccessFile() = default;
 
 private:
  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(RandomAccessFile);
};
 
/// \brief An interface used by the onnxruntime implementation to
/// access operating system functionality like the filesystem etc.
///
/// Callers may wish to provide a custom Env object to get fine grain
/// control.
///
/// All Env implementations are safe for concurrent access from
/// multiple threads without any external synchronization.
class Env {
 public:
  using EnvThread = onnxruntime::EnvThread;
  virtual ~Env() = default;
  // clang-format off
  /**
   * Start a new thread for a thread pool
   * \param name_prefix A human-readable string for debugging purpose, can be NULL
   * \param index The index value of the thread, for each thread pool instance, the index should start from 0 and be continuous.
   * \param start_address The entry point of thread
   * \param threadpool The thread pool that the new thread belongs to
   * \param thread_options options to create the thread
   *
   * Caller is responsible for deleting the returned value
   */
  // clang-format on
  virtual EnvThread* CreateThread(_In_opt_z_ const ORTCHAR_T* name_prefix, int index,
                                  _In_ unsigned (*start_address)(int id, Eigen::ThreadPoolInterface* param),
                                  Eigen::ThreadPoolInterface* threadpool, const ThreadOptions& thread_options) = 0;
 
  /// \brief Returns a default environment suitable for the current operating
  /// system.
  ///
  /// Sophisticated users may wish to provide their own Env
  /// implementation instead of relying on this default environment.
  ///
  /// The result of Default() belongs to this library and must never be deleted.
  static Env& Default();
 
  /// <summary>
  /// The API returns the number of different physical cores on the system
  /// </summary>
  /// <returns>Number of physical cores</returns>
  virtual int GetNumPhysicalCpuCores() const = 0;
 
  virtual std::vector<LogicalProcessors> GetDefaultThreadAffinities() const = 0;
 
  virtual int GetL2CacheSize() const = 0;
 
  /// \brief Returns the number of micro-seconds since the Unix epoch.
  virtual uint64_t NowMicros() const {
    return env_time_->NowMicros();
  }
 
  /// \brief Returns the number of seconds since the Unix epoch.
  virtual uint64_t NowSeconds() const {
    return env_time_->NowSeconds();
  }
 
  /// Sleeps/delays the thread for the prescribed number of micro-seconds.
  /// On Windows, it's the min time to sleep, not the actual one.
  virtual void SleepForMicroseconds(int64_t micros) const = 0;
 
  /**
   * Gets the length of the specified file.
   */
  virtual common::Status GetFileLength(_In_z_ const ORTCHAR_T* file_path, size_t& length) const = 0;
  virtual common::Status GetFileLength(int fd, /*out*/ size_t& file_size) const = 0;
 
  /**
   * Copies the content of the file into the provided buffer.
   * @param file_path The path to the file.
   * @param offset The file offset from which to start reading.
   * @param length The length in bytes to read.
   * @param buffer The buffer in which to write.
   */
  virtual common::Status ReadFileIntoBuffer(_In_z_ const ORTCHAR_T* file_path, FileOffsetType offset, size_t length,
                                            gsl::span<char> buffer) const = 0;
 
  using MappedMemoryPtr = std::unique_ptr<char[], std::function<void(void*)>>;
 
  /**
   * Maps the content of the file into memory.
   * This is a copy-on-write mapping, so any changes are not written to the
   * actual file.
   * @param file_path The path to the file.
   * @param offset The file offset from which to start the mapping.
   * @param length The length in bytes of the mapping.
   * @param[out] mapped_memory A smart pointer to the mapped memory which
   *             unmaps the memory (unless release()'d) when destroyed.
   */
  virtual common::Status MapFileIntoMemory(_In_z_ const ORTCHAR_T* file_path, FileOffsetType offset, size_t length,
                                           MappedMemoryPtr& mapped_memory) const = 0;
 
#ifdef _WIN32
  /// \brief Returns true if the directory exists.
  virtual bool FolderExists(const std::wstring& path) const = 0;
  virtual bool FileExists(const std::wstring& path) const = 0;
  /// \brief Recursively creates the directory, if it doesn't exist.
  virtual common::Status CreateFolder(const std::wstring& path) const = 0;
  // Mainly for use with protobuf library
  virtual common::Status FileOpenRd(const std::wstring& path, /*out*/ int& fd) const = 0;
  // Mainly for use with protobuf library
  virtual common::Status FileOpenWr(const std::wstring& path, /*out*/ int& fd) const = 0;
#endif
  /// \brief Returns true if the directory exists.
  virtual bool FolderExists(const std::string& path) const = 0;
  virtual bool FileExists(const std::string& path) const = 0;
  /// \brief Recursively creates the directory, if it doesn't exist.
  virtual common::Status CreateFolder(const std::string& path) const = 0;
  // Recursively deletes the directory and its contents.
  // Note: This function is not thread safe!
  virtual common::Status DeleteFolder(const PathString& path) const = 0;
  // Mainly for use with protobuf library
  virtual common::Status FileOpenRd(const std::string& path, /*out*/ int& fd) const = 0;
  // Mainly for use with protobuf library
  virtual common::Status FileOpenWr(const std::string& path, /*out*/ int& fd) const = 0;
  // Mainly for use with protobuf library
  virtual common::Status FileClose(int fd) const = 0;
 
  /** Gets the canonical form of a file path (symlinks resolved). */
  virtual common::Status GetCanonicalPath(
      const PathString& path,
      PathString& canonical_path) const = 0;
 
  /** Like GetCanonicalPath, but the path is not required to exist. Mirrors
   *  std::filesystem::weakly_canonical. */
  virtual common::Status GetWeaklyCanonicalPath(
      const PathString& path,
      PathString& canonical_path) const = 0;
 
  // This functions is always successful. It can't fail.
  virtual PIDType GetSelfPid() const = 0;
 
  // \brief Load a dynamic library.
  //
  // Pass "library_filename" to a platform-specific mechanism for dynamically
  // loading a library.  The rules for determining the exact location of the
  // library are platform-specific and are not documented here.
  //
  // global_symbols only has an effect on unix, where a value of true means to load with RTLD_GLOBAL vs RTLD_LOCAL
  //
  // On success, returns a handle to the library in "*handle" and returns
  // OK from the function.
  // Otherwise returns nullptr in "*handle" and an error status from the
  // function.
  virtual common::Status LoadDynamicLibrary(const PathString& library_filename, bool global_symbols, void** handle) const = 0;
 
  virtual common::Status UnloadDynamicLibrary(void* handle) const = 0;
 
  // \brief Gets the file path of the onnx runtime code
  //
  // Used to help load other shared libraries that live in the same folder as the core code.
  // For example, the DNNL provider shared library.
  virtual PathString GetRuntimePath() const = 0;
 
  // \brief Get a pointer to a symbol from a dynamic library.
  //
  // "handle" should be a pointer returned from a previous call to LoadDynamicLibrary.
  // On success, store a pointer to the located symbol in "*symbol" and return
  // OK from the function. Otherwise, returns nullptr in "*symbol" and an error
  // status from the function.
  virtual common::Status GetSymbolFromLibrary(void* handle, const std::string& symbol_name, void** symbol) const = 0;
 
  // \brief build the name of dynamic library.
  //
  // "name" should be name of the library.
  // "version" should be the version of the library or NULL
  // returns the name that LoadDynamicLibrary() can use
  virtual std::string FormatLibraryFileName(const std::string& name, const std::string& version) const = 0;
 
  // \brief returns a provider that will handle telemetry on the current platform
  virtual const Telemetry& GetTelemetryProvider() const = 0;
 
  // \brief returns a value for the queried variable name (var_name)
  //
  // Returns the corresponding value stored in the environment variable if available
  // Returns empty string if there is no such environment variable available
  virtual std::string GetEnvironmentVar(const std::string& var_name) const = 0;
 
  /**
   * Open a regular file for positional reads. Leaves file unchanged on failure.
   * Retain the returned object across every read that must use the same file identity,
   * for example throughout loading a tensor or all tensors from one external-data file.
   * Custom environments can override this to supply their own file implementation.
   */
  virtual common::Status OpenRandomAccessFile(const ORTCHAR_T* /*file_path*/,
                                              std::unique_ptr<RandomAccessFile>& /*file*/) const {
    return ORT_MAKE_STATUS(ONNXRUNTIME, NOT_IMPLEMENTED, "This environment does not support random-access files.");
  }
 
 protected:
  Env();
 
 private:
  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Env);
  EnvTime* env_time_ = EnvTime::Default();
};
 
}  // namespace onnxruntime