test_container_runtime_3092.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. """Container detection for the connection diagnostic (#3092).
  2. The reporter ran Bambuddy in a Podman container with host networking and was
  3. told "Not running in Docker - not applicable", which reads as "you are on
  4. bare metal" and sends people looking for the problem somewhere else. Two
  5. separate questions are pinned here: which engine we are under, and whether
  6. its network namespace is the host's.
  7. """
  8. import builtins
  9. import io
  10. import os
  11. from contextlib import contextmanager
  12. from unittest.mock import patch
  13. from backend.app.services import discovery
  14. from backend.app.services.printer_diagnostic import (
  15. _detect_container_network_mode,
  16. _has_native_interface,
  17. )
  18. MOD = "backend.app.services.printer_diagnostic"
  19. @contextmanager
  20. def _host(files=None, env=None):
  21. """Present a fixed set of marker files and environment to the detector."""
  22. files = files or {}
  23. class _Path:
  24. def __init__(self, p):
  25. self._p = str(p)
  26. def __str__(self):
  27. return self._p
  28. def exists(self):
  29. return self._p in files
  30. def _read(path):
  31. return files.get(str(path), "")
  32. real_open = builtins.open
  33. def _open(path, *args, **kwargs):
  34. # is_running_in_docker() reads /proc/1/cgroup with a plain open() and
  35. # is deliberately left that way, so intercept only the paths under
  36. # test and let everything else through untouched.
  37. key = str(path)
  38. if key in files:
  39. return io.StringIO(files[key])
  40. if key in ("/proc/1/cgroup", "/run/systemd/container"):
  41. raise FileNotFoundError(key)
  42. return real_open(path, *args, **kwargs)
  43. with (
  44. patch.object(discovery, "_read_text", _read),
  45. patch.object(discovery, "Path", _Path),
  46. patch.object(builtins, "open", _open),
  47. patch.dict(os.environ, env or {}, clear=True),
  48. ):
  49. yield
  50. class TestDetectContainerRuntime:
  51. def test_bare_metal_is_none(self):
  52. with _host():
  53. assert discovery.detect_container_runtime() is None
  54. def test_podman_by_its_own_marker_file(self):
  55. with _host({"/run/.containerenv": ""}):
  56. assert discovery.detect_container_runtime() == discovery.RUNTIME_PODMAN
  57. def test_podman_by_the_older_root_marker(self):
  58. with _host({"/.containerenv": ""}):
  59. assert discovery.detect_container_runtime() == discovery.RUNTIME_PODMAN
  60. def test_podman_by_cgroup(self):
  61. with _host({"/proc/1/cgroup": "0::/machine.slice/libpod-abc.scope\n"}):
  62. assert discovery.detect_container_runtime() == discovery.RUNTIME_PODMAN
  63. def test_docker_by_its_own_marker_file(self):
  64. with _host({"/.dockerenv": ""}):
  65. assert discovery.detect_container_runtime() == discovery.RUNTIME_DOCKER
  66. def test_systemd_names_the_engine_and_wins(self):
  67. """The only signal that tells the two apart without guessing.
  68. Podman leaves /.dockerenv alone, but a Docker-compatible shim may not,
  69. so the file that carries the engine's own name is consulted first.
  70. """
  71. with _host({"/run/systemd/container": "podman\n", "/.dockerenv": ""}):
  72. assert discovery.detect_container_runtime() == discovery.RUNTIME_PODMAN
  73. def test_kubernetes(self):
  74. with _host({"/proc/1/cgroup": "11:memory:/kubepods/besteffort/pod123\n"}):
  75. assert discovery.detect_container_runtime() == discovery.RUNTIME_KUBERNETES
  76. def test_lxc_is_named_not_mistaken_for_docker(self):
  77. with _host({"/run/systemd/container": "lxc\n"}):
  78. assert discovery.detect_container_runtime() == discovery.RUNTIME_LXC
  79. def test_an_unnamed_engine_still_counts_as_a_container(self):
  80. with _host({"/run/systemd/container": "some-new-engine\n"}):
  81. assert discovery.detect_container_runtime() == discovery.RUNTIME_OTHER
  82. def test_lxc_is_not_an_oci_runtime(self):
  83. """A system container is bridged onto the LAN like a small VM.
  84. There is no "recreate it with host networking" advice to give, so it
  85. must not fall into the branch that gives it.
  86. """
  87. assert discovery.RUNTIME_LXC not in discovery.OCI_RUNTIMES
  88. assert discovery.RUNTIME_PODMAN in discovery.OCI_RUNTIMES
  89. class TestIsRunningInDockerIsUnchanged:
  90. """Naming Podman must not widen the flag three other callers key off.
  91. /api/discovery/info feeds it to the Add-Printer flow, where isDocker
  92. switches discovery from SSDP to subnet scanning. SSDP works for a
  93. host-networked Podman container, so answering True there would take a
  94. working feature away.
  95. """
  96. def test_podman_does_not_read_as_docker(self):
  97. with _host({"/run/.containerenv": "", "/proc/1/cgroup": "0::/machine.slice/libpod-abc.scope\n"}):
  98. assert discovery.is_running_in_docker() is False
  99. def test_docker_still_reads_as_docker(self):
  100. with _host({"/.dockerenv": ""}):
  101. assert discovery.is_running_in_docker() is True
  102. def test_containerd_still_reads_as_docker(self):
  103. with _host({"/proc/1/cgroup": "0::/system.slice/containerd.service\n"}):
  104. assert discovery.is_running_in_docker() is True
  105. def _sysfs(interfaces):
  106. """Present a fixed /sys/class/net to _has_native_interface().
  107. ``interfaces`` maps name -> (ifindex, iflink, is_tun). A veth's iflink is
  108. its peer's index in another namespace, so the two never agree.
  109. """
  110. class _Path:
  111. def __init__(self, p):
  112. self._p = str(p)
  113. def __truediv__(self, other):
  114. return _Path(f"{self._p}/{other}")
  115. def _parts(self):
  116. name, _, leaf = self._p.removeprefix("/sys/class/net/").partition("/")
  117. return interfaces.get(name), leaf
  118. def exists(self):
  119. spec, leaf = self._parts()
  120. return bool(spec) and leaf == "tun_flags" and spec[2]
  121. def read_text(self):
  122. spec, leaf = self._parts()
  123. if not spec:
  124. raise FileNotFoundError(self._p)
  125. return f"{spec[0] if leaf == 'ifindex' else spec[1]}\n"
  126. return (
  127. patch(f"{MOD}.Path", _Path),
  128. # The kernel names each interface with the same index sysfs reports,
  129. # which is exactly what the cross-check below relies on.
  130. patch(f"{MOD}.socket.if_nameindex", return_value=[(spec[0], name) for name, spec in interfaces.items()]),
  131. )
  132. @contextmanager
  133. def _netns(interfaces):
  134. path_patch, names_patch = _sysfs(interfaces)
  135. with path_patch, names_patch:
  136. yield
  137. # A NAT-networked container: one veth per attached network, nothing else.
  138. _BRIDGE_NETNS = {"lo": (1, 1, False), "eth0": (2, 45, False)}
  139. # Host networking on a plain Linux box: a real NIC, native to this namespace.
  140. _HOST_NETNS = {"lo": (1, 1, False), "enp3s0": (2, 2, False)}
  141. class TestHasNativeInterface:
  142. def test_a_natted_container_sees_only_veths(self):
  143. with _netns(_BRIDGE_NETNS):
  144. assert _has_native_interface() is False
  145. def test_a_shared_host_namespace_has_a_real_nic(self):
  146. with _netns(_HOST_NETNS):
  147. assert _has_native_interface() is True
  148. def test_a_bridge_counts(self):
  149. """A Proxmox/libvirt host may have nothing but vmbr0 with an address."""
  150. with _netns({"lo": (1, 1, False), "vmbr0": (2, 2, False)}):
  151. assert _has_native_interface() is True
  152. def test_a_bind_mounted_host_sys_is_not_this_namespace(self):
  153. """sysfs is namespace-tagged, but a bind mount of the host's /sys is not.
  154. A container given ``-v /sys:/sys`` sees the host's interfaces under
  155. names that can collide with its own, and reading their numbers would
  156. be reading another namespace's answer. The entry found in sysfs has
  157. to be the one the kernel just named.
  158. """
  159. interfaces = {"lo": (1, 1, False), "eth0": (2, 45, False)}
  160. path_patch, _ = _sysfs({"lo": (1, 1, False), "eth0": (7, 7, False)})
  161. with (
  162. path_patch,
  163. patch(f"{MOD}.socket.if_nameindex", return_value=[(i, n) for n, (i, _l, _t) in interfaces.items()]),
  164. ):
  165. assert _has_native_interface() is False
  166. def test_a_containers_own_vpn_does_not_count(self):
  167. """A container can run WireGuard or Tailscale; its tun is native here.
  168. That says nothing about whose namespace this is, and counting it would
  169. report host networking to a bridge-mode container.
  170. """
  171. with _netns({"lo": (1, 1, False), "eth0": (2, 45, False), "wg0": (3, 3, True)}):
  172. assert _has_native_interface() is False
  173. class TestDetectContainerNetworkMode:
  174. def test_docker_host_mode_by_the_original_signal(self):
  175. """A Docker host always has a docker0, whatever else is going on."""
  176. with _netns({"lo": (1, 1, False), "eth0": (2, 45, False), "docker0": (3, 3, False)}):
  177. assert _detect_container_network_mode(discovery.RUNTIME_DOCKER) == "host"
  178. def test_docker_bridge_mode(self):
  179. with _netns(_BRIDGE_NETNS):
  180. assert _detect_container_network_mode(discovery.RUNTIME_DOCKER) == "bridge"
  181. def test_podman_host_mode_on_a_host_with_no_engine_bridges(self):
  182. """#3092 itself.
  183. A Podman host running no bridge containers creates no docker0, no
  184. podman0 and no veth, so the original signal finds nothing and the old
  185. code concluded bridge networking.
  186. """
  187. with _netns(_HOST_NETNS):
  188. assert _detect_container_network_mode(discovery.RUNTIME_PODMAN) == "host"
  189. def test_podman_bridge_mode(self):
  190. with _netns(_BRIDGE_NETNS):
  191. assert _detect_container_network_mode(discovery.RUNTIME_PODMAN) == "bridge"
  192. def test_podmans_own_bridge_is_a_host_signal_too(self):
  193. with _netns({"lo": (1, 1, False), "eth0": (2, 45, False), "podman0": (3, 3, False)}):
  194. assert _detect_container_network_mode(discovery.RUNTIME_PODMAN) == "host"
  195. def test_an_isolated_namespace_under_no_known_engine_is_unknown(self):
  196. """Never guess bridge for something we cannot name — say so instead."""
  197. with _netns(_BRIDGE_NETNS):
  198. assert _detect_container_network_mode(None) is None