Team Ai
Datasetpublic

codekingpro/portable-devtools

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