Исходный код СУБД 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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
 
#include "core/platform/device_discovery.h"
#include "core/platform/linux/drm_device_discovery.h"
#include "core/platform/linux/npu_device_discovery.h"
#include "core/platform/linux/pci_device_discovery.h"
 
#include <filesystem>
#include <fstream>
#include <iterator>
#include <optional>
#include <regex>
#include <string>
#include <string_view>
 
#include "core/common/common.h"
#include "core/common/logging/logging.h"
#include "core/common/parse_string.h"
#include "core/common/pci_vendor_ids.h"
#include "core/common/string_utils.h"
 
namespace fs = std::filesystem;
 
namespace onnxruntime {
 
namespace {
 
Status ErrorCodeToStatus(const std::error_code& ec, const std::filesystem::path& path, const std::string_view context) {
  if (!ec) {
    return Status::OK();
  }
 
  return Status{common::StatusCategory::ONNXRUNTIME, common::StatusCode::FAIL,
                MakeString("Error: std::error_code with category name: ", ec.category().name(),
                           ", value: ", ec.value(), ", message: ", ec.message(), ", filesystem path: ", path, ", context: ", context)};
}
 
Status ReadFileContents(const fs::path& file_path, std::string& contents) {
  std::ifstream file{file_path};
  ORT_RETURN_IF_NOT(file, "Failed to open file: ", file_path);
  std::istreambuf_iterator<char> file_begin{file}, file_end{};
  contents.assign(file_begin, file_end);
  return Status::OK();
}
 
bool HasUeventEntry(std::string_view uevent, std::string_view entry) {
  size_t entry_pos = uevent.find(entry);
  while (entry_pos != std::string_view::npos) {
    const size_t entry_end = entry_pos + entry.size();
    if ((entry_pos == 0 || uevent[entry_pos - 1] == '\n') &&
        (entry_end == uevent.size() || uevent[entry_end] == '\n')) {
      return true;
    }
 
    entry_pos = uevent.find(entry, entry_end);
  }
 
  return false;
}
 
template <typename ValueType>
Status ReadValueFromFile(const fs::path& file_path, ValueType& value) {
  std::string file_text{};
  ORT_RETURN_IF_ERROR(ReadFileContents(file_path, file_text));
  file_text = utils::TrimString(file_text);
  return ParseStringWithClassicLocale<ValueType>(file_text, value);
}
 
std::optional<bool> IsGpuDiscrete(uint16_t vendor_id, uint16_t device_id) {
  ORT_UNUSED_PARAMETER(device_id);
 
  // Currently, we only assume that all Nvidia GPUs are discrete.
 
  if (vendor_id == pci_vendor_ids::kNvidia) {
    return true;
  }
 
  return std::nullopt;
}
 
Status GetPciBusId(const std::filesystem::path& sysfs_path, std::optional<std::string>& pci_bus_id) {
  constexpr const char* regex_pattern{R"([0-9a-f]+:[0-9a-f]+:[0-9a-f]+[.][0-9a-f]+)"};
  static const std::regex pci_bus_id_regex(regex_pattern);
 
  std::error_code error_code;
  auto pci_bus_id_path = std::filesystem::canonical(sysfs_path / "device", error_code);  // resolves symlink to PCI bus id, e.g. 0000:65:00.0
  ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, sysfs_path / "device", "Getting PCI bus id from sysfs device by resolving symlink"));
 
  auto pci_bus_id_filename = pci_bus_id_path.filename();
  if (std::regex_match(pci_bus_id_filename.string(), pci_bus_id_regex)) {
    pci_bus_id = pci_bus_id_filename.string();
  } else {
    pci_bus_id = {};
    LOGS_DEFAULT(WARNING) << MakeString("Skipping pci_bus_id for PCI path at \"",
                                        pci_bus_id_path.string(),
                                        "\" because filename ", pci_bus_id_filename, " did not match expected pattern of ",
                                        regex_pattern);
  }
 
  return Status::OK();
}
 
}  // namespace
 
