Coverage for lintro / utils / environment / container_detection.py: 36%

22 statements  

« prev     ^ index     » next       coverage.py v7.13.0, created at 2026-04-03 18:53 +0000

1"""Container environment detection for Docker, Podman, and similar runtimes.""" 

2 

3from __future__ import annotations 

4 

5import functools 

6import os 

7from pathlib import Path 

8 

9 

10@functools.lru_cache(maxsize=1) 

11def is_container_environment() -> bool: 

12 """Detect if running inside a Docker/container environment. 

13 

14 Checks multiple indicators: 

15 1. ``/.dockerenv`` file exists (Docker) 

16 2. ``/run/.containerenv`` exists (Podman) 

17 3. ``CONTAINER`` environment variable is set 

18 4. ``/proc/1/cgroup`` contains docker/lxc/containerd/kubepods references 

19 

20 Returns: 

21 True if a container environment is detected. 

22 """ 

23 # Docker marker file 

24 if Path("/.dockerenv").exists(): 

25 return True 

26 

27 # Podman marker file 

28 if Path("/run/.containerenv").exists(): 

29 return True 

30 

31 # Environment variable (set by some container runtimes) 

32 if os.environ.get("CONTAINER"): 

33 return True 

34 

35 # Check cgroup for container runtime references (Linux only) 

36 try: 

37 cgroup_path = Path("/proc/1/cgroup") 

38 if cgroup_path.exists(): 

39 content = cgroup_path.read_text(encoding="utf-8", errors="ignore") 

40 for indicator in ("docker", "lxc", "containerd", "kubepods"): 

41 if indicator in content.lower(): 

42 return True 

43 except OSError: 

44 pass 

45 

46 return False