Created
August 10, 2021 12:13
-
-
Save Stfort52/b9aa0e6465b97a2491f28426b9426e25 to your computer and use it in GitHub Desktop.
Script to find out which container is running the process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/python3 | |
| import re | |
| import sys | |
| import docker | |
| ID_PATTERN = re.compile("[0-9a-f]{12}") | |
| DOCKER_CONTAINERS = docker.from_env().containers | |
| def get_ppid(pid: int) -> int: | |
| try: | |
| with open(f"/proc/{pid}/status") as f: | |
| for line in f: | |
| key, value = line.strip().split(":")[:2] | |
| if key == "PPid": | |
| return int(value) | |
| except FileNotFoundError: | |
| print(f"process {pid} does not exist") | |
| exit(1) | |
| def get_cmdline(pid: int) -> str: | |
| try: | |
| with open(f"/proc/{pid}/cmdline") as f: | |
| return f.read() | |
| except FileNotFoundError: | |
| print(f"process {pid} does not exist") | |
| exit(1) | |
| def find_root(pid: int) -> int: | |
| if pid == 1: | |
| return 1 | |
| else: | |
| if "containerd-shim" in get_cmdline(pid): | |
| return pid | |
| else: | |
| return find_root(get_ppid(pid)) | |
| def root_info(pid: int) -> None: | |
| root = find_root(pid) | |
| if root == 1: | |
| print(f"process {pid} is not running in docker") | |
| else: | |
| cid = ID_PATTERN.search(get_cmdline(root)).group(0) | |
| name = DOCKER_CONTAINERS.get(cid).attrs['Name'] | |
| print(f"process {pid} is running in docker {cid}:{name}") | |
| if __name__ == "__main__": | |
| if len(sys.argv) > 1: | |
| for pid in sys.argv[1:]: | |
| root_info(int(pid)) | |
| else: | |
| root_info(int(input("pid\n>>> "))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment