test_process_all.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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. """Iterate over all process PIDs and for each one of them invoke and
  6. test all psutil.Process() methods.
  7. """
  8. import enum
  9. import errno
  10. import multiprocessing
  11. import os
  12. import stat
  13. import time
  14. import traceback
  15. import psutil
  16. from psutil import AIX
  17. from psutil import BSD
  18. from psutil import FREEBSD
  19. from psutil import LINUX
  20. from psutil import MACOS
  21. from psutil import NETBSD
  22. from psutil import OPENBSD
  23. from psutil import OSX
  24. from psutil import POSIX
  25. from psutil import WINDOWS
  26. from psutil.tests import CI_TESTING
  27. from psutil.tests import PYTEST_PARALLEL
  28. from psutil.tests import VALID_PROC_STATUSES
  29. from psutil.tests import PsutilTestCase
  30. from psutil.tests import check_connection_ntuple
  31. from psutil.tests import create_sockets
  32. from psutil.tests import is_namedtuple
  33. from psutil.tests import is_win_secure_system_proc
  34. from psutil.tests import process_namespace
  35. from psutil.tests import pytest
  36. # Cuts the time in half, but (e.g.) on macOS the process pool stays
  37. # alive after join() (multiprocessing bug?), messing up other tests.
  38. USE_PROC_POOL = LINUX and not CI_TESTING and not PYTEST_PARALLEL
  39. def proc_info(pid):
  40. tcase = PsutilTestCase()
  41. def check_exception(exc, proc, name, ppid):
  42. tcase.assertEqual(exc.pid, pid)
  43. if exc.name is not None:
  44. tcase.assertEqual(exc.name, name)
  45. if isinstance(exc, psutil.ZombieProcess):
  46. tcase.assertProcessZombie(proc)
  47. if exc.ppid is not None:
  48. tcase.assertGreaterEqual(exc.ppid, 0)
  49. tcase.assertEqual(exc.ppid, ppid)
  50. elif isinstance(exc, psutil.NoSuchProcess):
  51. tcase.assertProcessGone(proc)
  52. str(exc)
  53. repr(exc)
  54. def do_wait():
  55. if pid != 0:
  56. try:
  57. proc.wait(0)
  58. except psutil.Error as exc:
  59. check_exception(exc, proc, name, ppid)
  60. try:
  61. proc = psutil.Process(pid)
  62. except psutil.NoSuchProcess:
  63. tcase.assertPidGone(pid)
  64. return {}
  65. try:
  66. d = proc.as_dict(['ppid', 'name'])
  67. except psutil.NoSuchProcess:
  68. tcase.assertProcessGone(proc)
  69. else:
  70. name, ppid = d['name'], d['ppid']
  71. info = {'pid': proc.pid}
  72. ns = process_namespace(proc)
  73. # We don't use oneshot() because in order not to fool
  74. # check_exception() in case of NSP.
  75. for fun, fun_name in ns.iter(ns.getters, clear_cache=False):
  76. try:
  77. info[fun_name] = fun()
  78. except psutil.Error as exc:
  79. check_exception(exc, proc, name, ppid)
  80. continue
  81. do_wait()
  82. return info
  83. class TestFetchAllProcesses(PsutilTestCase):
  84. """Test which iterates over all running processes and performs
  85. some sanity checks against Process API's returned values.
  86. Uses a process pool to get info about all processes.
  87. """
  88. def setUp(self):
  89. psutil._set_debug(False)
  90. # Using a pool in a CI env may result in deadlock, see:
  91. # https://github.com/giampaolo/psutil/issues/2104
  92. if USE_PROC_POOL:
  93. self.pool = multiprocessing.Pool()
  94. def tearDown(self):
  95. psutil._set_debug(True)
  96. if USE_PROC_POOL:
  97. self.pool.terminate()
  98. self.pool.join()
  99. def iter_proc_info(self):
  100. # Fixes "can't pickle <function proc_info>: it's not the
  101. # same object as test_process_all.proc_info".
  102. from psutil.tests.test_process_all import proc_info
  103. if USE_PROC_POOL:
  104. return self.pool.imap_unordered(proc_info, psutil.pids())
  105. else:
  106. ls = [proc_info(pid) for pid in psutil.pids()]
  107. return ls
  108. def test_all(self):
  109. failures = []
  110. for info in self.iter_proc_info():
  111. for name, value in info.items():
  112. meth = getattr(self, name)
  113. try:
  114. meth(value, info)
  115. except Exception: # noqa: BLE001
  116. s = '\n' + '=' * 70 + '\n'
  117. s += (
  118. "FAIL: name=test_{}, pid={}, ret={}\ninfo={}\n".format(
  119. name,
  120. info['pid'],
  121. repr(value),
  122. info,
  123. )
  124. )
  125. s += '-' * 70
  126. s += f"\n{traceback.format_exc()}"
  127. s = "\n".join((" " * 4) + i for i in s.splitlines()) + "\n"
  128. failures.append(s)
  129. else:
  130. if value not in (0, 0.0, [], None, '', {}):
  131. assert value, value
  132. if failures:
  133. raise self.fail(''.join(failures))
  134. def cmdline(self, ret, info):
  135. assert isinstance(ret, list)
  136. for part in ret:
  137. assert isinstance(part, str)
  138. def exe(self, ret, info):
  139. assert isinstance(ret, str)
  140. assert ret.strip() == ret
  141. if ret:
  142. if WINDOWS and not ret.endswith('.exe'):
  143. return # May be "Registry", "MemCompression", ...
  144. assert os.path.isabs(ret), ret
  145. # Note: os.stat() may return False even if the file is there
  146. # hence we skip the test, see:
  147. # http://stackoverflow.com/questions/3112546/os-path-exists-lies
  148. if POSIX and os.path.isfile(ret):
  149. if hasattr(os, 'access') and hasattr(os, "X_OK"):
  150. # XXX: may fail on MACOS
  151. try:
  152. assert os.access(ret, os.X_OK)
  153. except AssertionError:
  154. if os.path.exists(ret) and not CI_TESTING:
  155. raise
  156. def pid(self, ret, info):
  157. assert isinstance(ret, int)
  158. assert ret >= 0
  159. def ppid(self, ret, info):
  160. assert isinstance(ret, int)
  161. assert ret >= 0
  162. proc_info(ret)
  163. def name(self, ret, info):
  164. assert isinstance(ret, str)
  165. if WINDOWS and not ret and is_win_secure_system_proc(info['pid']):
  166. # https://github.com/giampaolo/psutil/issues/2338
  167. return
  168. # on AIX, "<exiting>" processes don't have names
  169. if not AIX:
  170. assert ret, repr(ret)
  171. def create_time(self, ret, info):
  172. assert isinstance(ret, float)
  173. try:
  174. assert ret >= 0
  175. except AssertionError:
  176. # XXX
  177. if OPENBSD and info['status'] == psutil.STATUS_ZOMBIE:
  178. pass
  179. else:
  180. raise
  181. # this can't be taken for granted on all platforms
  182. # self.assertGreaterEqual(ret, psutil.boot_time())
  183. # make sure returned value can be pretty printed
  184. # with strftime
  185. time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
  186. def uids(self, ret, info):
  187. assert is_namedtuple(ret)
  188. for uid in ret:
  189. assert isinstance(uid, int)
  190. assert uid >= 0
  191. def gids(self, ret, info):
  192. assert is_namedtuple(ret)
  193. # note: testing all gids as above seems not to be reliable for
  194. # gid == 30 (nodoby); not sure why.
  195. for gid in ret:
  196. assert isinstance(gid, int)
  197. if not MACOS and not NETBSD:
  198. assert gid >= 0
  199. def username(self, ret, info):
  200. assert isinstance(ret, str)
  201. assert ret.strip() == ret
  202. assert ret.strip()
  203. def status(self, ret, info):
  204. assert isinstance(ret, str)
  205. assert ret, ret
  206. assert ret != '?' # XXX
  207. assert ret in VALID_PROC_STATUSES
  208. def io_counters(self, ret, info):
  209. assert is_namedtuple(ret)
  210. for field in ret:
  211. assert isinstance(field, int)
  212. if field != -1:
  213. assert field >= 0
  214. def ionice(self, ret, info):
  215. if LINUX:
  216. assert isinstance(ret.ioclass, int)
  217. assert isinstance(ret.value, int)
  218. assert ret.ioclass >= 0
  219. assert ret.value >= 0
  220. else: # Windows, Cygwin
  221. choices = [
  222. psutil.IOPRIO_VERYLOW,
  223. psutil.IOPRIO_LOW,
  224. psutil.IOPRIO_NORMAL,
  225. psutil.IOPRIO_HIGH,
  226. ]
  227. assert isinstance(ret, int)
  228. assert ret >= 0
  229. assert ret in choices
  230. def num_threads(self, ret, info):
  231. assert isinstance(ret, int)
  232. if WINDOWS and ret == 0 and is_win_secure_system_proc(info['pid']):
  233. # https://github.com/giampaolo/psutil/issues/2338
  234. return
  235. assert ret >= 1
  236. def threads(self, ret, info):
  237. assert isinstance(ret, list)
  238. for t in ret:
  239. assert is_namedtuple(t)
  240. assert t.id >= 0
  241. assert t.user_time >= 0
  242. assert t.system_time >= 0
  243. for field in t:
  244. assert isinstance(field, (int, float))
  245. def cpu_times(self, ret, info):
  246. assert is_namedtuple(ret)
  247. for n in ret:
  248. assert isinstance(n, float)
  249. assert n >= 0
  250. # TODO: check ntuple fields
  251. def cpu_percent(self, ret, info):
  252. assert isinstance(ret, float)
  253. assert 0.0 <= ret <= 100.0, ret
  254. def cpu_num(self, ret, info):
  255. assert isinstance(ret, int)
  256. if FREEBSD and ret == -1:
  257. return
  258. assert ret >= 0
  259. if psutil.cpu_count() == 1:
  260. assert ret == 0
  261. assert ret in list(range(psutil.cpu_count()))
  262. def memory_info(self, ret, info):
  263. assert is_namedtuple(ret)
  264. for value in ret:
  265. assert isinstance(value, int)
  266. assert value >= 0
  267. if WINDOWS:
  268. assert ret.peak_wset >= ret.wset
  269. assert ret.peak_paged_pool >= ret.paged_pool
  270. assert ret.peak_nonpaged_pool >= ret.nonpaged_pool
  271. assert ret.peak_pagefile >= ret.pagefile
  272. def memory_full_info(self, ret, info):
  273. assert is_namedtuple(ret)
  274. total = psutil.virtual_memory().total
  275. for name in ret._fields:
  276. value = getattr(ret, name)
  277. assert isinstance(value, int)
  278. assert value >= 0
  279. if LINUX or (OSX and name in {'vms', 'data'}):
  280. # On Linux there are processes (e.g. 'goa-daemon') whose
  281. # VMS is incredibly high for some reason.
  282. continue
  283. assert value <= total, name
  284. if LINUX:
  285. assert ret.pss >= ret.uss
  286. def open_files(self, ret, info):
  287. assert isinstance(ret, list)
  288. for f in ret:
  289. assert isinstance(f.fd, int)
  290. assert isinstance(f.path, str)
  291. assert f.path.strip() == f.path
  292. if WINDOWS:
  293. assert f.fd == -1
  294. elif LINUX:
  295. assert isinstance(f.position, int)
  296. assert isinstance(f.mode, str)
  297. assert isinstance(f.flags, int)
  298. assert f.position >= 0
  299. assert f.mode in {'r', 'w', 'a', 'r+', 'a+'}
  300. assert f.flags > 0
  301. elif BSD and not f.path:
  302. # XXX see: https://github.com/giampaolo/psutil/issues/595
  303. continue
  304. assert os.path.isabs(f.path), f
  305. try:
  306. st = os.stat(f.path)
  307. except FileNotFoundError:
  308. pass
  309. else:
  310. assert stat.S_ISREG(st.st_mode), f
  311. def num_fds(self, ret, info):
  312. assert isinstance(ret, int)
  313. assert ret >= 0
  314. def net_connections(self, ret, info):
  315. with create_sockets():
  316. assert len(ret) == len(set(ret))
  317. for conn in ret:
  318. assert is_namedtuple(conn)
  319. check_connection_ntuple(conn)
  320. def cwd(self, ret, info):
  321. assert isinstance(ret, str)
  322. assert ret.strip() == ret
  323. if ret:
  324. assert os.path.isabs(ret), ret
  325. try:
  326. st = os.stat(ret)
  327. except OSError as err:
  328. if WINDOWS and psutil._psplatform.is_permission_err(err):
  329. pass
  330. # directory has been removed in mean time
  331. elif err.errno != errno.ENOENT:
  332. raise
  333. else:
  334. assert stat.S_ISDIR(st.st_mode)
  335. def memory_percent(self, ret, info):
  336. assert isinstance(ret, float)
  337. assert 0 <= ret <= 100, ret
  338. def is_running(self, ret, info):
  339. assert isinstance(ret, bool)
  340. def cpu_affinity(self, ret, info):
  341. assert isinstance(ret, list)
  342. assert ret != []
  343. cpus = list(range(psutil.cpu_count()))
  344. for n in ret:
  345. assert isinstance(n, int)
  346. assert n in cpus
  347. def terminal(self, ret, info):
  348. assert isinstance(ret, (str, type(None)))
  349. if ret is not None:
  350. assert os.path.isabs(ret), ret
  351. assert os.path.exists(ret), ret
  352. def memory_maps(self, ret, info):
  353. for nt in ret:
  354. assert isinstance(nt.addr, str)
  355. assert isinstance(nt.perms, str)
  356. assert isinstance(nt.path, str)
  357. for fname in nt._fields:
  358. value = getattr(nt, fname)
  359. if fname == 'path':
  360. if value.startswith(("[", "anon_inode:")): # linux
  361. continue
  362. if BSD and value == "pvclock": # seen on FreeBSD
  363. continue
  364. assert os.path.isabs(nt.path), nt.path
  365. # commented as on Linux we might get
  366. # '/foo/bar (deleted)'
  367. # assert os.path.exists(nt.path), nt.path
  368. elif fname == 'addr':
  369. assert value, repr(value)
  370. elif fname == 'perms':
  371. if not WINDOWS:
  372. assert value, repr(value)
  373. else:
  374. assert isinstance(value, int)
  375. assert value >= 0
  376. def num_handles(self, ret, info):
  377. assert isinstance(ret, int)
  378. assert ret >= 0
  379. def nice(self, ret, info):
  380. assert isinstance(ret, int)
  381. if POSIX:
  382. assert -20 <= ret <= 20, ret
  383. else:
  384. priorities = [
  385. getattr(psutil, x)
  386. for x in dir(psutil)
  387. if x.endswith('_PRIORITY_CLASS')
  388. ]
  389. assert ret in priorities
  390. assert isinstance(ret, enum.IntEnum)
  391. def num_ctx_switches(self, ret, info):
  392. assert is_namedtuple(ret)
  393. for value in ret:
  394. assert isinstance(value, int)
  395. assert value >= 0
  396. def rlimit(self, ret, info):
  397. assert isinstance(ret, tuple)
  398. assert len(ret) == 2
  399. assert ret[0] >= -1
  400. assert ret[1] >= -1
  401. def environ(self, ret, info):
  402. assert isinstance(ret, dict)
  403. for k, v in ret.items():
  404. assert isinstance(k, str)
  405. assert isinstance(v, str)
  406. class TestPidsRange(PsutilTestCase):
  407. """Given pid_exists() return value for a range of PIDs which may or
  408. may not exist, make sure that psutil.Process() and psutil.pids()
  409. agree with pid_exists(). This guarantees that the 3 APIs are all
  410. consistent with each other. See:
  411. https://github.com/giampaolo/psutil/issues/2359
  412. XXX - Note about Windows: it turns out there are some "hidden" PIDs
  413. which are not returned by psutil.pids() and are also not revealed
  414. by taskmgr.exe and ProcessHacker, still they can be instantiated by
  415. psutil.Process() and queried. One of such PIDs is "conhost.exe".
  416. Running as_dict() for it reveals that some Process() APIs
  417. erroneously raise NoSuchProcess, so we know we have problem there.
  418. Let's ignore this for now, since it's quite a corner case (who even
  419. imagined hidden PIDs existed on Windows?).
  420. """
  421. def setUp(self):
  422. psutil._set_debug(False)
  423. def tearDown(self):
  424. psutil._set_debug(True)
  425. def test_it(self):
  426. def is_linux_tid(pid):
  427. try:
  428. f = open(f"/proc/{pid}/status", "rb") # noqa: SIM115
  429. except FileNotFoundError:
  430. return False
  431. else:
  432. with f:
  433. for line in f:
  434. if line.startswith(b"Tgid:"):
  435. tgid = int(line.split()[1])
  436. # If tgid and pid are different then we're
  437. # dealing with a process TID.
  438. return tgid != pid
  439. raise ValueError("'Tgid' line not found")
  440. def check(pid):
  441. # In case of failure retry up to 3 times in order to avoid
  442. # race conditions, especially when running in a CI
  443. # environment where PIDs may appear and disappear at any
  444. # time.
  445. x = 3
  446. while True:
  447. exists = psutil.pid_exists(pid)
  448. try:
  449. if exists:
  450. psutil.Process(pid)
  451. if not WINDOWS: # see docstring
  452. assert pid in psutil.pids()
  453. else:
  454. # On OpenBSD thread IDs can be instantiated,
  455. # and oneshot() succeeds, but other APIs fail
  456. # with EINVAL.
  457. if not OPENBSD:
  458. with pytest.raises(psutil.NoSuchProcess):
  459. psutil.Process(pid)
  460. if not WINDOWS: # see docstring
  461. assert pid not in psutil.pids()
  462. except (psutil.Error, AssertionError):
  463. x -= 1
  464. if x == 0:
  465. raise
  466. else:
  467. return
  468. for pid in range(1, 3000):
  469. if LINUX and is_linux_tid(pid):
  470. # On Linux a TID (thread ID) can be passed to the
  471. # Process class and is querable like a PID (process
  472. # ID). Skip it.
  473. continue
  474. with self.subTest(pid=pid):
  475. check(pid)