_psbsd.py 31 KB

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