_psosx.py 16 KB

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