Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#pragma once
 
#include <atomic>
#include <filesystem>
#include <memory>
#include <optional>
#include <vector>
#include <shared_mutex>
#include <string>
 
#include "core/common/common.h"
#include "core/common/basic_types.h"
#include "core/common/logging/logging.h"
#include "core/common/status.h"
#include "core/framework/allocator.h"
#include "core/framework/execution_provider.h"
#include "core/framework/data_transfer_manager.h"
#include "core/platform/device_discovery.h"
#include "core/platform/threadpool.h"
 
#include "core/session/abi_devices.h"
#include "core/session/abi_key_value_pairs.h"
#include "core/session/plugin_ep/ep_library.h"
#include "core/session/onnxruntime_c_api.h"
 
struct OrtThreadingOptions;
namespace onnxruntime {
class EpFactoryInternal;
class InferenceSession;
struct IExecutionProviderFactory;
struct OrtAllocatorImplWrappingIAllocator;
struct SessionOptions;
 
namespace plugin_ep {
class DataTransfer;
}  // namespace plugin_ep
 
/**
   Provides the runtime environment for onnxruntime.
   Create one instance for the duration of execution.
*/
class Environment {
 public:
  /**
     Create and initialize the runtime environment.
    @param logging manager instance that will enable per session logger output using
    session_options.session_logid as the logger id in messages.
    If nullptr, the default LoggingManager MUST have been created previously as it will be used
    for logging. This will use the default logger id in messages.
    See core/common/logging/logging.h for details, and how LoggingManager::DefaultLogger works.
    @param tp_options optional set of parameters controlling the number of intra and inter op threads for the global
    threadpools.
    @param create_global_thread_pools determine if this function will create the global threadpools or not.
    @param config_entries Application-specified configuration entries.
  */
  static Status Create(std::unique_ptr<logging::LoggingManager> logging_manager,
                       std::unique_ptr<Environment>& environment,
                       const OrtThreadingOptions* tp_options = nullptr,
                       bool create_global_thread_pools = false,
                       const OrtKeyValuePairs* config_entries = nullptr);
 
  /**
   * Set the global threading options for the environment, if no global thread pools have been created yet.
   *
   * This function is not safe to call simultaneously from multiple threads, and will return a FAIL status on all calls
   * after the first.
   * @param tp_options set of parameters controlling the number of intra and inter op threads for the global
    threadpools.
   */
  Status SetGlobalThreadingOptions(const OrtThreadingOptions& tp_options);
 
  logging::LoggingManager* GetLoggingManager() const {
    return logging_manager_.get();
  }
 
  void SetLoggingManager(std::unique_ptr<onnxruntime::logging::LoggingManager> logging_manager) {
    logging_manager_ = std::move(logging_manager);
  }
 
  onnxruntime::concurrency::ThreadPool* GetIntraOpThreadPool() const {
    return intra_op_thread_pool_.get();
  }
 
  onnxruntime::concurrency::ThreadPool* GetInterOpThreadPool() const {
    return inter_op_thread_pool_.get();
  }
 
  bool EnvCreatedWithGlobalThreadPools() const {
    return create_global_thread_pools_;
  }
 
  /**
   * Registers an allocator for sharing between multiple sessions.
   * Return an error if an allocator with the same OrtMemoryInfo is already registered.
   */
  Status RegisterAllocator(OrtAllocator* allocator);
 
  /**
   * Creates and registers an allocator for sharing between multiple sessions.
   * Return an error if an allocator with the same OrtMemoryInfo is already registered.
   */
  Status CreateAndRegisterAllocator(const OrtMemoryInfo& mem_info, const OrtArenaCfg* arena_cfg = nullptr);
 
  /**
   * Returns the list of registered allocators in this env.
   */
  const std::vector<AllocatorPtr>& GetRegisteredSharedAllocators() const {
    return shared_allocators_;
  }
 
  /**
   * Returns an AllocatorPtr for a shared IAllocator based allocator if it matches the memory info.
   * The OrtMemoryInfo name and whether it's an arena or device allocator is ignored in the lookup, as is the
   * alignment.
   * The user calling this function is not expected to know the alignment, and we expect the allocator instance to be
   * created with a valid alignment for the device.
   */
  AllocatorPtr GetRegisteredSharedAllocator(const OrtMemoryInfo& mem_info) const;
 
  /**
   * Removes registered allocator that was previously registered for sharing between multiple sessions.
   */
  Status UnregisterAllocator(const OrtMemoryInfo& mem_info);
 
  Environment() = default;
 
  /**
   * Create and register an allocator, specified by provider_type, for sharing between multiple sessions.
   * Return an error if an allocator with the same OrtMemoryInfo is already registered.
   * For provider_type please refer core/graph/constants.h
   */
  Status CreateAndRegisterAllocatorV2(const std::string& provider_type, const OrtMemoryInfo& mem_info,
                                      const std::unordered_map<std::string, std::string>& options,
                                      const OrtArenaCfg* arena_cfg = nullptr);
 
#if !defined(ORT_MINIMAL_BUILD)
  Status RegisterExecutionProviderLibrary(const std::string& registration_name, const ORTCHAR_T* lib_path);
  Status UnregisterExecutionProviderLibrary(const std::string& registration_name);
 
  /**
   * Passkey that restricts CreateAndRegisterStaticPluginEps() to OrtEnv, which is the only caller able to satisfy
   * that function's ordering and locking requirements. Only OrtEnv can construct one.
   */
  class StaticPluginEpRegistrationToken {
   private:
    StaticPluginEpRegistrationToken() = default;
    ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(StaticPluginEpRegistrationToken);
    friend struct ::OrtEnv;
  };
 
  /**
   * Register the plugin execution providers that are statically linked into the ORT binary.
   *
   * This must be called after the OrtEnv singleton that owns this Environment has been published, because a
   * statically linked plugin EP uses the public ORT API, and any OrtEnv API it calls must be able to find the
   * instance.
   *
   * The passkey parameter limits the set of possible callers to OrtEnv.
   */
  Status CreateAndRegisterStaticPluginEps(StaticPluginEpRegistrationToken);
 
  // convert an OrtEpFactory* to EpFactoryInternal* if possible.
  EpFactoryInternal* GetEpFactoryInternal(OrtEpFactory* factory) const {
    // we're comparing pointers so the reinterpret_cast should be safe
    auto it = internal_ep_factories_.find(reinterpret_cast<EpFactoryInternal*>(factory));
    return it != internal_ep_factories_.end() ? *it : nullptr;
  }
 
  const std::vector<const OrtEpDevice*>& GetOrtEpDevices() const {
    return execution_devices_;
  }
 
  /// Get hardware device incompatibility details for a specific EP.
  /// @param ep_name The name of the execution provider to check.
  /// @param hw The hardware device to check for incompatibility.
  /// @param details Output: Incompatibility details including reasons for incompatibility if any.
  /// @returns Status indicating success or failure.
  Status GetHardwareDeviceEpIncompatibilityDetails(const std::string& ep_name,
                                                   const OrtHardwareDevice* hw,
                                                   std::unique_ptr<OrtDeviceEpIncompatibilityDetails>& details) const;
 
  const std::vector<const OrtHardwareDevice*>& GetSortedOrtHardwareDevices() const;
 
  Status CreateSharedAllocator(const OrtEpDevice& ep_device,
                               OrtDeviceMemoryType mem_type, OrtAllocatorType allocator_type,
                               const OrtKeyValuePairs* allocator_options, OrtAllocator** allocator);
  Status ReleaseSharedAllocator(const OrtEpDevice& ep_device, OrtDeviceMemoryType mem_type);
 
  const DataTransferManager& GetDataTransferManager() const {
    return data_transfer_mgr_;
  }
#endif  // !defined(ORT_MINIMAL_BUILD)
 
  // return a shared allocator from a plugin EP or custom allocator added with RegisterAllocator
  Status GetSharedAllocator(const OrtMemoryInfo& mem_info, OrtAllocator*& allocator);
 
  /// <summary>
  /// Returns a copy of the configuration entries set by the application on environment creation.
  ///
  /// Primarily used by EP libraries to retrieve environment-level configurations, but could be used
  /// more generally to specify global settings.
  ///
  /// Refer to OrtApi::CreateEnvWithOptions().
  /// </summary>
  /// <returns></returns>
  OrtKeyValuePairs GetConfigEntries() const;
 
#ifdef ORT_ENABLE_SESSION_THREADPOOL_CALLBACKS
  /**
   * Returns the per-session thread pool work callbacks, or nullptr if not set.
   *
   * Not safe to call concurrently with SetPerSessionWorkCallbacks.
   */
  const OrtThreadPoolCallbacksConfig* GetPerSessionWorkCallbacks() const {
    return per_session_work_callbacks_.has_value()
               ? &per_session_work_callbacks_.value()
               : nullptr;
  }
 
  /**
   * Sets thread pool work callbacks for per-session thread pools.
   * Only affects sessions created after this call. Does not affect global thread pools.
   *
   * Not safe to call concurrently with GetPerSessionWorkCallbacks or session creation.
   * Must be called before creating any sessions that should use the callbacks.
   */
  Status SetPerSessionWorkCallbacks(const OrtThreadPoolCallbacksConfig& config);
#endif
 
  ~Environment();
 
 private:
  ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(Environment);
 
  Status Initialize(std::unique_ptr<logging::LoggingManager> logging_manager,
                    const OrtThreadingOptions* tp_options = nullptr,
                    bool create_global_thread_pools = false,
                    const OrtKeyValuePairs* config_entries = nullptr);
 
  Status RegisterAllocatorImpl(AllocatorPtr allocator);
  Status UnregisterAllocatorImpl(const OrtMemoryInfo& mem_info, bool error_if_not_found = true);
  Status CreateSharedAllocatorImpl(const OrtEpDevice& ep_device,
                                   const OrtMemoryInfo& memory_info, OrtAllocatorType allocator_type,
                                   const OrtKeyValuePairs* allocator_options, OrtAllocator** allocator,
                                   bool replace_existing);
 
  // Inserts (or assigns) a config entry into `config_entries_`. Locks `config_entries_mutex_`.
  void InsertOrAssignConfigEntry(std::string key, std::string value);
 
  // Removes a config entry from `config_entries_`. Does nothing if the key does not exist.
  // Locks `config_entries_mutex_`.
  void RemoveConfigEntry(const std::string& key);
 
  std::unique_ptr<logging::LoggingManager> logging_manager_;
  std::unique_ptr<onnxruntime::concurrency::ThreadPool> intra_op_thread_pool_;
  std::unique_ptr<onnxruntime::concurrency::ThreadPool> inter_op_thread_pool_;
  bool create_global_thread_pools_{false};
 
  mutable std::mutex mutex_;
 
  // shared allocators from various sources.
  // CreateAndRegisterAllocator[V2]: IAllocator allocators created by ORT
  // RegisterAllocator: IAllocatorImplWrappingOrtAllocator custom allocators registered by the user.
  //                    TODO: How can we detect registration of an allocator from an InferenceSession?
  // OrtEpDevice: We create a default shared IAllocatorImplWrappingOrtAllocator for each OrtEpDevice memory info.
  std::vector<AllocatorPtr> shared_allocators_;
 
  // RegisterAllocator and CreateSharedAllocator pointers. Used for GetSharedAllocator.
  // Every instance here is also in shared_allocators_.
  std::unordered_set<OrtAllocator*> shared_ort_allocators_;
 
  // OrtAllocator wrapped CPUAllocator::DefaultInstance that is returned by GetSharedAllocator when no plugin EP is
  // providing a CPU allocator.
  std::unique_ptr<OrtAllocatorImplWrappingIAllocator> default_cpu_ort_allocator_;
 
#if !defined(ORT_MINIMAL_BUILD)
  // register EPs that are built into the ORT binary so they can take part in AutoEP selection
  // added to ep_libraries
  Status CreateAndRegisterInternalEps();
 
  Status RegisterExecutionProviderLibrary(const std::string& registration_name,
                                          std::unique_ptr<EpLibrary> ep_library,
                                          const std::vector<EpFactoryInternal*>& internal_factories = {});
 
  struct EpInfo {
    // Calls EpLibrary::Load.
    // For each factory, gets the OrtEpDevice instances and adds to `out.execution_devices`.
    // Provide `internal_factories` if this is an internal EP.
    // If successful, `out` is set to the created instance.
    static Status Create(std::unique_ptr<EpLibrary> library_in, std::unique_ptr<EpInfo>& out,
                         const std::vector<EpFactoryInternal*>& internal_factories = {});
 
    // removes entries for this library from execution_devices
    // calls EpLibrary::Unload
    ~EpInfo();
 
    std::unique_ptr<EpLibrary> library;
    std::vector<std::unique_ptr<OrtEpDevice>> execution_devices;
    std::vector<OrtEpFactory*> factories;
    std::vector<EpFactoryInternal*> internal_factories;    // factories that can create IExecutionProvider instances
    std::vector<plugin_ep::DataTransfer*> data_transfers;  // data transfer instances for this EP.
 
   private:
    EpInfo() = default;
  };
 
  // registration name to EpInfo for library
  std::unordered_map<std::string, std::unique_ptr<EpInfo>> ep_libraries_;
 
  // combined set of OrtEpDevices for all registered OrtEpFactory instances
  // std::vector so we can use directly in GetEpDevices.
  // inefficient when EPs are unregistered but that is not expected to be a common operation.
  std::vector<const OrtEpDevice*> execution_devices_;
 
  // lookup set for internal EPs so we can create an IExecutionProvider directly
  std::unordered_set<EpFactoryInternal*> internal_ep_factories_;
 
  DataTransferManager data_transfer_mgr_;  // plugin EP IDataTransfer instances
 
#endif  // !defined(ORT_MINIMAL_BUILD)
 
  // Application-specified environment configuration entries
  // The environment may add or remove an entry on EP library registration and unregistration, respectively.
  OrtKeyValuePairs config_entries_;
  mutable std::shared_mutex config_entries_mutex_;  // Should be locked when accessing config_entries_
 
  // Tracks the number of registered EP libraries that can create virtual devices.
  // It is incremented when an EP library is registered with a name that ends in ".virtual".
  // It is decremented when that EP library is unregistered.
  // If it reaches 0, the config entry "allow_virtual_devices" is removed.
  //
  // This starts at 1 if user created an OrtEnv with the config "allow_virtual_devices" set to "1"
  // to prevent removal of the config entry in that case.
  size_t num_allow_virtual_device_uses_{};
 
#ifdef ORT_ENABLE_SESSION_THREADPOOL_CALLBACKS
  std::optional<OrtThreadPoolCallbacksConfig> per_session_work_callbacks_;
#endif
};
 
}  // namespace onnxruntime