namespace drm_device_discovery {
 
Status DetectGpuSysfsPaths(const fs::path& sysfs_class_drm_path,
                           std::vector<GpuSysfsPathInfo>& gpu_sysfs_paths_out) {
  std::error_code error_code{};
  const bool sysfs_class_drm_path_exists = fs::exists(sysfs_class_drm_path, error_code);
  ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, sysfs_class_drm_path, "Checking existence of DRM sysfs path"));
 
  if (!sysfs_class_drm_path_exists) {
    gpu_sysfs_paths_out = {};
    return Status::OK();
  }
 
  const auto detect_card_path = [](const fs::path& sysfs_path, size_t& card_idx) -> bool {
    const auto filename = sysfs_path.filename();
    const auto filename_str = std::string_view{filename.native()};
 
    constexpr std::string_view prefix = "card";
    if (filename_str.find(prefix) != 0) {
      return false;
    }
 
    size_t parsed_card_idx{};
    if (!TryParseStringWithClassicLocale<size_t>(filename_str.substr(prefix.size()), parsed_card_idx)) {
      return false;
    }
 
    card_idx = parsed_card_idx;
    return true;
  };
 
  std::vector<GpuSysfsPathInfo> gpu_sysfs_paths{};
 
  auto dir_iterator = fs::directory_iterator{sysfs_class_drm_path, error_code};
  ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, sysfs_class_drm_path, "Iterating over DRM sysfs devices"));
 
  for (const auto& dir_item : dir_iterator) {
    const auto& dir_item_path = dir_item.path();
    size_t card_idx{};
    if (!detect_card_path(dir_item_path, card_idx)) {
      continue;
    }
 
    const auto vendor_path = dir_item_path / "device" / "vendor";
    const bool vendor_path_exists = fs::exists(vendor_path, error_code);
    ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, vendor_path, "Checking existence of DRM card vendor sysfs attribute"));
 
    bool is_nvidia_platform_gpu = false;
    if (!vendor_path_exists) {
      std::string uevent;
      const auto status = ReadFileContents(dir_item_path / "device" / "uevent", uevent);
      is_nvidia_platform_gpu = status.IsOK() &&
                               (HasUeventEntry(uevent, "DRIVER=nvgpu") ||
                                HasUeventEntry(uevent, "DRIVER=nvidia") ||
                                HasUeventEntry(uevent, "DRIVER=nv_platform"));
      if (!is_nvidia_platform_gpu) {
        LOGS_DEFAULT(VERBOSE) << "Skipping non-PCI DRM card: " << dir_item_path;
        continue;
      }
    }
 
    gpu_sysfs_paths.push_back({card_idx, dir_item_path, is_nvidia_platform_gpu});
  }
 
  gpu_sysfs_paths_out = std::move(gpu_sysfs_paths);
  return Status::OK();
}
 
Status GetGpuDeviceFromSysfs(const GpuSysfsPathInfo& path_info, OrtHardwareDevice& gpu_device_out) {
  OrtHardwareDevice gpu_device{};
  const auto& sysfs_path = path_info.path;
 
  uint16_t vendor_id = pci_vendor_ids::kNvidia;
  if (!path_info.is_nvidia_platform_gpu) {
    const auto vendor_id_path = sysfs_path / "device" / "vendor";
    ORT_RETURN_IF_ERROR(ReadValueFromFile(vendor_id_path, vendor_id));
  }
  gpu_device.vendor_id = vendor_id;
 
  // TODO vendor name
 
  uint16_t device_id{};
  if (!path_info.is_nvidia_platform_gpu) {
    const auto device_id_path = sysfs_path / "device" / "device";
    ORT_RETURN_IF_ERROR(ReadValueFromFile(device_id_path, device_id));
  }
  gpu_device.device_id = device_id;
 
  gpu_device.metadata.Add("card_idx", MakeString(path_info.card_idx));
 
  if (path_info.is_nvidia_platform_gpu) {
    gpu_device.metadata.Add("Discrete", "0");
  } else if (const auto is_gpu_discrete = IsGpuDiscrete(vendor_id, device_id);
             is_gpu_discrete.has_value()) {
    gpu_device.metadata.Add("Discrete", (*is_gpu_discrete ? "1" : "0"));
  }
 
  if (!path_info.is_nvidia_platform_gpu) {
    std::optional<std::string> pci_bus_id;
    ORT_RETURN_IF_ERROR(GetPciBusId(sysfs_path, pci_bus_id));
    if (pci_bus_id) {
      gpu_device.metadata.Add("pci_bus_id", std::move(*pci_bus_id));
    }
  }
 
  gpu_device.type = OrtHardwareDeviceType_GPU;
 
  gpu_device_out = std::move(gpu_device);
  return Status::OK();
}
 
}  // namespace drm_device_discovery
 
