test_posix.py 17 KB

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