Fixes container detector for systemd & cgroupv1 with Docker (#3429)

* Fixes container detector for systemd & cgroupv1 with Docker

* Update CHANGELOG

---------

Co-authored-by: Emídio Neto <9735060+emdneto@users.noreply.github.com>
Co-authored-by: Riccardo Magliocchetti <riccardo.magliocchetti@gmail.com>
This commit is contained in:
Sean Hood
2025-06-03 16:27:09 +01:00
committed by GitHub
parent ccf9cabeee
commit 8f7bab5337
3 changed files with 24 additions and 2 deletions

View File

@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import re
from logging import getLogger
from opentelemetry.sdk.resources import Resource, ResourceDetector
@ -31,9 +32,14 @@ def _get_container_id_v1():
) as container_info_file:
for raw_line in container_info_file.readlines():
line = raw_line.strip()
if len(line) > _CONTAINER_ID_LENGTH:
container_id = line[-_CONTAINER_ID_LENGTH:]
match = re.search(
r"^.*/(?:.*[-:])?([0-9a-f]+)(?:\.|\s*$)", line
)
if match is not None:
container_id = match.group(1)
break
except FileNotFoundError as exception:
logger.warning("Failed to get container id. Exception: %s", exception)
return container_id

View File

@ -51,6 +51,20 @@ class ContainerResourceDetectorTest(TestBase):
actual.attributes.copy(), MockContainerResourceAttributes
)
@patch(
"builtins.open",
new_callable=mock_open,
read_data=f"""0::/system.slice/docker-{MockContainerResourceAttributes[ResourceAttributes.CONTAINER_ID]}.scope
""",
)
def test_container_id_detect_from_cgroup_file_with_suffix(
self, mock_cgroup_file
):
actual = ContainerResourceDetector().detect()
self.assertDictEqual(
actual.attributes.copy(), MockContainerResourceAttributes
)
@patch(
"opentelemetry.resource.detector.container._get_container_id_v1",
return_value=None,