_psbsd.py 30 KB

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