@@ -302,7 +302,7 @@ namespace {
302302
303303// / Magic number from linux/proc_ns.h:
304304// / <https://github.com/torvalds/linux/blob/5859a2b1991101d6b978f3feb5325dad39421f29/include/linux/proc_ns.h#L41-L49>
305- // constexpr ino_t HOST_CGROUP_NAMESPACE_INODE = 0xeffffffb;
305+ constexpr ino_t HOST_CGROUP_NAMESPACE_INODE = 0xeffffffb ;
306306
307307// / Represents the cgroup version of the current process.
308308// enum class Cgroup : char { v1, v2 };
@@ -316,6 +316,19 @@ Optional<ino_t> get_inode(std::string_view path) {
316316 return buf.st_ino ;
317317}
318318
319+ // Host namespace inode number are hardcoded, which allows for dectection of
320+ // whether the binary is running in host or not. However, it does not work when
321+ // running in a Docker in Docker environment.
322+ bool is_running_in_host_namespace () {
323+ // linux procfs file that represents the cgroup namespace of the current
324+ // process.
325+ if (auto inode = get_inode (" /proc/self/ns/cgroup" )) {
326+ return *inode == HOST_CGROUP_NAMESPACE_INODE;
327+ }
328+
329+ return false ;
330+ }
331+
319332Optional<std::string> find_container_id_from_cgroup (
320333 const std::shared_ptr<tracing::Logger>& logger) {
321334 auto cgroup_fd = std::ifstream (" /proc/self/cgroup" , std::ios::in);
@@ -361,18 +374,18 @@ Optional<std::string> find_container_id(std::istream& source,
361374
362375Optional<ContainerID> get_id (const std::shared_ptr<tracing::Logger>& logger) {
363376#if defined(__linux__) || defined(__unix__)
364- // Comment out the host namespace check, following the algorithm from other tracers.
365- // Also don't get the cgroup version upfront, following the algorithm from other tracers.
366- // This should allow us to detect containers running in Docker Desktop.
367-
377+ // Determine the container ID or inode
368378 ContainerID id;
369379 if (auto maybe_id = find_container_id_from_cgroup (logger)) {
370380 id.value = *maybe_id;
371381 id.type = ContainerID::Type::container_id;
372- } else if (auto maybe_inode = get_inode ( " /sys/fs/cgroup " )) {
382+ } else if (! is_running_in_host_namespace ( )) {
373383 // NOTE(@dmehala): failed to find the container ID, try getting the cgroup inode.
374- id.type = ContainerID::Type::cgroup_inode;
375- id.value = std::to_string (*maybe_inode);
384+ auto maybe_inode = get_inode (" /sys/fs/cgroup" );
385+ if (maybe_inode) {
386+ id.type = ContainerID::Type::cgroup_inode;
387+ id.value = std::to_string (*maybe_inode);
388+ }
376389 }
377390
378391 return id;
0 commit comments