test_posix.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """POSIX specific tests."""
  6. import datetime
  7. import errno
  8. import os
  9. import re
  10. import shutil
  11. import subprocess
  12. import time
  13. from unittest import mock
  14. import psutil
  15. from psutil import AIX
  16. from psutil import BSD
  17. from psutil import LINUX
  18. from psutil import MACOS
  19. from psutil import OPENBSD
  20. from psutil import POSIX
  21. from psutil import SUNOS
  22. from psutil.tests import AARCH64
  23. from psutil.tests import HAS_NET_IO_COUNTERS
  24. from psutil.tests import PYTHON_EXE
  25. from psutil.tests import PsutilTestCase
  26. from psutil.tests import pytest
  27. from psutil.tests import retry_on_failure
  28. from psutil.tests import sh
  29. from psutil.tests import skip_on_access_denied
  30. from psutil.tests import spawn_testproc
  31. from psutil.tests import terminate
  32. if POSIX:
  33. import mmap
  34. import resource
  35. from psutil._psutil_posix import getpagesize
  36. def ps(fmt, pid=None):
  37. """Wrapper for calling the ps command with a little bit of cross-platform
  38. support for a narrow range of features.
  39. """
  40. cmd = ['ps']
  41. if LINUX:
  42. cmd.append('--no-headers')
  43. if pid is not None:
  44. cmd.extend(['-p', str(pid)])
  45. elif SUNOS or AIX:
  46. cmd.append('-A')
  47. else:
  48. cmd.append('ax')
  49. if SUNOS:
  50. fmt = fmt.replace("start", "stime")
  51. cmd.extend(['-o', fmt])
  52. output = sh(cmd)
  53. output = output.splitlines() if LINUX else output.splitlines()[1:]
  54. all_output = []
  55. for line in output:
  56. line = line.strip()
  57. try:
  58. line = int(line)
  59. except ValueError:
  60. pass
  61. all_output.append(line)
  62. if pid is None:
  63. return all_output
  64. else:
  65. return all_output[0]
  66. # ps "-o" field names differ wildly between platforms.
  67. # "comm" means "only executable name" but is not available on BSD platforms.
  68. # "args" means "command with all its arguments", and is also not available
  69. # on BSD platforms.
  70. # "command" is like "args" on most platforms, but like "comm" on AIX,
  71. # and not available on SUNOS.
  72. # so for the executable name we can use "comm" on Solaris and split "command"
  73. # on other platforms.
  74. # to get the cmdline (with args) we have to use "args" on AIX and
  75. # Solaris, and can use "command" on all others.
  76. def ps_name(pid):
  77. field = "command"
  78. if SUNOS:
  79. field = "comm"
  80. command = ps(field, pid).split()
  81. return command[0]
  82. def ps_args(pid):
  83. field = "command"
  84. if AIX or SUNOS:
  85. field = "args"
  86. out = ps(field, pid)
  87. # observed on BSD + Github CI: '/usr/local/bin/python3 -E -O (python3.9)'
  88. out = re.sub(r"\(python.*?\)$", "", out)
  89. return out.strip()
  90. def ps_rss(pid):
  91. field = "rss"
  92. if AIX:
  93. field = "rssize"
  94. return ps(field, pid)
  95. def ps_vsz(pid):
  96. field = "vsz"
  97. if AIX:
  98. field = "vsize"
  99. return ps(field, pid)
  100. def df(device):
  101. try:
  102. out = sh(f"df -k {device}").strip()
  103. except RuntimeError as err:
  104. if "device busy" in str(err).lower():
  105. raise pytest.skip("df returned EBUSY")
  106. raise
  107. line = out.split('\n')[1]
  108. fields = line.split()
  109. sys_total = int(fields[1]) * 1024
  110. sys_used = int(fields[2]) * 1024
  111. sys_free = int(fields[3]) * 1024
  112. sys_percent = float(fields[4].replace('%', ''))
  113. return (sys_total, sys_used, sys_free, sys_percent)
  114. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  115. class TestProcess(PsutilTestCase):
  116. """Compare psutil results against 'ps' command line utility (mainly)."""
  117. @classmethod
  118. def setUpClass(cls):
  119. cls.pid = spawn_testproc(
  120. [PYTHON_EXE, "-E", "-O"], stdin=subprocess.PIPE
  121. ).pid
  122. @classmethod
  123. def tearDownClass(cls):
  124. terminate(cls.pid)
  125. def test_ppid(self):
  126. ppid_ps = ps('ppid', self.pid)
  127. ppid_psutil = psutil.Process(self.pid).ppid()
  128. assert ppid_ps == ppid_psutil
  129. def test_uid(self):
  130. uid_ps = ps('uid', self.pid)
  131. uid_psutil = psutil.Process(self.pid).uids().real
  132. assert uid_ps == uid_psutil
  133. def test_gid(self):
  134. gid_ps = ps('rgid', self.pid)
  135. gid_psutil = psutil.Process(self.pid).gids().real
  136. assert gid_ps == gid_psutil
  137. def test_username(self):
  138. username_ps = ps('user', self.pid)
  139. username_psutil = psutil.Process(self.pid).username()
  140. assert username_ps == username_psutil
  141. def test_username_no_resolution(self):
  142. # Emulate a case where the system can't resolve the uid to
  143. # a username in which case psutil is supposed to return
  144. # the stringified uid.
  145. p = psutil.Process()
  146. with mock.patch("psutil.pwd.getpwuid", side_effect=KeyError) as fun:
  147. assert p.username() == str(p.uids().real)
  148. assert fun.called
  149. @skip_on_access_denied()
  150. @retry_on_failure()
  151. def test_rss_memory(self):
  152. # give python interpreter some time to properly initialize
  153. # so that the results are the same
  154. time.sleep(0.1)
  155. rss_ps = ps_rss(self.pid)
  156. rss_psutil = psutil.Process(self.pid).memory_info()[0] / 1024
  157. assert rss_ps == rss_psutil
  158. @skip_on_access_denied()
  159. @retry_on_failure()
  160. def test_vsz_memory(self):
  161. # give python interpreter some time to properly initialize
  162. # so that the results are the same
  163. time.sleep(0.1)
  164. vsz_ps = ps_vsz(self.pid)
  165. vsz_psutil = psutil.Process(self.pid).memory_info()[1] / 1024
  166. assert vsz_ps == vsz_psutil
  167. def test_name(self):
  168. name_ps = ps_name(self.pid)
  169. # remove path if there is any, from the command
  170. name_ps = os.path.basename(name_ps).lower()
  171. name_psutil = psutil.Process(self.pid).name().lower()
  172. # ...because of how we calculate PYTHON_EXE; on MACOS this may
  173. # be "pythonX.Y".
  174. name_ps = re.sub(r"\d.\d", "", name_ps)
  175. name_psutil = re.sub(r"\d.\d", "", name_psutil)
  176. # ...may also be "python.X"
  177. name_ps = re.sub(r"\d", "", name_ps)
  178. name_psutil = re.sub(r"\d", "", name_psutil)
  179. assert name_ps == name_psutil
  180. def test_name_long(self):
  181. # On UNIX the kernel truncates the name to the first 15
  182. # characters. In such a case psutil tries to determine the
  183. # full name from the cmdline.
  184. name = "long-program-name"
  185. cmdline = ["long-program-name-extended", "foo", "bar"]
  186. with mock.patch("psutil._psplatform.Process.name", return_value=name):
  187. with mock.patch(
  188. "psutil._psplatform.Process.cmdline", return_value=cmdline
  189. ):
  190. p = psutil.Process()
  191. assert p.name() == "long-program-name-extended"
  192. def test_name_long_cmdline_ad_exc(self):
  193. # Same as above but emulates a case where cmdline() raises
  194. # AccessDenied in which case psutil is supposed to return
  195. # the truncated name instead of crashing.
  196. name = "long-program-name"
  197. with mock.patch("psutil._psplatform.Process.name", return_value=name):
  198. with mock.patch(
  199. "psutil._psplatform.Process.cmdline",
  200. side_effect=psutil.AccessDenied(0, ""),
  201. ):
  202. p = psutil.Process()
  203. assert p.name() == "long-program-name"
  204. def test_name_long_cmdline_nsp_exc(self):
  205. # Same as above but emulates a case where cmdline() raises NSP
  206. # which is supposed to propagate.
  207. name = "long-program-name"
  208. with mock.patch("psutil._psplatform.Process.name", return_value=name):
  209. with mock.patch(
  210. "psutil._psplatform.Process.cmdline",
  211. side_effect=psutil.NoSuchProcess(0, ""),
  212. ):
  213. p = psutil.Process()
  214. with pytest.raises(psutil.NoSuchProcess):
  215. p.name()
  216. @pytest.mark.skipif(MACOS or BSD, reason="ps -o start not available")
  217. def test_create_time(self):
  218. time_ps = ps('start', self.pid)
  219. time_psutil = psutil.Process(self.pid).create_time()
  220. time_psutil_tstamp = datetime.datetime.fromtimestamp(
  221. time_psutil
  222. ).strftime("%H:%M:%S")
  223. # sometimes ps shows the time rounded up instead of down, so we check
  224. # for both possible values
  225. round_time_psutil = round(time_psutil)
  226. round_time_psutil_tstamp = datetime.datetime.fromtimestamp(
  227. round_time_psutil
  228. ).strftime("%H:%M:%S")
  229. assert time_ps in {time_psutil_tstamp, round_time_psutil_tstamp}
  230. def test_exe(self):
  231. ps_pathname = ps_name(self.pid)
  232. psutil_pathname = psutil.Process(self.pid).exe()
  233. try:
  234. assert ps_pathname == psutil_pathname
  235. except AssertionError:
  236. # certain platforms such as BSD are more accurate returning:
  237. # "/usr/local/bin/python3.7"
  238. # ...instead of:
  239. # "/usr/local/bin/python"
  240. # We do not want to consider this difference in accuracy
  241. # an error.
  242. adjusted_ps_pathname = ps_pathname[: len(ps_pathname)]
  243. assert ps_pathname == adjusted_ps_pathname
  244. # On macOS the official python installer exposes a python wrapper that
  245. # executes a python executable hidden inside an application bundle inside
  246. # the Python framework.
  247. # There's a race condition between the ps call & the psutil call below
  248. # depending on the completion of the execve call so let's retry on failure
  249. @retry_on_failure()
  250. def test_cmdline(self):
  251. ps_cmdline = ps_args(self.pid)
  252. psutil_cmdline = " ".join(psutil.Process(self.pid).cmdline())
  253. if AARCH64 and len(ps_cmdline) < len(psutil_cmdline):
  254. assert psutil_cmdline.startswith(ps_cmdline)
  255. else:
  256. assert ps_cmdline == psutil_cmdline
  257. # On SUNOS "ps" reads niceness /proc/pid/psinfo which returns an
  258. # incorrect value (20); the real deal is getpriority(2) which
  259. # returns 0; psutil relies on it, see:
  260. # https://github.com/giampaolo/psutil/issues/1082
  261. # AIX has the same issue
  262. @pytest.mark.skipif(SUNOS, reason="not reliable on SUNOS")
  263. @pytest.mark.skipif(AIX, reason="not reliable on AIX")
  264. def test_nice(self):
  265. ps_nice = ps('nice', self.pid)
  266. psutil_nice = psutil.Process().nice()
  267. assert ps_nice == psutil_nice
  268. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  269. class TestSystemAPIs(PsutilTestCase):
  270. """Test some system APIs."""
  271. @retry_on_failure()
  272. def test_pids(self):
  273. # Note: this test might fail if the OS is starting/killing
  274. # other processes in the meantime
  275. pids_ps = sorted(ps("pid"))
  276. pids_psutil = psutil.pids()
  277. # on MACOS and OPENBSD ps doesn't show pid 0
  278. if MACOS or (OPENBSD and 0 not in pids_ps):
  279. pids_ps.insert(0, 0)
  280. # There will often be one more process in pids_ps for ps itself
  281. if len(pids_ps) - len(pids_psutil) > 1:
  282. difference = [x for x in pids_psutil if x not in pids_ps] + [
  283. x for x in pids_ps if x not in pids_psutil
  284. ]
  285. raise self.fail("difference: " + str(difference))
  286. # for some reason ifconfig -a does not report all interfaces
  287. # returned by psutil
  288. @pytest.mark.skipif(SUNOS, reason="unreliable on SUNOS")
  289. @pytest.mark.skipif(not shutil.which("ifconfig"), reason="no ifconfig cmd")
  290. @pytest.mark.skipif(not HAS_NET_IO_COUNTERS, reason="not supported")
  291. def test_nic_names(self):
  292. output = sh("ifconfig -a")
  293. for nic in psutil.net_io_counters(pernic=True):
  294. for line in output.split():
  295. if line.startswith(nic):
  296. break
  297. else:
  298. raise self.fail(
  299. f"couldn't find {nic} nic in 'ifconfig -a'"
  300. f" output\n{output}"
  301. )
  302. # @pytest.mark.skipif(CI_TESTING and not psutil.users(),
  303. # reason="unreliable on CI")
  304. @retry_on_failure()
  305. def test_users(self):
  306. out = sh("who -u")
  307. if not out.strip():
  308. raise pytest.skip("no users on this system")
  309. lines = out.split('\n')
  310. users = [x.split()[0] for x in lines]
  311. terminals = [x.split()[1] for x in lines]
  312. assert len(users) == len(psutil.users())
  313. with self.subTest(psutil=psutil.users(), who=out):
  314. for idx, u in enumerate(psutil.users()):
  315. assert u.name == users[idx]
  316. assert u.terminal == terminals[idx]
  317. if u.pid is not None: # None on OpenBSD
  318. psutil.Process(u.pid)
  319. @retry_on_failure()
  320. def test_users_started(self):
  321. out = sh("who -u")
  322. if not out.strip():
  323. raise pytest.skip("no users on this system")
  324. tstamp = None
  325. # '2023-04-11 09:31' (Linux)
  326. started = re.findall(r"\d\d\d\d-\d\d-\d\d \d\d:\d\d", out)
  327. if started:
  328. tstamp = "%Y-%m-%d %H:%M"
  329. else:
  330. # 'Apr 10 22:27' (macOS)
  331. started = re.findall(r"[A-Z][a-z][a-z] \d\d \d\d:\d\d", out)
  332. if started:
  333. tstamp = "%b %d %H:%M"
  334. else:
  335. # 'Apr 10'
  336. started = re.findall(r"[A-Z][a-z][a-z] \d\d", out)
  337. if started:
  338. tstamp = "%b %d"
  339. else:
  340. # 'apr 10' (sunOS)
  341. started = re.findall(r"[a-z][a-z][a-z] \d\d", out)
  342. if started:
  343. tstamp = "%b %d"
  344. started = [x.capitalize() for x in started]
  345. if not tstamp:
  346. raise pytest.skip(f"cannot interpret tstamp in who output\n{out}")
  347. with self.subTest(psutil=psutil.users(), who=out):
  348. for idx, u in enumerate(psutil.users()):
  349. psutil_value = datetime.datetime.fromtimestamp(
  350. u.started
  351. ).strftime(tstamp)
  352. assert psutil_value == started[idx]
  353. def test_pid_exists_let_raise(self):
  354. # According to "man 2 kill" possible error values for kill
  355. # are (EINVAL, EPERM, ESRCH). Test that any other errno
  356. # results in an exception.
  357. with mock.patch(
  358. "psutil._psposix.os.kill", side_effect=OSError(errno.EBADF, "")
  359. ) as m:
  360. with pytest.raises(OSError):
  361. psutil._psposix.pid_exists(os.getpid())
  362. assert m.called
  363. def test_os_waitpid_let_raise(self):
  364. # os.waitpid() is supposed to catch EINTR and ECHILD only.
  365. # Test that any other errno results in an exception.
  366. with mock.patch(
  367. "psutil._psposix.os.waitpid", side_effect=OSError(errno.EBADF, "")
  368. ) as m:
  369. with pytest.raises(OSError):
  370. psutil._psposix.wait_pid(os.getpid())
  371. assert m.called
  372. def test_os_waitpid_eintr(self):
  373. # os.waitpid() is supposed to "retry" on EINTR.
  374. with mock.patch(
  375. "psutil._psposix.os.waitpid", side_effect=OSError(errno.EINTR, "")
  376. ) as m:
  377. with pytest.raises(psutil._psposix.TimeoutExpired):
  378. psutil._psposix.wait_pid(os.getpid(), timeout=0.01)
  379. assert m.called
  380. def test_os_waitpid_bad_ret_status(self):
  381. # Simulate os.waitpid() returning a bad status.
  382. with mock.patch(
  383. "psutil._psposix.os.waitpid", return_value=(1, -1)
  384. ) as m:
  385. with pytest.raises(ValueError):
  386. psutil._psposix.wait_pid(os.getpid())
  387. assert m.called
  388. # AIX can return '-' in df output instead of numbers, e.g. for /proc
  389. @pytest.mark.skipif(AIX, reason="unreliable on AIX")
  390. @retry_on_failure()
  391. def test_disk_usage(self):
  392. tolerance = 4 * 1024 * 1024 # 4MB
  393. for part in psutil.disk_partitions(all=False):
  394. usage = psutil.disk_usage(part.mountpoint)
  395. try:
  396. sys_total, sys_used, sys_free, sys_percent = df(part.device)
  397. except RuntimeError as err:
  398. # see:
  399. # https://travis-ci.org/giampaolo/psutil/jobs/138338464
  400. # https://travis-ci.org/giampaolo/psutil/jobs/138343361
  401. err = str(err).lower()
  402. if (
  403. "no such file or directory" in err
  404. or "raw devices not supported" in err
  405. or "permission denied" in err
  406. ):
  407. continue
  408. raise
  409. else:
  410. assert abs(usage.total - sys_total) < tolerance
  411. assert abs(usage.used - sys_used) < tolerance
  412. assert abs(usage.free - sys_free) < tolerance
  413. assert abs(usage.percent - sys_percent) <= 1
  414. @pytest.mark.skipif(not POSIX, reason="POSIX only")
  415. class TestMisc(PsutilTestCase):
  416. def test_getpagesize(self):
  417. pagesize = getpagesize()
  418. assert pagesize > 0
  419. assert pagesize == resource.getpagesize()
  420. assert pagesize == mmap.PAGESIZE