From 7869558646077cedaf53c75e46449432ce8a9c56 Mon Sep 17 00:00:00 2001 From: Juan Pedro Bretti Mandarano Date: Wed, 1 Feb 2023 16:55:44 +0100 Subject: [PATCH] add docker support * Add an id for Docker containers Usual Linux images for Docker containers, does not have the originally listed files. Following the conversation at https://github.com/denisbrodbeck/machineid/issues/10, I am including the following: Because `/proc/self/cgroup` seams to not be working on same Docker versions, I am also including `/proc/self/mountinfo`. Tested on `Python 3.11` running on `Debian GNU/Linux 11 (bullseye)` inside a Docker. * Included "if 'docker' in mountinfo" for "linux" Following your review, I made some updates on the patch. * Update __init__.py * Fixed the indentation to 2. * Checked on a Docker container the `if 'docker' in cgroup:` works when the `docker` is not found. Same test with `mountinfo`. * When the full code does not find an ID raises the following: `Python 3.11.0 (main, Nov 15 2022, 19:58:01) [GCC 10.2.1 20210110] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import machineid >>> print(machineid.id()) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.11/site-packages/machineid/__init__.py", line 90, in id raise Exception('failed to obtain id on platform {}'.format(platform)) Exception: failed to obtain id on platform linux` * Update __init__.py Check if `cgroup` and `mountinfo` are not None, before checking if `docker` is inside the file. To not rise a possible error when is trying to check `if 'docker' in None` (when the file does not exist). --- machineid/__init__.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/machineid/__init__.py b/machineid/__init__.py index bf6d7be..3928569 100644 --- a/machineid/__init__.py +++ b/machineid/__init__.py @@ -74,6 +74,16 @@ def id() -> str: id = __read__('/var/lib/dbus/machine-id') if not id: id = __read__('/etc/machine-id') + if not id: + cgroup = __read__('/proc/self/cgroup') + if cgroup: + if 'docker' in cgroup: + id = __exec__('head -1 /proc/self/cgroup | cut -d/ -f3') + if not id: + mountinfo = __read__('/proc/self/mountinfo') + if mountinfo: + if 'docker' in mountinfo: + id = __exec__("grep 'systemd' /proc/self/mountinfo | cut -d/ -f3") if platform.startswith('openbsd') or platform.startswith('freebsd'): id = __read__('/etc/hostid')