_psosx.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. """macOS platform implementation."""
  5. import errno
  6. import functools
  7. import os
  8. from collections import namedtuple
  9. from . import _common
  10. from . import _psposix
  11. from . import _psutil_osx as cext
  12. from . import _psutil_posix as cext_posix
  13. from ._common import AccessDenied
  14. from ._common import NoSuchProcess
  15. from ._common import ZombieProcess
  16. from ._common import conn_tmap
  17. from ._common import conn_to_ntuple
  18. from ._common import isfile_strict
  19. from ._common import memoize_when_activated
  20. from ._common import parse_environ_block
  21. from ._common import usage_percent
  22. __extra__all__ = []
  23. # =====================================================================
  24. # --- globals
  25. # =====================================================================
  26. PAGESIZE = cext_posix.getpagesize()
  27. AF_LINK = cext_posix.AF_LINK
  28. TCP_STATUSES = {
  29. cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
  30. cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
  31. cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
  32. cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
  33. cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
  34. cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
  35. cext.TCPS_CLOSED: _common.CONN_CLOSE,
  36. cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
  37. cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
  38. cext.TCPS_LISTEN: _common.CONN_LISTEN,
  39. cext.TCPS_CLOSING: _common.CONN_CLOSING,
  40. cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
  41. }
  42. PROC_STATUSES = {
  43. cext.SIDL: _common.STATUS_IDLE,
  44. cext.SRUN: _common.STATUS_RUNNING,
  45. cext.SSLEEP: _common.STATUS_SLEEPING,
  46. cext.SSTOP: _common.STATUS_STOPPED,
  47. cext.SZOMB: _common.STATUS_ZOMBIE,
  48. }
  49. kinfo_proc_map = dict(
  50. ppid=0,
  51. ruid=1,
  52. euid=2,
  53. suid=3,
  54. rgid=4,
  55. egid=5,
  56. sgid=6,
  57. ttynr=7,
  58. ctime=8,
  59. status=9,
  60. name=10,
  61. )
  62. pidtaskinfo_map = dict(
  63. cpuutime=0,
  64. cpustime=1,
  65. rss=2,
  66. vms=3,
  67. pfaults=4,
  68. pageins=5,
  69. numthreads=6,
  70. volctxsw=7,
  71. )
  72. # =====================================================================
  73. # --- named tuples
  74. # =====================================================================
  75. # fmt: off
  76. # psutil.cpu_times()
  77. scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle'])
  78. # psutil.virtual_memory()
  79. svmem = namedtuple(
  80. 'svmem', ['total', 'available', 'percent', 'used', 'free',
  81. 'active', 'inactive', 'wired'])
  82. # psutil.Process.memory_info()
  83. pmem = namedtuple('pmem', ['rss', 'vms', 'pfaults', 'pageins'])
  84. # psutil.Process.memory_full_info()
  85. pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
  86. # fmt: on
  87. # =====================================================================
  88. # --- memory
  89. # =====================================================================
  90. def virtual_memory():
  91. """System virtual memory as a namedtuple."""
  92. total, active, inactive, wired, free, speculative = cext.virtual_mem()
  93. # This is how Zabbix calculate avail and used mem:
  94. # https://github.com/zabbix/zabbix/blob/master/src/libs/zbxsysinfo/osx/memory.c
  95. # Also see: https://github.com/giampaolo/psutil/issues/1277
  96. avail = inactive + free
  97. used = active + wired
  98. # This is NOT how Zabbix calculates free mem but it matches "free"
  99. # cmdline utility.
  100. free -= speculative
  101. percent = usage_percent((total - avail), total, round_=1)
  102. return svmem(total, avail, percent, used, free, active, inactive, wired)
  103. def swap_memory():
  104. """Swap system memory as a (total, used, free, sin, sout) tuple."""
  105. total, used, free, sin, sout = cext.swap_mem()
  106. percent = usage_percent(used, total, round_=1)
  107. return _common.sswap(total, used, free, percent, sin, sout)
  108. # =====================================================================
  109. # --- CPU
  110. # =====================================================================
  111. def cpu_times():
  112. """Return system CPU times as a namedtuple."""
  113. user, nice, system, idle = cext.cpu_times()
  114. return scputimes(user, nice, system, idle)
  115. def per_cpu_times():
  116. """Return system CPU times as a named tuple."""
  117. ret = []
  118. for cpu_t in cext.per_cpu_times():
  119. user, nice, system, idle = cpu_t
  120. item = scputimes(user, nice, system, idle)
  121. ret.append(item)
  122. return ret
  123. def cpu_count_logical():
  124. """Return the number of logical CPUs in the system."""
  125. return cext.cpu_count_logical()
  126. def cpu_count_cores():
  127. """Return the number of CPU cores in the system."""
  128. return cext.cpu_count_cores()
  129. def cpu_stats():
  130. ctx_switches, interrupts, soft_interrupts, syscalls, _traps = (
  131. cext.cpu_stats()
  132. )
  133. return _common.scpustats(
  134. ctx_switches, interrupts, soft_interrupts, syscalls
  135. )
  136. def cpu_freq():
  137. """Return CPU frequency.
  138. On macOS per-cpu frequency is not supported.
  139. Also, the returned frequency never changes, see:
  140. https://arstechnica.com/civis/viewtopic.php?f=19&t=465002.
  141. """
  142. curr, min_, max_ = cext.cpu_freq()
  143. return [_common.scpufreq(curr, min_, max_)]
  144. # =====================================================================
  145. # --- disks
  146. # =====================================================================
  147. disk_usage = _psposix.disk_usage
  148. disk_io_counters = cext.disk_io_counters
  149. def disk_partitions(all=False):
  150. """Return mounted disk partitions as a list of namedtuples."""
  151. retlist = []
  152. partitions = cext.disk_partitions()
  153. for partition in partitions:
  154. device, mountpoint, fstype, opts = partition
  155. if device == 'none':
  156. device = ''
  157. if not all:
  158. if not os.path.isabs(device) or not os.path.exists(device):
  159. continue
  160. ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
  161. retlist.append(ntuple)
  162. return retlist
  163. # =====================================================================
  164. # --- sensors
  165. # =====================================================================
  166. def sensors_battery():
  167. """Return battery information."""
  168. try:
  169. percent, minsleft, power_plugged = cext.sensors_battery()
  170. except NotImplementedError:
  171. # no power source - return None according to interface
  172. return None
  173. power_plugged = power_plugged == 1
  174. if power_plugged:
  175. secsleft = _common.POWER_TIME_UNLIMITED
  176. elif minsleft == -1:
  177. secsleft = _common.POWER_TIME_UNKNOWN
  178. else:
  179. secsleft = minsleft * 60
  180. return _common.sbattery(percent, secsleft, power_plugged)
  181. # =====================================================================
  182. # --- network
  183. # =====================================================================
  184. net_io_counters = cext.net_io_counters
  185. net_if_addrs = cext_posix.net_if_addrs
  186. def net_connections(kind='inet'):
  187. """System-wide network connections."""
  188. # Note: on macOS this will fail with AccessDenied unless
  189. # the process is owned by root.
  190. ret = []
  191. for pid in pids():
  192. try:
  193. cons = Process(pid).net_connections(kind)
  194. except NoSuchProcess:
  195. continue
  196. else:
  197. if cons:
  198. for c in cons:
  199. c = list(c) + [pid]
  200. ret.append(_common.sconn(*c))
  201. return ret
  202. def net_if_stats():
  203. """Get NIC stats (isup, duplex, speed, mtu)."""
  204. names = net_io_counters().keys()
  205. ret = {}
  206. for name in names:
  207. try:
  208. mtu = cext_posix.net_if_mtu(name)
  209. flags = cext_posix.net_if_flags(name)
  210. duplex, speed = cext_posix.net_if_duplex_speed(name)
  211. except OSError as err:
  212. # https://github.com/giampaolo/psutil/issues/1279
  213. if err.errno != errno.ENODEV:
  214. raise
  215. else:
  216. if hasattr(_common, 'NicDuplex'):
  217. duplex = _common.NicDuplex(duplex)
  218. output_flags = ','.join(flags)
  219. isup = 'running' in flags
  220. ret[name] = _common.snicstats(
  221. isup, duplex, speed, mtu, output_flags
  222. )
  223. return ret
  224. # =====================================================================
  225. # --- other system functions
  226. # =====================================================================
  227. def boot_time():
  228. """The system boot time expressed in seconds since the epoch."""
  229. return cext.boot_time()
  230. def users():
  231. """Return currently connected users as a list of namedtuples."""
  232. retlist = []
  233. rawlist = cext.users()
  234. for item in rawlist:
  235. user, tty, hostname, tstamp, pid = item
  236. if tty == '~':
  237. continue # reboot or shutdown
  238. if not tstamp:
  239. continue
  240. nt = _common.suser(user, tty or None, hostname or None, tstamp, pid)
  241. retlist.append(nt)
  242. return retlist
  243. # =====================================================================
  244. # --- processes
  245. # =====================================================================
  246. def pids():
  247. ls = cext.pids()
  248. if 0 not in ls:
  249. # On certain macOS versions pids() C doesn't return PID 0 but
  250. # "ps" does and the process is querable via sysctl():
  251. # https://travis-ci.org/giampaolo/psutil/jobs/309619941
  252. try:
  253. Process(0).create_time()
  254. ls.insert(0, 0)
  255. except NoSuchProcess:
  256. pass
  257. except AccessDenied:
  258. ls.insert(0, 0)
  259. return ls
  260. pid_exists = _psposix.pid_exists
  261. def is_zombie(pid):
  262. try:
  263. st = cext.proc_kinfo_oneshot(pid)[kinfo_proc_map['status']]
  264. return st == cext.SZOMB
  265. except OSError:
  266. return False
  267. def wrap_exceptions(fun):
  268. """Decorator which translates bare OSError exceptions into
  269. NoSuchProcess and AccessDenied.
  270. """
  271. @functools.wraps(fun)
  272. def wrapper(self, *args, **kwargs):
  273. pid, ppid, name = self.pid, self._ppid, self._name
  274. try:
  275. return fun(self, *args, **kwargs)
  276. except ProcessLookupError as err:
  277. if is_zombie(pid):
  278. raise ZombieProcess(pid, name, ppid) from err
  279. raise NoSuchProcess(pid, name) from err
  280. except PermissionError as err:
  281. raise AccessDenied(pid, name) from err
  282. return wrapper
  283. class Process:
  284. """Wrapper class around underlying C implementation."""
  285. __slots__ = ["_cache", "_name", "_ppid", "pid"]
  286. def __init__(self, pid):
  287. self.pid = pid
  288. self._name = None
  289. self._ppid = None
  290. @wrap_exceptions
  291. @memoize_when_activated
  292. def _get_kinfo_proc(self):
  293. # Note: should work with all PIDs without permission issues.
  294. ret = cext.proc_kinfo_oneshot(self.pid)
  295. assert len(ret) == len(kinfo_proc_map)
  296. return ret
  297. @wrap_exceptions
  298. @memoize_when_activated
  299. def _get_pidtaskinfo(self):
  300. # Note: should work for PIDs owned by user only.
  301. ret = cext.proc_pidtaskinfo_oneshot(self.pid)
  302. assert len(ret) == len(pidtaskinfo_map)
  303. return ret
  304. def oneshot_enter(self):
  305. self._get_kinfo_proc.cache_activate(self)
  306. self._get_pidtaskinfo.cache_activate(self)
  307. def oneshot_exit(self):
  308. self._get_kinfo_proc.cache_deactivate(self)
  309. self._get_pidtaskinfo.cache_deactivate(self)
  310. @wrap_exceptions
  311. def name(self):
  312. name = self._get_kinfo_proc()[kinfo_proc_map['name']]
  313. return name if name is not None else cext.proc_name(self.pid)
  314. @wrap_exceptions
  315. def exe(self):
  316. return cext.proc_exe(self.pid)
  317. @wrap_exceptions
  318. def cmdline(self):
  319. return cext.proc_cmdline(self.pid)
  320. @wrap_exceptions
  321. def environ(self):
  322. return parse_environ_block(cext.proc_environ(self.pid))
  323. @wrap_exceptions
  324. def ppid(self):
  325. self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']]
  326. return self._ppid
  327. @wrap_exceptions
  328. def cwd(self):
  329. return cext.proc_cwd(self.pid)
  330. @wrap_exceptions
  331. def uids(self):
  332. rawtuple = self._get_kinfo_proc()
  333. return _common.puids(
  334. rawtuple[kinfo_proc_map['ruid']],
  335. rawtuple[kinfo_proc_map['euid']],
  336. rawtuple[kinfo_proc_map['suid']],
  337. )
  338. @wrap_exceptions
  339. def gids(self):
  340. rawtuple = self._get_kinfo_proc()
  341. return _common.puids(
  342. rawtuple[kinfo_proc_map['rgid']],
  343. rawtuple[kinfo_proc_map['egid']],
  344. rawtuple[kinfo_proc_map['sgid']],
  345. )
  346. @wrap_exceptions
  347. def terminal(self):
  348. tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']]
  349. tmap = _psposix.get_terminal_map()
  350. try:
  351. return tmap[tty_nr]
  352. except KeyError:
  353. return None
  354. @wrap_exceptions
  355. def memory_info(self):
  356. rawtuple = self._get_pidtaskinfo()
  357. return pmem(
  358. rawtuple[pidtaskinfo_map['rss']],
  359. rawtuple[pidtaskinfo_map['vms']],
  360. rawtuple[pidtaskinfo_map['pfaults']],
  361. rawtuple[pidtaskinfo_map['pageins']],
  362. )
  363. @wrap_exceptions
  364. def memory_full_info(self):
  365. basic_mem = self.memory_info()
  366. uss = cext.proc_memory_uss(self.pid)
  367. return pfullmem(*basic_mem + (uss,))
  368. @wrap_exceptions
  369. def cpu_times(self):
  370. rawtuple = self._get_pidtaskinfo()
  371. return _common.pcputimes(
  372. rawtuple[pidtaskinfo_map['cpuutime']],
  373. rawtuple[pidtaskinfo_map['cpustime']],
  374. # children user / system times are not retrievable (set to 0)
  375. 0.0,
  376. 0.0,
  377. )
  378. @wrap_exceptions
  379. def create_time(self):
  380. return self._get_kinfo_proc()[kinfo_proc_map['ctime']]
  381. @wrap_exceptions
  382. def num_ctx_switches(self):
  383. # Unvoluntary value seems not to be available;
  384. # getrusage() numbers seems to confirm this theory.
  385. # We set it to 0.
  386. vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']]
  387. return _common.pctxsw(vol, 0)
  388. @wrap_exceptions
  389. def num_threads(self):
  390. return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']]
  391. @wrap_exceptions
  392. def open_files(self):
  393. if self.pid == 0:
  394. return []
  395. files = []
  396. rawlist = cext.proc_open_files(self.pid)
  397. for path, fd in rawlist:
  398. if isfile_strict(path):
  399. ntuple = _common.popenfile(path, fd)
  400. files.append(ntuple)
  401. return files
  402. @wrap_exceptions
  403. def net_connections(self, kind='inet'):
  404. families, types = conn_tmap[kind]
  405. rawlist = cext.proc_net_connections(self.pid, families, types)
  406. ret = []
  407. for item in rawlist:
  408. fd, fam, type, laddr, raddr, status = item
  409. nt = conn_to_ntuple(
  410. fd, fam, type, laddr, raddr, status, TCP_STATUSES
  411. )
  412. ret.append(nt)
  413. return ret
  414. @wrap_exceptions
  415. def num_fds(self):
  416. if self.pid == 0:
  417. return 0
  418. return cext.proc_num_fds(self.pid)
  419. @wrap_exceptions
  420. def wait(self, timeout=None):
  421. return _psposix.wait_pid(self.pid, timeout, self._name)
  422. @wrap_exceptions
  423. def nice_get(self):
  424. return cext_posix.getpriority(self.pid)
  425. @wrap_exceptions
  426. def nice_set(self, value):
  427. return cext_posix.setpriority(self.pid, value)
  428. @wrap_exceptions
  429. def status(self):
  430. code = self._get_kinfo_proc()[kinfo_proc_map['status']]
  431. # XXX is '?' legit? (we're not supposed to return it anyway)
  432. return PROC_STATUSES.get(code, '?')
  433. @wrap_exceptions
  434. def threads(self):
  435. rawlist = cext.proc_threads(self.pid)
  436. retlist = []
  437. for thread_id, utime, stime in rawlist:
  438. ntuple = _common.pthread(thread_id, utime, stime)
  439. retlist.append(ntuple)
  440. return retlist