44#include < cstdint>
55#include < fstream>
66#include < iostream>
7+ #include < memory>
78#include < regex>
89
910// clang-format off
4546#endif
4647// clang-format on
4748
49+ #include < datadog/logger.h>
50+
4851namespace datadog {
4952namespace tracing {
5053namespace {
@@ -292,10 +295,18 @@ Expected<InMemoryFile> InMemoryFile::make(StringView) {
292295namespace container {
293296namespace {
294297#if defined(__linux__) || defined(__unix__)
298+ // / Magic numbers from linux/magic.h:
299+ // / <https://github.com/torvalds/linux/blob/ca91b9500108d4cf083a635c2e11c884d5dd20ea/include/uapi/linux/magic.h#L71>
300+ constexpr uint64_t CGROUP_SUPER_MAGIC = 0x27e0eb ;
301+ constexpr uint64_t CGROUP2_SUPER_MAGIC = 0x63677270 ;
302+
295303// / Magic number from linux/proc_ns.h:
296304// / <https://github.com/torvalds/linux/blob/5859a2b1991101d6b978f3feb5325dad39421f29/include/linux/proc_ns.h#L41-L49>
297305constexpr ino_t HOST_CGROUP_NAMESPACE_INODE = 0xeffffffb ;
298306
307+ // / Represents the cgroup version of the current process.
308+ enum class Cgroup : char { v1, v2 };
309+
299310Optional<ino_t > get_inode (std::string_view path) {
300311 struct stat buf;
301312 if (stat (path.data (), &buf) != 0 ) {
@@ -318,6 +329,25 @@ bool is_running_in_host_namespace() {
318329 return false ;
319330}
320331
332+ Optional<Cgroup> get_cgroup_version (const std::shared_ptr<tracing::Logger>& logger) {
333+ struct statfs buf;
334+
335+ if (statfs (" /sys/fs/cgroup" , &buf) != 0 ) {
336+ logger->log_error (" Failed to statfs /sys/fs/cgroup" );
337+ return nullopt ;
338+ }
339+
340+ logger->log_error ([&](auto & stream) {
341+ stream << " statfs /sys/fs/cgroup: f_type = " << buf.f_type ;
342+ });
343+ if (buf.f_type == CGROUP_SUPER_MAGIC)
344+ return Cgroup::v1;
345+ else if (buf.f_type == CGROUP2_SUPER_MAGIC)
346+ return Cgroup::v2;
347+
348+ return nullopt ;
349+ }
350+
321351Optional<std::string> find_container_id_from_cgroup () {
322352 auto cgroup_fd = std::ifstream (" /proc/self/cgroup" , std::ios::in);
323353 if (!cgroup_fd.is_open ()) {
@@ -355,8 +385,11 @@ Optional<std::string> find_container_id(std::istream& source) {
355385 return nullopt ;
356386}
357387
358- Optional<ContainerID> get_id () {
388+ Optional<ContainerID> get_id (const std::shared_ptr<tracing::Logger>& logger ) {
359389#if defined(__linux__) || defined(__unix__)
390+ auto maybe_cgroup = get_cgroup_version (logger);
391+ if (!maybe_cgroup) return nullopt ;
392+
360393 // Determine the container ID or inode
361394 ContainerID id;
362395 if (auto maybe_id = find_container_id_from_cgroup ()) {
0 commit comments