_psbsd.py 31 KB

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