// PCI bus-based GPU detection as a fallback for environments where DRM sysfs entries
// are not available (e.g., AKS/Kubernetes containers where the nvidia-drm kernel module
// is not loaded but GPU PCI devices are still exposed via sysfs).
 
namespace pci_device_discovery {
 
Status DetectGpuPciPaths(const fs::path& sysfs_pci_devices_path,
                         std::vector<GpuPciPathInfo>& gpu_pci_paths_out) {
  std::error_code error_code{};
  const bool path_exists = fs::exists(sysfs_pci_devices_path, error_code);
  ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, sysfs_pci_devices_path, "Checking path exists"));
 
  if (!path_exists) {
    gpu_pci_paths_out = {};
    return Status::OK();
  }
 
  std::vector<GpuPciPathInfo> gpu_pci_paths{};
 
  auto dir_iterator = fs::directory_iterator{sysfs_pci_devices_path, error_code};
  ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, sysfs_pci_devices_path, "Getting directory_iterator"));
 
  for (const auto& dir_item : dir_iterator) {
    const auto& device_path = dir_item.path();
 
    // Read PCI class code to identify GPU devices.
    // The class file contains a 24-bit value: 0xCCSSpp (class/subclass/prog-if).
    uint32_t pci_class{};
    if (auto status = ReadValueFromFile(device_path / "class", pci_class); !status.IsOK()) {
      continue;
    }
 
    // Check for GPU/display controller PCI class codes:
    //   Base class 0x03 = Display controller
    //   Sub-class 0x00 = VGA compatible controller
    //   Sub-class 0x02 = 3D controller (common for NVIDIA data center/compute GPUs)
    // Reference: PCI Code and ID Assignment Specification
    //   https://pcisig.com/pci-code-and-id-assignment-specification-agreement
    //   See section on base class 03h.
    const uint8_t base_class = static_cast<uint8_t>((pci_class >> 16) & 0xFF);
    const uint8_t sub_class = static_cast<uint8_t>((pci_class >> 8) & 0xFF);
    if (base_class != 0x03 || (sub_class != 0x00 && sub_class != 0x02)) {
      continue;
    }
 
    GpuPciPathInfo path_info{};
    path_info.path = device_path;
    path_info.pci_bus_id = device_path.filename().string();
    gpu_pci_paths.emplace_back(std::move(path_info));
  }
 
  gpu_pci_paths_out = std::move(gpu_pci_paths);
  return Status::OK();
}
 
Status GetGpuDeviceFromPci(const GpuPciPathInfo& path_info, OrtHardwareDevice& gpu_device_out) {
  OrtHardwareDevice gpu_device{};
  const auto& pci_path = path_info.path;
 
  // vendor id - directly under PCI device path
  uint16_t vendor_id{};
  ORT_RETURN_IF_ERROR(ReadValueFromFile(pci_path / "vendor", vendor_id));
  gpu_device.vendor_id = vendor_id;
 
  // device id - directly under PCI device path
  uint16_t device_id{};
  ORT_RETURN_IF_ERROR(ReadValueFromFile(pci_path / "device", device_id));
  gpu_device.device_id = device_id;
 
  // metadata
  if (const auto is_gpu_discrete = IsGpuDiscrete(vendor_id, device_id);
      is_gpu_discrete.has_value()) {
    gpu_device.metadata.Add("Discrete", (*is_gpu_discrete ? "1" : "0"));
  }
 
  if (!path_info.pci_bus_id.empty()) {
    gpu_device.metadata.Add("pci_bus_id", path_info.pci_bus_id);
  }
 
  gpu_device.type = OrtHardwareDeviceType_GPU;
 
  gpu_device_out = std::move(gpu_device);
  return Status::OK();
}
 
}  // namespace pci_device_discovery
 
