Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 9 additions & 0 deletions install/test/src/test_resource_detectors.cc
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include <opentelemetry/resource_detectors/container_detector.h>
#include <opentelemetry/resource_detectors/container_detector_builder.h>
#include <opentelemetry/resource_detectors/env_entity_detector.h>
#include <opentelemetry/resource_detectors/host_detector.h>
#include <opentelemetry/resource_detectors/process_detector.h>
#include <opentelemetry/resource_detectors/process_detector_builder.h>
#include <memory>
Expand All @@ -26,6 +27,14 @@ TEST(ResourceDetectorsInstall, EnvEntityDetector)
ASSERT_NO_THROW(auto resource = detector->Detect());
}

TEST(ResourceDetectorsInstall, HostResourceDetector)
{
std::unique_ptr<opentelemetry::sdk::resource::ResourceDetector> detector =
std::make_unique<opentelemetry::resource_detector::HostResourceDetector>();
ASSERT_TRUE(detector != nullptr);
ASSERT_NO_THROW(auto resource = detector->Detect());
}

TEST(ResourceDetectorsInstall, ProcessResourceDetector)
{
std::unique_ptr<opentelemetry::sdk::resource::ResourceDetector> detector =
Expand Down
2 changes: 2 additions & 0 deletions resource_detectors/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -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",
],
Expand Down
8 changes: 6 additions & 2 deletions resource_detectors/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

#pragma once

#include <string>

#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
Original file line number Diff line number Diff line change
@@ -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
65 changes: 65 additions & 0 deletions resource_detectors/src/host_detector.cc
Original file line number Diff line number Diff line change
@@ -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 <exception>
#include <ostream>
#include <string>
#include <utility>

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
152 changes: 152 additions & 0 deletions resource_detectors/src/host_detector_utils.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

#include "opentelemetry/resource_detectors/detail/host_detector_utils.h"

#include <fstream>
#include <string>

#ifdef _MSC_VER
// clang-format off
# include <windows.h>
# pragma comment(lib, "advapi32.lib")
// clang-format on
#elif defined(__APPLE__)
# include <unistd.h>
# include <uuid/uuid.h>
# include <ctime>
#else
# include <unistd.h>
#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<int>(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<int>(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
1 change: 1 addition & 0 deletions resource_detectors/test/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
Expand Down
4 changes: 2 additions & 2 deletions resource_detectors/test/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading