|
| 1 | +import csv |
1 | 2 | import logging |
2 | 3 | import os |
3 | 4 | import sys |
|
26 | 27 |
|
27 | 28 | def resolve_container_path(container_path): |
28 | 29 | container_path = os.path.realpath(container_path) |
29 | | - proc_cgroup = '/proc/self/cgroup' |
| 30 | + mountinfo = '/proc/self/mountinfo' |
30 | 31 | try: |
31 | | - with open(proc_cgroup) as f: |
32 | | - log.info('Found %s', proc_cgroup) |
33 | | - # Entries in /proc/self/cgroup look like this (note the nesting): |
34 | | - # 11:name=systemd:/docker/82c1bd2…23b5bcf/docker/6547bce…60ca5a7 |
35 | | - prefix, container_id = next(f).strip().split(':')[2].split('/')[-2:] |
| 32 | + with open(mountinfo) as f: |
| 33 | + log.info('Found %s', mountinfo) |
| 34 | + # Entries in /proc/self/mountinfo look like this: |
| 35 | + # 752 744 259:2 /docker/containers/dc61d93…ID…/hosts … |
| 36 | + prefix = '/docker/containers' |
| 37 | + contents = csv.reader(f, delimiter=' ') |
| 38 | + for line in contents: |
| 39 | + path = line[3] |
| 40 | + if path.startswith(prefix): |
| 41 | + log.info('Extracting the container ID from %s', path) |
| 42 | + parts = path.rsplit('/', maxsplit=2)[:-1] |
| 43 | + assert len(parts) == 2 and parts[0] == prefix, parts |
| 44 | + container_id = parts[1] |
36 | 45 | except FileNotFoundError: |
37 | 46 | log.info('Did not find %s', proc_cgroup) |
38 | 47 | else: |
39 | | - if prefix == 'docker': |
40 | | - api = docker.client.from_env().api |
41 | | - for mount in api.inspect_container(container_id)['Mounts']: |
42 | | - if container_path.startswith(mount['Destination']): |
43 | | - tail = os.path.relpath(container_path, mount['Destination']) |
44 | | - host_path = os.path.normpath(os.path.join(mount['Source'], tail)) |
45 | | - log.info('Resolved %s to %s', container_path, host_path) |
46 | | - return host_path |
| 48 | + api = docker.client.from_env().api |
| 49 | + for mount in api.inspect_container(container_id)['Mounts']: |
| 50 | + if container_path.startswith(mount['Destination']): |
| 51 | + tail = os.path.relpath(container_path, mount['Destination']) |
| 52 | + host_path = os.path.normpath(os.path.join(mount['Source'], tail)) |
| 53 | + log.info('Resolved %s to %s', container_path, host_path) |
| 54 | + return host_path |
47 | 55 | log.error('Failed to resolve container path %s', container_path) |
48 | 56 | return None |
49 | 57 |
|
|
0 commit comments