diff --git a/CHANGELOG.md b/CHANGELOG.md index a7935e0456..45b96f4dd7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,8 @@ Increment the: ## [Unreleased] +* [RESOURCE DETECTOR] Add the host resource detector + [#4413](https://github.com/open-telemetry/opentelemetry-cpp/issues/4413) * [CONFIGURATION] Add configuration builders for the container and process resource detectors [#4412](https://github.com/open-telemetry/opentelemetry-cpp/issues/4412) diff --git a/install/test/src/test_resource_detectors.cc b/install/test/src/test_resource_detectors.cc index 4804bfbd14..d2c177e875 100644 --- a/install/test/src/test_resource_detectors.cc +++ b/install/test/src/test_resource_detectors.cc @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -26,6 +27,14 @@ TEST(ResourceDetectorsInstall, EnvEntityDetector) ASSERT_NO_THROW(auto resource = detector->Detect()); } +TEST(ResourceDetectorsInstall, HostResourceDetector) +{ + std::unique_ptr detector = + std::make_unique(); + ASSERT_TRUE(detector != nullptr); + ASSERT_NO_THROW(auto resource = detector->Detect()); +} + TEST(ResourceDetectorsInstall, ProcessResourceDetector) { std::unique_ptr detector = diff --git a/resource_detectors/BUILD b/resource_detectors/BUILD index 0b859f3342..9b21a8c092 100644 --- a/resource_detectors/BUILD +++ b/resource_detectors/BUILD @@ -17,6 +17,8 @@ cc_library( "src/container_detector.cc", "src/container_detector_utils.cc", "src/env_entity_detector.cc", + "src/host_detector.cc", + "src/host_detector_utils.cc", "src/process_detector.cc", "src/process_detector_utils.cc", ], diff --git a/resource_detectors/CMakeLists.txt b/resource_detectors/CMakeLists.txt index 22147de68e..07881df435 100644 --- a/resource_detectors/CMakeLists.txt +++ b/resource_detectors/CMakeLists.txt @@ -3,8 +3,12 @@ add_library( opentelemetry_resource_detectors - src/container_detector_utils.cc src/container_detector.cc - src/env_entity_detector.cc src/process_detector.cc + src/container_detector_utils.cc + src/container_detector.cc + src/env_entity_detector.cc + src/host_detector.cc + src/host_detector_utils.cc + src/process_detector.cc src/process_detector_utils.cc) set_target_properties(opentelemetry_resource_detectors diff --git a/resource_detectors/include/opentelemetry/resource_detectors/detail/host_detector_utils.h b/resource_detectors/include/opentelemetry/resource_detectors/detail/host_detector_utils.h new file mode 100644 index 0000000000..2aa1102633 --- /dev/null +++ b/resource_detectors/include/opentelemetry/resource_detectors/detail/host_detector_utils.h @@ -0,0 +1,55 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include + +#include "opentelemetry/version.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace resource_detector +{ +namespace detail +{ + +/** + * Retrieves the hostname. + * Platform-specific behavior: + * - Windows: Uses GetComputerNameExW() with ComputerNameDnsHostname. + * - Linux/MacOS: Uses gethostname(). + * @return the hostname or an empty string on error + */ +std::string GetHostName(); + +/** + * Returns the host.arch semantic convention value for the architecture this + * binary was compiled for, or an empty string when the architecture is not one + * of the values the semantic conventions enumerate. + */ +std::string GetHostArch(); + +/** + * Retrieves a unique identifier for the host. + * Platform-specific behavior: + * - Windows: Reads the MachineGuid value from the + * HKLM\SOFTWARE\Microsoft\Cryptography registry key. + * - MacOS: Uses gethostuuid(). + * - Linux/Unix: Reads /etc/machine-id, falling back to + * /var/lib/dbus/machine-id. + * @return the host id or an empty string when no source is available + */ +std::string GetHostId(); + +/** + * Reads a machine id from the first line of the given file, trimmed of + * surrounding whitespace. This function is the Linux implementation behind + * GetHostId() and is exposed for testability. + * @param file_path path of the machine id file + * @return the machine id or an empty string on error + */ +std::string GetHostIdFromFile(const char *file_path); + +} // namespace detail +} // namespace resource_detector +OPENTELEMETRY_END_NAMESPACE diff --git a/resource_detectors/include/opentelemetry/resource_detectors/host_detector.h b/resource_detectors/include/opentelemetry/resource_detectors/host_detector.h new file mode 100644 index 0000000000..9fa8b15c73 --- /dev/null +++ b/resource_detectors/include/opentelemetry/resource_detectors/host_detector.h @@ -0,0 +1,37 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include "opentelemetry/sdk/resource/resource_detector.h" +#include "opentelemetry/version.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace resource_detector +{ + +/** + * HostResourceDetector to detect resource attributes describing the host the process + * runs on. It sets host.name, host.arch and host.id following the OpenTelemetry + * semantic conventions. + * + * Platform specific behavior and limitations: + * - host.name is read with gethostname() on Linux and MacOS and with + * GetComputerNameExW() on Windows. + * - host.id is read from /etc/machine-id (falling back to /var/lib/dbus/machine-id) + * on Linux, from gethostuuid() on MacOS and from the + * HKLM\SOFTWARE\Microsoft\Cryptography\MachineGuid registry value on Windows. + * The attribute is omitted when no source is available, for example in Linux + * containers without a machine id. + * - host.arch is derived at compile time from the architecture the SDK was built + * for and is omitted when that architecture has no host.arch value in the + * semantic conventions. + */ +class HostResourceDetector : public opentelemetry::sdk::resource::ResourceDetector +{ +public: + opentelemetry::sdk::resource::Resource Detect() noexcept override; +}; + +} // namespace resource_detector +OPENTELEMETRY_END_NAMESPACE diff --git a/resource_detectors/src/host_detector.cc b/resource_detectors/src/host_detector.cc new file mode 100644 index 0000000000..f71898cb8d --- /dev/null +++ b/resource_detectors/src/host_detector.cc @@ -0,0 +1,65 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#include "opentelemetry/resource_detectors/host_detector.h" +#include "opentelemetry/nostd/variant.h" +#include "opentelemetry/resource_detectors/detail/host_detector_utils.h" +#include "opentelemetry/sdk/common/global_log_handler.h" +#include "opentelemetry/sdk/resource/resource.h" +#include "opentelemetry/sdk/resource/resource_detector.h" +#include "opentelemetry/semconv/incubating/host_attributes.h" +#include "opentelemetry/semconv/schema_url.h" +#include "opentelemetry/version.h" + +#include +#include +#include +#include + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace resource_detector +{ + +opentelemetry::sdk::resource::Resource HostResourceDetector::Detect() noexcept +{ + opentelemetry::sdk::resource::ResourceAttributes attributes; + + try + { + std::string host_name = opentelemetry::resource_detector::detail::GetHostName(); + if (!host_name.empty()) + { + attributes[semconv::host::kHostName] = std::move(host_name); + } + } + catch (const std::exception &ex) + { + OTEL_INTERNAL_LOG_ERROR("[Host Resource Detector] " << "Error extracting the host name: " + << ex.what()); + } + + std::string host_arch = opentelemetry::resource_detector::detail::GetHostArch(); + if (!host_arch.empty()) + { + attributes[semconv::host::kHostArch] = std::move(host_arch); + } + + try + { + std::string host_id = opentelemetry::resource_detector::detail::GetHostId(); + if (!host_id.empty()) + { + attributes[semconv::host::kHostId] = std::move(host_id); + } + } + catch (const std::exception &ex) + { + OTEL_INTERNAL_LOG_ERROR("[Host Resource Detector] " << "Error extracting the host id: " + << ex.what()); + } + + return ResourceDetector::Create(attributes, semconv::kSchemaUrl); +} + +} // namespace resource_detector +OPENTELEMETRY_END_NAMESPACE diff --git a/resource_detectors/src/host_detector_utils.cc b/resource_detectors/src/host_detector_utils.cc new file mode 100644 index 0000000000..bed06908c5 --- /dev/null +++ b/resource_detectors/src/host_detector_utils.cc @@ -0,0 +1,152 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#include "opentelemetry/resource_detectors/detail/host_detector_utils.h" + +#include +#include + +#ifdef _MSC_VER +// clang-format off +# include +# pragma comment(lib, "advapi32.lib") +// clang-format on +#elif defined(__APPLE__) +# include +# include +# include +#else +# include +#endif + +#include "opentelemetry/semconv/incubating/host_attributes.h" +#include "opentelemetry/version.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace resource_detector +{ +namespace detail +{ + +#if !defined(_MSC_VER) && !defined(__APPLE__) +constexpr const char *kMachineIdPath = "/etc/machine-id"; +constexpr const char *kDbusMachineIdPath = "/var/lib/dbus/machine-id"; +#endif + +std::string GetHostName() +{ +#ifdef _MSC_VER + DWORD size = 0; + GetComputerNameExW(ComputerNameDnsHostname, nullptr, &size); + if (size == 0) + { + return std::string(); + } + + std::wstring wname(size, L'\0'); + if (!GetComputerNameExW(ComputerNameDnsHostname, &wname[0], &size)) + { + return std::string(); + } + + // Convert UTF-16 to UTF-8 + int size_needed = WideCharToMultiByte(CP_UTF8, 0, wname.c_str(), static_cast(size), nullptr, + 0, nullptr, nullptr); + if (size_needed <= 0) + { + return std::string(); + } + std::string utf8_name(size_needed, 0); + WideCharToMultiByte(CP_UTF8, 0, wname.c_str(), static_cast(size), &utf8_name[0], size_needed, + nullptr, nullptr); + return utf8_name; +#else + char buffer[256]; + if (gethostname(buffer, sizeof(buffer)) != 0) + { + return std::string(); + } + buffer[sizeof(buffer) - 1] = '\0'; + return std::string(buffer); +#endif +} + +std::string GetHostArch() +{ +#if defined(_M_AMD64) || defined(__x86_64__) + return semconv::host::HostArchValues::kAmd64; +#elif defined(_M_ARM64) || defined(__aarch64__) + return semconv::host::HostArchValues::kArm64; +#elif defined(_M_ARM) || defined(__arm__) + return semconv::host::HostArchValues::kArm32; +#elif defined(_M_IX86) || defined(__i386__) + return semconv::host::HostArchValues::kX86; +#elif defined(__powerpc64__) + return semconv::host::HostArchValues::kPpc64; +#elif defined(__powerpc__) + return semconv::host::HostArchValues::kPpc32; +#elif defined(__s390x__) + return semconv::host::HostArchValues::kS390x; +#elif defined(__ia64__) + return semconv::host::HostArchValues::kIa64; +#else + return std::string(); +#endif +} + +std::string GetHostIdFromFile(const char *file_path) +{ + std::ifstream file(file_path); + if (!file.is_open()) + { + return std::string(); + } + + std::string line; + std::getline(file, line); + + const auto end = line.find_last_not_of(" \t\n\r"); + if (end == std::string::npos) + { + return std::string(); + } + const auto start = line.find_first_not_of(" \t\n\r"); + return line.substr(start, end - start + 1); +} + +std::string GetHostId() +{ +#ifdef _MSC_VER + char buffer[64]; + DWORD size = sizeof(buffer); + LSTATUS status = RegGetValueA(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Cryptography", + "MachineGuid", RRF_RT_REG_SZ, nullptr, buffer, &size); + if (status != ERROR_SUCCESS || size <= 1) + { + return std::string(); + } + // size includes the terminating null character + return std::string(buffer, size - 1); +#elif defined(__APPLE__) + uuid_t uuid; + struct timespec timeout = {1, 0}; + if (gethostuuid(uuid, &timeout) != 0) + { + return std::string(); + } + char uuid_str[37]; + uuid_unparse_lower(uuid, uuid_str); + return std::string(uuid_str); +#else + std::string machine_id = GetHostIdFromFile(kMachineIdPath); + if (machine_id.empty()) + { + machine_id = GetHostIdFromFile(kDbusMachineIdPath); + } + return machine_id; +#endif +} + +} // namespace detail +} // namespace resource_detector +OPENTELEMETRY_END_NAMESPACE diff --git a/resource_detectors/test/BUILD b/resource_detectors/test/BUILD index a212bcdac6..761a4b3e73 100644 --- a/resource_detectors/test/BUILD +++ b/resource_detectors/test/BUILD @@ -8,6 +8,7 @@ cc_test( srcs = [ "container_detector_test.cc", "env_entity_detector_test.cc", + "host_detector_test.cc", "process_detector_test.cc", ], tags = ["test"], diff --git a/resource_detectors/test/CMakeLists.txt b/resource_detectors/test/CMakeLists.txt index f7dda21a25..c2167055cd 100644 --- a/resource_detectors/test/CMakeLists.txt +++ b/resource_detectors/test/CMakeLists.txt @@ -2,8 +2,8 @@ # SPDX-License-Identifier: Apache-2.0 add_executable( - resource_detector_test container_detector_test.cc process_detector_test.cc - env_entity_detector_test.cc) + resource_detector_test container_detector_test.cc host_detector_test.cc + process_detector_test.cc env_entity_detector_test.cc) # Link the required dependencies target_link_libraries( diff --git a/resource_detectors/test/host_detector_test.cc b/resource_detectors/test/host_detector_test.cc new file mode 100644 index 0000000000..05f0901cb4 --- /dev/null +++ b/resource_detectors/test/host_detector_test.cc @@ -0,0 +1,102 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include + +#include "opentelemetry/nostd/variant.h" +#include "opentelemetry/resource_detectors/detail/host_detector_utils.h" +#include "opentelemetry/resource_detectors/host_detector.h" +#include "opentelemetry/sdk/resource/resource.h" +#include "opentelemetry/semconv/incubating/host_attributes.h" +#include "opentelemetry/semconv/schema_url.h" + +namespace semconv = opentelemetry::semconv; + +TEST(HostDetectorUtilsTest, GetHostName) +{ + std::string host_name = opentelemetry::resource_detector::detail::GetHostName(); + EXPECT_FALSE(host_name.empty()); +} + +TEST(HostDetectorUtilsTest, GetHostArch) +{ + std::string arch = opentelemetry::resource_detector::detail::GetHostArch(); + +#if defined(_M_AMD64) || defined(__x86_64__) + EXPECT_EQ(arch, std::string{semconv::host::HostArchValues::kAmd64}); +#elif defined(_M_ARM64) || defined(__aarch64__) + EXPECT_EQ(arch, std::string{semconv::host::HostArchValues::kArm64}); +#endif + + if (!arch.empty()) + { + const char *known_values[] = { + semconv::host::HostArchValues::kAmd64, semconv::host::HostArchValues::kArm32, + semconv::host::HostArchValues::kArm64, semconv::host::HostArchValues::kIa64, + semconv::host::HostArchValues::kPpc32, semconv::host::HostArchValues::kPpc64, + semconv::host::HostArchValues::kS390x, semconv::host::HostArchValues::kX86}; + bool found = false; + for (const char *value : known_values) + { + if (arch == value) + { + found = true; + break; + } + } + EXPECT_TRUE(found); + } +} + +TEST(HostDetectorUtilsTest, GetHostIdFromFile) +{ + const char *filename = "test_machine_id.txt"; + + { + std::ofstream outfile(filename); + outfile << "0f81dc7e29c2446fb0f232fe8f42e027\n"; + } + + std::string host_id = opentelemetry::resource_detector::detail::GetHostIdFromFile(filename); + EXPECT_EQ(host_id, std::string{"0f81dc7e29c2446fb0f232fe8f42e027"}); + + std::remove(filename); +} + +TEST(HostDetectorUtilsTest, GetHostIdFromEmptyFile) +{ + const char *filename = "test_empty_machine_id.txt"; + + { + std::ofstream outfile(filename); + } + + std::string host_id = opentelemetry::resource_detector::detail::GetHostIdFromFile(filename); + EXPECT_TRUE(host_id.empty()); + + std::remove(filename); +} + +TEST(HostDetectorUtilsTest, GetHostIdFromMissingFile) +{ + std::string host_id = + opentelemetry::resource_detector::detail::GetHostIdFromFile("test_missing_machine_id.txt"); + EXPECT_TRUE(host_id.empty()); +} + +TEST(HostDetectorTest, DetectSetsHostName) +{ + opentelemetry::resource_detector::HostResourceDetector detector; + auto resource = detector.Detect(); + const auto &attrs = resource.GetAttributes(); + + auto it = attrs.find(semconv::host::kHostName); + ASSERT_NE(it, attrs.end()); + EXPECT_FALSE(opentelemetry::nostd::get(it->second).empty()); + + EXPECT_EQ(resource.GetSchemaURL(), std::string{semconv::kSchemaUrl}); +}