namespace {
 
constexpr const char* kSysfsPciDevicesPath = "/sys/bus/pci/devices";
constexpr const char* kSysfsClassDrmPath = "/sys/class/drm";
constexpr const char* kSysfsAccelPath = "/sys/class/accel";
 
Status GetGpuDevices(std::vector<OrtHardwareDevice>& gpu_devices_out) {
  std::vector<drm_device_discovery::GpuSysfsPathInfo> gpu_sysfs_path_infos{};
  ORT_RETURN_IF_ERROR(drm_device_discovery::DetectGpuSysfsPaths(kSysfsClassDrmPath, gpu_sysfs_path_infos));
 
  std::vector<OrtHardwareDevice> gpu_devices{};
  gpu_devices.reserve(gpu_sysfs_path_infos.size());
 
  for (const auto& gpu_sysfs_path_info : gpu_sysfs_path_infos) {
    OrtHardwareDevice gpu_device{};
    if (auto status = drm_device_discovery::GetGpuDeviceFromSysfs(gpu_sysfs_path_info, gpu_device); !status.IsOK()) {
      LOGS_DEFAULT(WARNING) << MakeString("Failed to detect devices under ", gpu_sysfs_path_info.path, ": ", status.ErrorMessage());
      continue;
    }
    gpu_devices.emplace_back(std::move(gpu_device));
  }
 
  // If DRM-based detection found no GPUs, fall back to PCI bus scanning.
  // This handles containerized environments (e.g., AKS/Kubernetes) where the DRM
  // subsystem (nvidia-drm) may not be available but GPU PCI devices are still
  // exposed via /sys/bus/pci/devices/.
  if (gpu_devices.empty()) {
    LOGS_DEFAULT(VERBOSE) << "No GPUs found via /sys/class/drm. "
                          << "Falling back to PCI bus scanning via " << kSysfsPciDevicesPath << ".";
 
    std::vector<pci_device_discovery::GpuPciPathInfo> gpu_pci_path_infos{};
    ORT_RETURN_IF_ERROR(pci_device_discovery::DetectGpuPciPaths(kSysfsPciDevicesPath, gpu_pci_path_infos));
 
    gpu_devices.reserve(gpu_pci_path_infos.size());
 
    for (const auto& gpu_pci_path_info : gpu_pci_path_infos) {
      OrtHardwareDevice gpu_device{};
      if (auto status = pci_device_discovery::GetGpuDeviceFromPci(gpu_pci_path_info, gpu_device); !status.IsOK()) {
        LOGS_DEFAULT(WARNING) << MakeString("Failed to detect devices under ", gpu_pci_path_info.path, ": ", status.ErrorMessage());
        continue;
      }
      gpu_devices.emplace_back(std::move(gpu_device));
    }
  }
 
  gpu_devices_out = std::move(gpu_devices);
  return Status::OK();
}
 
}  // namespace
 
namespace npu_device_discovery {
 
Status DetectNpuSysfsPaths(const fs::path& sysfs_accel_path,
                           std::vector<NpuSysfsPathInfo>& npu_sysfs_paths_out) {
  std::error_code error_code{};
 
  const bool sysfs_accel_path_exists = fs::exists(sysfs_accel_path, error_code);
  ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, sysfs_accel_path, "Checking existence of accel sysfs path"));
 
  if (!sysfs_accel_path_exists) {
    npu_sysfs_paths_out = {};
    return Status::OK();
  }
 
  const auto detect_accel_path = [](const fs::path& sysfs_path, size_t& accel_idx) -> bool {
    const auto filename = sysfs_path.filename();
    const auto filename_str = std::string_view{filename.native()};
 
    // Look for a filename matching "accelN". N is a number.
    constexpr std::string_view prefix = "accel";
    if (filename_str.find(prefix) != 0) {
      return false;
    }
 
    size_t parsed_accel_idx{};
    if (!TryParseStringWithClassicLocale<size_t>(filename_str.substr(prefix.size()), parsed_accel_idx)) {
      return false;
    }
 
    accel_idx = parsed_accel_idx;
    return true;
  };
 
  std::vector<NpuSysfsPathInfo> npu_sysfs_paths{};
 
  auto dir_iterator = fs::directory_iterator{sysfs_accel_path, error_code};
  ORT_RETURN_IF_ERROR(ErrorCodeToStatus(error_code, sysfs_accel_path, "Iterating over accel sysfs devices"));
 
  for (const auto& dir_item : dir_iterator) {
    const auto& dir_item_path = dir_item.path();
 
    if (size_t accel_idx{}; detect_accel_path(dir_item_path, accel_idx)) {
      NpuSysfsPathInfo path_info{};
      path_info.accel_idx = accel_idx;
      path_info.path = dir_item_path;
      npu_sysfs_paths.emplace_back(std::move(path_info));
    }
  }
 
  npu_sysfs_paths_out = std::move(npu_sysfs_paths);
  return Status::OK();
}
 
