Team Ai
Datasetpublic

codekingpro/portable-devtools

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