_psbsd.py 30 KB

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