_psbsd.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. # Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
  2. # Use of this source code is governed by a BSD-style license that can be
  3. # found in the LICENSE file.
  4. """FreeBSD, OpenBSD and NetBSD platforms implementation."""
  5. import contextlib
  6. import errno
  7. import functools
  8. import os
  9. from collections import defaultdict
  10. from collections import namedtuple
  11. from xml.etree import ElementTree # noqa: ICN001
  12. from . import _common
  13. from . import _ntuples as ntp
  14. from . import _psposix
  15. from . import _psutil_bsd as cext
  16. from ._common import FREEBSD
  17. from ._common import NETBSD
  18. from ._common import OPENBSD
  19. from ._common import AccessDenied
  20. from ._common import NoSuchProcess
  21. from ._common import ZombieProcess
  22. from ._common import conn_tmap
  23. from ._common import conn_to_ntuple
  24. from ._common import debug
  25. from ._common import memoize
  26. from ._common import memoize_when_activated
  27. from ._common import usage_percent
  28. __extra__all__ = []
  29. # =====================================================================
  30. # --- globals
  31. # =====================================================================
  32. if FREEBSD:
  33. PROC_STATUSES = {
  34. cext.SIDL: _common.STATUS_IDLE,
  35. cext.SRUN: _common.STATUS_RUNNING,
  36. cext.SSLEEP: _common.STATUS_SLEEPING,
  37. cext.SSTOP: _common.STATUS_STOPPED,
  38. cext.SZOMB: _common.STATUS_ZOMBIE,
  39. cext.SWAIT: _common.STATUS_WAITING,
  40. cext.SLOCK: _common.STATUS_LOCKED,
  41. }
  42. elif OPENBSD:
  43. PROC_STATUSES = {
  44. cext.SIDL: _common.STATUS_IDLE,
  45. cext.SSLEEP: _common.STATUS_SLEEPING,
  46. cext.SSTOP: _common.STATUS_STOPPED,
  47. # According to /usr/include/sys/proc.h SZOMB is unused.
  48. # test_zombie_process() shows that SDEAD is the right
  49. # equivalent. Also it appears there's no equivalent of
  50. # psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE.
  51. # cext.SZOMB: _common.STATUS_ZOMBIE,
  52. cext.SDEAD: _common.STATUS_ZOMBIE,
  53. cext.SZOMB: _common.STATUS_ZOMBIE,
  54. # From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt
  55. # OpenBSD has SRUN and SONPROC: SRUN indicates that a process
  56. # is runnable but *not* yet running, i.e. is on a run queue.
  57. # SONPROC indicates that the process is actually executing on
  58. # a CPU, i.e. it is no longer on a run queue.
  59. # As such we'll map SRUN to STATUS_WAKING and SONPROC to
  60. # STATUS_RUNNING
  61. cext.SRUN: _common.STATUS_WAKING,
  62. cext.SONPROC: _common.STATUS_RUNNING,
  63. }
  64. elif NETBSD:
  65. PROC_STATUSES = {
  66. cext.SIDL: _common.STATUS_IDLE,
  67. cext.SSLEEP: _common.STATUS_SLEEPING,
  68. cext.SSTOP: _common.STATUS_STOPPED,
  69. cext.SZOMB: _common.STATUS_ZOMBIE,
  70. cext.SRUN: _common.STATUS_WAKING,
  71. cext.SONPROC: _common.STATUS_RUNNING,
  72. }
  73. TCP_STATUSES = {
  74. cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
  75. cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
  76. cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
  77. cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
  78. cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
  79. cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
  80. cext.TCPS_CLOSED: _common.CONN_CLOSE,
  81. cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
  82. cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
  83. cext.TCPS_LISTEN: _common.CONN_LISTEN,
  84. cext.TCPS_CLOSING: _common.CONN_CLOSING,
  85. cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
  86. }
  87. PAGESIZE = cext.getpagesize()
  88. AF_LINK = cext.AF_LINK
  89. HAS_PROC_NUM_THREADS = hasattr(cext, "proc_num_threads")
  90. kinfo_proc_map = dict(
  91. ppid=0,
  92. status=1,
  93. real_uid=2,
  94. effective_uid=3,
  95. saved_uid=4,
  96. real_gid=5,
  97. effective_gid=6,
  98. saved_gid=7,
  99. ttynr=8,
  100. create_time=9,
  101. ctx_switches_vol=10,
  102. ctx_switches_unvol=11,
  103. read_io_count=12,
  104. write_io_count=13,
  105. user_time=14,
  106. sys_time=15,
  107. ch_user_time=16,
  108. ch_sys_time=17,
  109. rss=18,
  110. vms=19,
  111. memtext=20,
  112. memdata=21,
  113. memstack=22,
  114. cpunum=23,
  115. name=24,
  116. )
  117. # =====================================================================
  118. # --- memory
  119. # =====================================================================
  120. def virtual_memory():
  121. mem = cext.virtual_mem()
  122. if NETBSD:
  123. total, free, active, inactive, wired, cached = mem
  124. # On NetBSD buffers and shared mem is determined via /proc.
  125. # The C ext set them to 0.
  126. with open('/proc/meminfo', 'rb') as f:
  127. for line in f:
  128. if line.startswith(b'Buffers:'):
  129. buffers = int(line.split()[1]) * 1024
  130. elif line.startswith(b'MemShared:'):
  131. shared = int(line.split()[1]) * 1024
  132. # Before avail was calculated as (inactive + cached + free),
  133. # same as zabbix, but it turned out it could exceed total (see
  134. # #2233), so zabbix seems to be wrong. Htop calculates it
  135. # differently, and the used value seem more realistic, so let's
  136. # match htop.
  137. # https://github.com/htop-dev/htop/blob/e7f447b/netbsd/NetBSDProcessList.c#L162
  138. # https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/netbsd/memory.c#L135
  139. used = active + wired
  140. avail = total - used
  141. else:
  142. total, free, active, inactive, wired, cached, buffers, shared = mem
  143. # matches freebsd-memory CLI:
  144. # * https://people.freebsd.org/~rse/dist/freebsd-memory
  145. # * https://www.cyberciti.biz/files/scripts/freebsd-memory.pl.txt
  146. # matches zabbix:
  147. # * https://github.com/zabbix/zabbix/blob/af5e0f8/src/libs/zbxsysinfo/freebsd/memory.c#L143
  148. avail = inactive + cached + free
  149. used = active + wired + cached
  150. percent = usage_percent((total - avail), total, round_=1)
  151. return ntp.svmem(
  152. total,
  153. avail,
  154. percent,
  155. used,
  156. free,
  157. active,
  158. inactive,
  159. buffers,
  160. cached,
  161. shared,
  162. wired,
  163. )
  164. def swap_memory():
  165. """System swap memory as (total, used, free, sin, sout) namedtuple."""
  166. total, used, free, sin, sout = cext.swap_mem()
  167. percent = usage_percent(used, total, round_=1)
  168. return ntp.sswap(total, used, free, percent, sin, sout)
  169. # malloc / heap functions (FreeBSD / NetBSD)
  170. if hasattr(cext, "heap_info"):
  171. heap_info = cext.heap_info
  172. heap_trim = cext.heap_trim
  173. # =====================================================================
  174. # --- CPU
  175. # =====================================================================
  176. def cpu_times():
  177. """Return system per-CPU times as a namedtuple."""
  178. user, nice, system, idle, irq = cext.cpu_times()
  179. return ntp.scputimes(user, nice, system, idle, irq)
  180. def per_cpu_times():
  181. """Return system CPU times as a namedtuple."""
  182. ret = []
  183. for cpu_t in cext.per_cpu_times():
  184. user, nice, system, idle, irq = cpu_t
  185. item = ntp.scputimes(user, nice, system, idle, irq)
  186. ret.append(item)
  187. return ret
  188. def cpu_count_logical():
  189. """Return the number of logical CPUs in the system."""
  190. return cext.cpu_count_logical()
  191. if OPENBSD or NETBSD:
  192. def cpu_count_cores():
  193. # OpenBSD and NetBSD do not implement this.
  194. return 1 if cpu_count_logical() == 1 else None
  195. else:
  196. def cpu_count_cores():
  197. """Return the number of CPU cores in the system."""
  198. # From the C module we'll get an XML string similar to this:
  199. # http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html
  200. # We may get None in case "sysctl kern.sched.topology_spec"
  201. # is not supported on this BSD version, in which case we'll mimic
  202. # os.cpu_count() and return None.
  203. ret = None
  204. s = cext.cpu_topology()
  205. if s is not None:
  206. # get rid of padding chars appended at the end of the string
  207. index = s.rfind("</groups>")
  208. if index != -1:
  209. s = s[: index + 9]
  210. root = ElementTree.fromstring(s)
  211. try:
  212. ret = len(root.findall('group/children/group/cpu')) or None
  213. finally:
  214. # needed otherwise it will memleak
  215. root.clear()
  216. if not ret:
  217. # If logical CPUs == 1 it's obvious we' have only 1 core.
  218. if cpu_count_logical() == 1:
  219. return 1
  220. return ret
  221. def cpu_stats():
  222. """Return various CPU stats as a named tuple."""
  223. if FREEBSD:
  224. # Note: the C ext is returning some metrics we are not exposing:
  225. # traps.
  226. ctxsw, intrs, soft_intrs, syscalls, _traps = cext.cpu_stats()
  227. elif NETBSD:
  228. # XXX
  229. # Note about intrs: the C extension returns 0. intrs
  230. # can be determined via /proc/stat; it has the same value as
  231. # soft_intrs thought so the kernel is faking it (?).
  232. #
  233. # Note about syscalls: the C extension always sets it to 0 (?).
  234. #
  235. # Note: the C ext is returning some metrics we are not exposing:
  236. # traps, faults and forks.
  237. ctxsw, intrs, soft_intrs, syscalls, _traps, _faults, _forks = (
  238. cext.cpu_stats()
  239. )
  240. with open('/proc/stat', 'rb') as f:
  241. for line in f:
  242. if line.startswith(b'intr'):
  243. intrs = int(line.split()[1])
  244. elif OPENBSD:
  245. # Note: the C ext is returning some metrics we are not exposing:
  246. # traps, faults and forks.
  247. ctxsw, intrs, soft_intrs, syscalls, _traps, _faults, _forks = (
  248. cext.cpu_stats()
  249. )
  250. return ntp.scpustats(ctxsw, intrs, soft_intrs, syscalls)
  251. if FREEBSD:
  252. def cpu_freq():
  253. """Return frequency metrics for CPUs. As of Dec 2018 only
  254. CPU 0 appears to be supported by FreeBSD and all other cores
  255. match the frequency of CPU 0.
  256. """
  257. ret = []
  258. num_cpus = cpu_count_logical()
  259. for cpu in range(num_cpus):
  260. try:
  261. current, available_freq = cext.cpu_freq(cpu)
  262. except NotImplementedError:
  263. continue
  264. if available_freq:
  265. try:
  266. min_freq = int(available_freq.split(" ")[-1].split("/")[0])
  267. except (IndexError, ValueError):
  268. min_freq = None
  269. try:
  270. max_freq = int(available_freq.split(" ")[0].split("/")[0])
  271. except (IndexError, ValueError):
  272. max_freq = None
  273. ret.append(ntp.scpufreq(current, min_freq, max_freq))
  274. return ret
  275. elif OPENBSD:
  276. def cpu_freq():
  277. curr = float(cext.cpu_freq())
  278. return [ntp.scpufreq(curr, 0.0, 0.0)]
  279. # =====================================================================
  280. # --- disks
  281. # =====================================================================
  282. def disk_partitions(all=False):
  283. """Return mounted disk partitions as a list of namedtuples.
  284. 'all' argument is ignored, see:
  285. https://github.com/giampaolo/psutil/issues/906.
  286. """
  287. retlist = []
  288. partitions = cext.disk_partitions()
  289. for partition in partitions:
  290. device, mountpoint, fstype, opts = partition
  291. ntuple = ntp.sdiskpart(device, mountpoint, fstype, opts)
  292. retlist.append(ntuple)
  293. return retlist
  294. disk_usage = _psposix.disk_usage
  295. disk_io_counters = cext.disk_io_counters
  296. # =====================================================================
  297. # --- network
  298. # =====================================================================
  299. net_io_counters = cext.net_io_counters
  300. net_if_addrs = cext.net_if_addrs
  301. def net_if_stats():
  302. """Get NIC stats (isup, duplex, speed, mtu)."""
  303. names = net_io_counters().keys()
  304. ret = {}
  305. for name in names:
  306. try:
  307. mtu = cext.net_if_mtu(name)
  308. flags = cext.net_if_flags(name)
  309. duplex, speed = cext.net_if_duplex_speed(name)
  310. except OSError as err:
  311. # https://github.com/giampaolo/psutil/issues/1279
  312. if err.errno != errno.ENODEV:
  313. raise
  314. else:
  315. if hasattr(_common, 'NicDuplex'):
  316. duplex = _common.NicDuplex(duplex)
  317. output_flags = ','.join(flags)
  318. isup = 'running' in flags
  319. ret[name] = ntp.snicstats(isup, duplex, speed, mtu, output_flags)
  320. return ret
  321. def net_connections(kind):
  322. """System-wide network connections."""
  323. families, types = conn_tmap[kind]
  324. ret = set()
  325. if OPENBSD:
  326. rawlist = cext.net_connections(-1, families, types)
  327. elif NETBSD:
  328. rawlist = cext.net_connections(-1, kind)
  329. else: # FreeBSD
  330. rawlist = cext.net_connections(families, types)
  331. for item in rawlist:
  332. fd, fam, type, laddr, raddr, status, pid = item
  333. nt = conn_to_ntuple(
  334. fd, fam, type, laddr, raddr, status, TCP_STATUSES, pid
  335. )
  336. ret.add(nt)
  337. return list(ret)
  338. # =====================================================================
  339. # --- sensors
  340. # =====================================================================
  341. if FREEBSD:
  342. def sensors_battery():
  343. """Return battery info."""
  344. try:
  345. percent, minsleft, power_plugged = cext.sensors_battery()
  346. except NotImplementedError:
  347. # See: https://github.com/giampaolo/psutil/issues/1074
  348. return None
  349. power_plugged = power_plugged == 1
  350. if power_plugged:
  351. secsleft = _common.POWER_TIME_UNLIMITED
  352. elif minsleft == -1:
  353. secsleft = _common.POWER_TIME_UNKNOWN
  354. else:
  355. secsleft = minsleft * 60
  356. return ntp.sbattery(percent, secsleft, power_plugged)
  357. def sensors_temperatures():
  358. """Return CPU cores temperatures if available, else an empty dict."""
  359. ret = defaultdict(list)
  360. num_cpus = cpu_count_logical()
  361. for cpu in range(num_cpus):
  362. try:
  363. current, high = cext.sensors_cpu_temperature(cpu)
  364. if high <= 0:
  365. high = None
  366. name = f"Core {cpu}"
  367. ret["coretemp"].append(ntp.shwtemp(name, current, high, high))
  368. except NotImplementedError:
  369. pass
  370. return ret
  371. # =====================================================================
  372. # --- other system functions
  373. # =====================================================================
  374. def boot_time():
  375. """The system boot time expressed in seconds since the epoch."""
  376. return cext.boot_time()
  377. if NETBSD:
  378. try:
  379. INIT_BOOT_TIME = boot_time()
  380. except Exception as err: # noqa: BLE001
  381. # Don't want to crash at import time.
  382. debug(f"ignoring exception on import: {err!r}")
  383. INIT_BOOT_TIME = 0
  384. def adjust_proc_create_time(ctime):
  385. """Account for system clock updates."""
  386. if INIT_BOOT_TIME == 0:
  387. return ctime
  388. diff = INIT_BOOT_TIME - boot_time()
  389. if diff == 0 or abs(diff) < 1:
  390. return ctime
  391. debug("system clock was updated; adjusting process create_time()")
  392. if diff < 0:
  393. return ctime - diff
  394. return ctime + diff
  395. def users():
  396. """Return currently connected users as a list of namedtuples."""
  397. retlist = []
  398. rawlist = cext.users()
  399. for item in rawlist:
  400. user, tty, hostname, tstamp, pid = item
  401. if tty == '~':
  402. continue # reboot or shutdown
  403. nt = ntp.suser(user, tty or None, hostname, tstamp, pid)
  404. retlist.append(nt)
  405. return retlist
  406. # =====================================================================
  407. # --- processes
  408. # =====================================================================
  409. @memoize
  410. def _pid_0_exists():
  411. try:
  412. Process(0).name()
  413. except NoSuchProcess:
  414. return False
  415. except AccessDenied:
  416. return True
  417. else:
  418. return True
  419. def pids():
  420. """Returns a list of PIDs currently running on the system."""
  421. ret = cext.pids()
  422. if OPENBSD and (0 not in ret) and _pid_0_exists():
  423. # On OpenBSD the kernel does not return PID 0 (neither does
  424. # ps) but it's actually querable (Process(0) will succeed).
  425. ret.insert(0, 0)
  426. return ret
  427. if NETBSD:
  428. def pid_exists(pid):
  429. exists = _psposix.pid_exists(pid)
  430. if not exists:
  431. # We do this because _psposix.pid_exists() lies in case of
  432. # zombie processes.
  433. return pid in pids()
  434. else:
  435. return True
  436. elif OPENBSD:
  437. def pid_exists(pid):
  438. exists = _psposix.pid_exists(pid)
  439. if not exists:
  440. return False
  441. else:
  442. # OpenBSD seems to be the only BSD platform where
  443. # _psposix.pid_exists() returns True for thread IDs (tids),
  444. # so we can't use it.
  445. return pid in pids()
  446. else: # FreeBSD
  447. pid_exists = _psposix.pid_exists
  448. def wrap_exceptions(fun):
  449. """Decorator which translates bare OSError exceptions into
  450. NoSuchProcess and AccessDenied.
  451. """
  452. @functools.wraps(fun)
  453. def wrapper(self, *args, **kwargs):
  454. pid, ppid, name = self.pid, self._ppid, self._name
  455. try:
  456. return fun(self, *args, **kwargs)
  457. except ProcessLookupError as err:
  458. if cext.proc_is_zombie(pid):
  459. raise ZombieProcess(pid, name, ppid) from err
  460. raise NoSuchProcess(pid, name) from err
  461. except PermissionError as err:
  462. raise AccessDenied(pid, name) from err
  463. except cext.ZombieProcessError as err:
  464. raise ZombieProcess(pid, name, ppid) from err
  465. except OSError as err:
  466. if pid == 0 and 0 in pids():
  467. raise AccessDenied(pid, name) from err
  468. raise err from None
  469. return wrapper
  470. @contextlib.contextmanager
  471. def wrap_exceptions_procfs(inst):
  472. """Same as above, for routines relying on reading /proc fs."""
  473. pid, name, ppid = inst.pid, inst._name, inst._ppid
  474. try:
  475. yield
  476. except (ProcessLookupError, FileNotFoundError) as err:
  477. # ENOENT (no such file or directory) gets raised on open().
  478. # ESRCH (no such process) can get raised on read() if
  479. # process is gone in meantime.
  480. if cext.proc_is_zombie(inst.pid):
  481. raise ZombieProcess(pid, name, ppid) from err
  482. else:
  483. raise NoSuchProcess(pid, name) from err
  484. except PermissionError as err:
  485. raise AccessDenied(pid, name) from err
  486. class Process:
  487. """Wrapper class around underlying C implementation."""
  488. __slots__ = ["_cache", "_name", "_ppid", "pid"]
  489. def __init__(self, pid):
  490. self.pid = pid
  491. self._name = None
  492. self._ppid = None
  493. def _assert_alive(self):
  494. """Raise NSP if the process disappeared on us."""
  495. # For those C function who do not raise NSP, possibly returning
  496. # incorrect or incomplete result.
  497. cext.proc_name(self.pid)
  498. @wrap_exceptions
  499. @memoize_when_activated
  500. def oneshot(self):
  501. """Retrieves multiple process info in one shot as a raw tuple."""
  502. ret = cext.proc_oneshot_info(self.pid)
  503. assert len(ret) == len(kinfo_proc_map)
  504. return ret
  505. def oneshot_enter(self):
  506. self.oneshot.cache_activate(self)
  507. def oneshot_exit(self):
  508. self.oneshot.cache_deactivate(self)
  509. @wrap_exceptions
  510. def name(self):
  511. name = self.oneshot()[kinfo_proc_map['name']]
  512. return name if name is not None else cext.proc_name(self.pid)
  513. @wrap_exceptions
  514. def exe(self):
  515. if FREEBSD:
  516. if self.pid == 0:
  517. return '' # else NSP
  518. return cext.proc_exe(self.pid)
  519. elif NETBSD:
  520. if self.pid == 0:
  521. # /proc/0 dir exists but /proc/0/exe doesn't
  522. return ""
  523. with wrap_exceptions_procfs(self):
  524. return os.readlink(f"/proc/{self.pid}/exe")
  525. else:
  526. # OpenBSD: exe cannot be determined; references:
  527. # https://chromium.googlesource.com/chromium/src/base/+/
  528. # master/base_paths_posix.cc
  529. # We try our best guess by using which against the first
  530. # cmdline arg (may return None).
  531. import shutil
  532. cmdline = self.cmdline()
  533. if cmdline:
  534. return shutil.which(cmdline[0]) or ""
  535. else:
  536. return ""
  537. @wrap_exceptions
  538. def cmdline(self):
  539. if OPENBSD and self.pid == 0:
  540. return [] # ...else it crashes
  541. elif NETBSD:
  542. # XXX - most of the times the underlying sysctl() call on
  543. # NetBSD and OpenBSD returns a truncated string. Also
  544. # /proc/pid/cmdline behaves the same so it looks like this
  545. # is a kernel bug.
  546. try:
  547. return cext.proc_cmdline(self.pid)
  548. except OSError as err:
  549. if err.errno == errno.EINVAL:
  550. pid, name, ppid = self.pid, self._name, self._ppid
  551. if cext.proc_is_zombie(self.pid):
  552. raise ZombieProcess(pid, name, ppid) from err
  553. if not pid_exists(self.pid):
  554. raise NoSuchProcess(pid, name, ppid) from err
  555. # XXX: this happens with unicode tests. It means the C
  556. # routine is unable to decode invalid unicode chars.
  557. debug(f"ignoring {err!r} and returning an empty list")
  558. return []
  559. else:
  560. raise
  561. else:
  562. return cext.proc_cmdline(self.pid)
  563. @wrap_exceptions
  564. def environ(self):
  565. return cext.proc_environ(self.pid)
  566. @wrap_exceptions
  567. def terminal(self):
  568. tty_nr = self.oneshot()[kinfo_proc_map['ttynr']]
  569. tmap = _psposix.get_terminal_map()
  570. try:
  571. return tmap[tty_nr]
  572. except KeyError:
  573. return None
  574. @wrap_exceptions
  575. def ppid(self):
  576. self._ppid = self.oneshot()[kinfo_proc_map['ppid']]
  577. return self._ppid
  578. @wrap_exceptions
  579. def uids(self):
  580. rawtuple = self.oneshot()
  581. return ntp.puids(
  582. rawtuple[kinfo_proc_map['real_uid']],
  583. rawtuple[kinfo_proc_map['effective_uid']],
  584. rawtuple[kinfo_proc_map['saved_uid']],
  585. )
  586. @wrap_exceptions
  587. def gids(self):
  588. rawtuple = self.oneshot()
  589. return ntp.pgids(
  590. rawtuple[kinfo_proc_map['real_gid']],
  591. rawtuple[kinfo_proc_map['effective_gid']],
  592. rawtuple[kinfo_proc_map['saved_gid']],
  593. )
  594. @wrap_exceptions
  595. def cpu_times(self):
  596. rawtuple = self.oneshot()
  597. return ntp.pcputimes(
  598. rawtuple[kinfo_proc_map['user_time']],
  599. rawtuple[kinfo_proc_map['sys_time']],
  600. rawtuple[kinfo_proc_map['ch_user_time']],
  601. rawtuple[kinfo_proc_map['ch_sys_time']],
  602. )
  603. if FREEBSD:
  604. @wrap_exceptions
  605. def cpu_num(self):
  606. return self.oneshot()[kinfo_proc_map['cpunum']]
  607. @wrap_exceptions
  608. def memory_info(self):
  609. rawtuple = self.oneshot()
  610. return ntp.pmem(
  611. rawtuple[kinfo_proc_map['rss']],
  612. rawtuple[kinfo_proc_map['vms']],
  613. rawtuple[kinfo_proc_map['memtext']],
  614. rawtuple[kinfo_proc_map['memdata']],
  615. rawtuple[kinfo_proc_map['memstack']],
  616. )
  617. memory_full_info = memory_info
  618. @wrap_exceptions
  619. def create_time(self, monotonic=False):
  620. ctime = self.oneshot()[kinfo_proc_map['create_time']]
  621. if NETBSD and not monotonic:
  622. # NetBSD: ctime subject to system clock updates.
  623. ctime = adjust_proc_create_time(ctime)
  624. return ctime
  625. @wrap_exceptions
  626. def num_threads(self):
  627. if HAS_PROC_NUM_THREADS:
  628. # FreeBSD / NetBSD
  629. return cext.proc_num_threads(self.pid)
  630. else:
  631. return len(self.threads())
  632. @wrap_exceptions
  633. def num_ctx_switches(self):
  634. rawtuple = self.oneshot()
  635. return ntp.pctxsw(
  636. rawtuple[kinfo_proc_map['ctx_switches_vol']],
  637. rawtuple[kinfo_proc_map['ctx_switches_unvol']],
  638. )
  639. @wrap_exceptions
  640. def threads(self):
  641. # Note: on OpenSBD this (/dev/mem) requires root access.
  642. rawlist = cext.proc_threads(self.pid)
  643. retlist = []
  644. for thread_id, utime, stime in rawlist:
  645. ntuple = ntp.pthread(thread_id, utime, stime)
  646. retlist.append(ntuple)
  647. if OPENBSD:
  648. self._assert_alive()
  649. return retlist
  650. @wrap_exceptions
  651. def net_connections(self, kind='inet'):
  652. families, types = conn_tmap[kind]
  653. ret = []
  654. if NETBSD:
  655. rawlist = cext.net_connections(self.pid, kind)
  656. elif OPENBSD:
  657. rawlist = cext.net_connections(self.pid, families, types)
  658. else:
  659. rawlist = cext.proc_net_connections(self.pid, families, types)
  660. for item in rawlist:
  661. fd, fam, type, laddr, raddr, status = item[:6]
  662. if FREEBSD:
  663. if (fam not in families) or (type not in types):
  664. continue
  665. nt = conn_to_ntuple(
  666. fd, fam, type, laddr, raddr, status, TCP_STATUSES
  667. )
  668. ret.append(nt)
  669. self._assert_alive()
  670. return ret
  671. @wrap_exceptions
  672. def wait(self, timeout=None):
  673. return _psposix.wait_pid(self.pid, timeout)
  674. @wrap_exceptions
  675. def nice_get(self):
  676. return cext.proc_priority_get(self.pid)
  677. @wrap_exceptions
  678. def nice_set(self, value):
  679. return cext.proc_priority_set(self.pid, value)
  680. @wrap_exceptions
  681. def status(self):
  682. code = self.oneshot()[kinfo_proc_map['status']]
  683. # XXX is '?' legit? (we're not supposed to return it anyway)
  684. return PROC_STATUSES.get(code, '?')
  685. @wrap_exceptions
  686. def io_counters(self):
  687. rawtuple = self.oneshot()
  688. return ntp.pio(
  689. rawtuple[kinfo_proc_map['read_io_count']],
  690. rawtuple[kinfo_proc_map['write_io_count']],
  691. -1,
  692. -1,
  693. )
  694. @wrap_exceptions
  695. def cwd(self):
  696. """Return process current working directory."""
  697. # sometimes we get an empty string, in which case we turn
  698. # it into None
  699. if OPENBSD and self.pid == 0:
  700. return "" # ...else it would raise EINVAL
  701. return cext.proc_cwd(self.pid)
  702. nt_mmap_grouped = namedtuple(
  703. 'mmap', 'path rss, private, ref_count, shadow_count'
  704. )
  705. nt_mmap_ext = namedtuple(
  706. 'mmap', 'addr, perms path rss, private, ref_count, shadow_count'
  707. )
  708. @wrap_exceptions
  709. def open_files(self):
  710. """Return files opened by process as a list of namedtuples."""
  711. rawlist = cext.proc_open_files(self.pid)
  712. return [ntp.popenfile(path, fd) for path, fd in rawlist]
  713. @wrap_exceptions
  714. def num_fds(self):
  715. """Return the number of file descriptors opened by this process."""
  716. ret = cext.proc_num_fds(self.pid)
  717. if NETBSD:
  718. self._assert_alive()
  719. return ret
  720. # --- FreeBSD only APIs
  721. if FREEBSD:
  722. @wrap_exceptions
  723. def cpu_affinity_get(self):
  724. return cext.proc_cpu_affinity_get(self.pid)
  725. @wrap_exceptions
  726. def cpu_affinity_set(self, cpus):
  727. # Pre-emptively check if CPUs are valid because the C
  728. # function has a weird behavior in case of invalid CPUs,
  729. # see: https://github.com/giampaolo/psutil/issues/586
  730. allcpus = set(range(len(per_cpu_times())))
  731. for cpu in cpus:
  732. if cpu not in allcpus:
  733. msg = f"invalid CPU {cpu!r} (choose between {allcpus})"
  734. raise ValueError(msg)
  735. try:
  736. cext.proc_cpu_affinity_set(self.pid, cpus)
  737. except OSError as err:
  738. # 'man cpuset_setaffinity' about EDEADLK:
  739. # <<the call would leave a thread without a valid CPU to run
  740. # on because the set does not overlap with the thread's
  741. # anonymous mask>>
  742. if err.errno in {errno.EINVAL, errno.EDEADLK}:
  743. for cpu in cpus:
  744. if cpu not in allcpus:
  745. msg = (
  746. f"invalid CPU {cpu!r} (choose between"
  747. f" {allcpus})"
  748. )
  749. raise ValueError(msg) from err
  750. raise
  751. @wrap_exceptions
  752. def memory_maps(self):
  753. return cext.proc_memory_maps(self.pid)
  754. @wrap_exceptions
  755. def rlimit(self, resource, limits=None):
  756. if limits is None:
  757. return cext.proc_getrlimit(self.pid, resource)
  758. else:
  759. if len(limits) != 2:
  760. msg = (
  761. "second argument must be a (soft, hard) tuple, got"
  762. f" {limits!r}"
  763. )
  764. raise ValueError(msg)
  765. soft, hard = limits
  766. return cext.proc_setrlimit(self.pid, resource, soft, hard)