Status GetNpuDeviceFromSysfs(const NpuSysfsPathInfo& path_info,
                             OrtHardwareDevice& npu_device_out) {
  OrtHardwareDevice npu_device{};
 
  const auto& sysfs_path = path_info.path;
 
  uint16_t vendor_id{};
  const auto vendor_id_path = sysfs_path / "device" / "vendor";
  ORT_RETURN_IF_ERROR(ReadValueFromFile(vendor_id_path, vendor_id));
  npu_device.vendor_id = vendor_id;
 
  uint16_t device_id{};
  const auto device_id_path = sysfs_path / "device" / "device";
  ORT_RETURN_IF_ERROR(ReadValueFromFile(device_id_path, device_id));
  npu_device.device_id = device_id;
 
  npu_device.metadata.Add("accel_idx", MakeString(path_info.accel_idx));
 
  std::optional<std::string> pci_bus_id;
  ORT_RETURN_IF_ERROR(GetPciBusId(sysfs_path, pci_bus_id));
  if (pci_bus_id) {
    npu_device.metadata.Add("pci_bus_id", std::move(*pci_bus_id));
  }
 
  npu_device.type = OrtHardwareDeviceType_NPU;
 
  npu_device_out = std::move(npu_device);
 
  return Status::OK();
}
 
}  // namespace npu_device_discovery
 
namespace {
 
Status GetNpuDevices(std::vector<OrtHardwareDevice>& npu_devices_out) {
  std::vector<npu_device_discovery::NpuSysfsPathInfo> npu_sysfs_path_infos{};
  ORT_RETURN_IF_ERROR(npu_device_discovery::DetectNpuSysfsPaths(kSysfsAccelPath, npu_sysfs_path_infos));
 
  std::vector<OrtHardwareDevice> npu_devices{};
  npu_devices.reserve(npu_sysfs_path_infos.size());
 
  for (const auto& npu_sysfs_path_info : npu_sysfs_path_infos) {
    OrtHardwareDevice npu_device{};
    if (auto status = npu_device_discovery::GetNpuDeviceFromSysfs(npu_sysfs_path_info, npu_device); !status.IsOK()) {
      LOGS_DEFAULT(WARNING) << MakeString("Failed to detect devices under ",
                                          npu_sysfs_path_info.path,
                                          ": ",
                                          status.ErrorMessage());
      continue;
    }
    npu_devices.emplace_back(std::move(npu_device));
  }
 
  npu_devices_out = std::move(npu_devices);
 
  return Status::OK();
}
}  // namespace
 
std::unordered_set<OrtHardwareDevice> DeviceDiscovery::DiscoverDevicesForPlatform() {
  std::unordered_set<OrtHardwareDevice> devices;
 
  // get CPU devices
  devices.emplace(GetCpuDeviceFromCPUIDInfo());
 
  // get GPU devices
  {
    std::vector<OrtHardwareDevice> gpu_devices{};
    Status gpu_device_discovery_status = GetGpuDevices(gpu_devices);
    if (gpu_device_discovery_status.IsOK()) {
      devices.insert(std::make_move_iterator(gpu_devices.begin()),
                     std::make_move_iterator(gpu_devices.end()));
    } else {
      LOGS_DEFAULT(WARNING) << "GPU device discovery failed: " << gpu_device_discovery_status.ErrorMessage();
    }
  }
 
  // get NPU devices
  {
    std::vector<OrtHardwareDevice> npu_devices{};
    Status npu_device_discovery_status = GetNpuDevices(npu_devices);
    if (npu_device_discovery_status.IsOK()) {
      devices.insert(std::make_move_iterator(npu_devices.begin()),
                     std::make_move_iterator(npu_devices.end()));
    } else {
      LOGS_DEFAULT(WARNING) << "NPU device discovery failed: " << npu_device_discovery_status.ErrorMessage();
    }
  }
 
  return devices;
}
}  // namespace onnxruntime