Skip to content

Commit 0d8c43b

Browse files
committed
Fixes container detector for systemd & cgroupv1 with Docker
1 parent b8018c5 commit 0d8c43b

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

resource/opentelemetry-resource-detector-container/src/opentelemetry/resource/detector/container/__init__.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import re
1516
from logging import getLogger
1617

1718
from opentelemetry.sdk.resources import Resource, ResourceDetector
@@ -31,9 +32,14 @@ def _get_container_id_v1():
3132
) as container_info_file:
3233
for raw_line in container_info_file.readlines():
3334
line = raw_line.strip()
34-
if len(line) > _CONTAINER_ID_LENGTH:
35-
container_id = line[-_CONTAINER_ID_LENGTH:]
35+
36+
match = re.search(
37+
r"^.*/(?:.*[-:])?([0-9a-f]+)(?:\.|\s*$)", line
38+
)
39+
if match is not None:
40+
container_id = match.group(1)
3641
break
42+
3743
except FileNotFoundError as exception:
3844
logger.warning("Failed to get container id. Exception: %s", exception)
3945
return container_id

resource/opentelemetry-resource-detector-container/tests/test_container.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,20 @@ def test_container_id_detect_from_cgroup_file(self, mock_cgroup_file):
5151
actual.attributes.copy(), MockContainerResourceAttributes
5252
)
5353

54+
@patch(
55+
"builtins.open",
56+
new_callable=mock_open,
57+
read_data=f"""0::/system.slice/docker-{MockContainerResourceAttributes[ResourceAttributes.CONTAINER_ID]}.scope
58+
""",
59+
)
60+
def test_container_id_detect_from_cgroup_file_with_suffix(
61+
self, mock_cgroup_file
62+
):
63+
actual = ContainerResourceDetector().detect()
64+
self.assertDictEqual(
65+
actual.attributes.copy(), MockContainerResourceAttributes
66+
)
67+
5468
@patch(
5569
"opentelemetry.resource.detector.container._get_container_id_v1",
5670
return_value=None,

0 commit comments

Comments
 (0)