Current File : /home/mmdealscpanel/yummmdeals.com/psutil.tar
_exceptions.py000064400000005701150466730530007452 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.


class Error(Exception):
    """Base exception class. All other psutil exceptions inherit
    from this one.
    """

    def __init__(self, msg=""):
        Exception.__init__(self, msg)
        self.msg = msg

    def __repr__(self):
        ret = "psutil.%s %s" % (self.__class__.__name__, self.msg)
        return ret.strip()

    __str__ = __repr__


class NoSuchProcess(Error):
    """Exception raised when a process with a certain PID doesn't
    or no longer exists.
    """

    def __init__(self, pid, name=None, msg=None):
        Error.__init__(self, msg)
        self.pid = pid
        self.name = name
        self.msg = msg
        if msg is None:
            if name:
                details = "(pid=%s, name=%s)" % (self.pid, repr(self.name))
            else:
                details = "(pid=%s)" % self.pid
            self.msg = "process no longer exists " + details


class ZombieProcess(NoSuchProcess):
    """Exception raised when querying a zombie process. This is
    raised on OSX, BSD and Solaris only, and not always: depending
    on the query the OS may be able to succeed anyway.
    On Linux all zombie processes are querable (hence this is never
    raised). Windows doesn't have zombie processes.
    """

    def __init__(self, pid, name=None, ppid=None, msg=None):
        NoSuchProcess.__init__(self, msg)
        self.pid = pid
        self.ppid = ppid
        self.name = name
        self.msg = msg
        if msg is None:
            args = ["pid=%s" % pid]
            if name:
                args.append("name=%s" % repr(self.name))
            if ppid:
                args.append("ppid=%s" % self.ppid)
            details = "(%s)" % ", ".join(args)
            self.msg = "process still exists but it's a zombie " + details


class AccessDenied(Error):
    """Exception raised when permission to perform an action is denied."""

    def __init__(self, pid=None, name=None, msg=None):
        Error.__init__(self, msg)
        self.pid = pid
        self.name = name
        self.msg = msg
        if msg is None:
            if (pid is not None) and (name is not None):
                self.msg = "(pid=%s, name=%s)" % (pid, repr(name))
            elif (pid is not None):
                self.msg = "(pid=%s)" % self.pid
            else:
                self.msg = ""


class TimeoutExpired(Error):
    """Raised on Process.wait(timeout) if timeout expires and process
    is still alive.
    """

    def __init__(self, seconds, pid=None, name=None):
        Error.__init__(self, "timeout after %s seconds" % seconds)
        self.seconds = seconds
        self.pid = pid
        self.name = name
        if (pid is not None) and (name is not None):
            self.msg += " (pid=%s, name=%s)" % (pid, repr(name))
        elif (pid is not None):
            self.msg += " (pid=%s)" % self.pid
__init__.py000064400000245775150466730530006712 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""psutil is a cross-platform library for retrieving information on
running processes and system utilization (CPU, memory, disks, network,
sensors) in Python. Supported platforms:

 - Linux
 - Windows
 - OSX
 - FreeBSD
 - OpenBSD
 - NetBSD
 - Sun Solaris
 - AIX

Works with Python versions from 2.6 to 3.X.
"""

from __future__ import division

import collections
import contextlib
import datetime
import errno
import functools
import os
import signal
import subprocess
import sys
import time
import traceback
try:
    import pwd
except ImportError:
    pwd = None

from . import _common
from ._common import deprecated_method
from ._common import memoize
from ._common import memoize_when_activated
from ._common import wrap_numbers as _wrap_numbers
from ._compat import callable
from ._compat import long
from ._compat import PY3 as _PY3

from ._common import STATUS_DEAD
from ._common import STATUS_DISK_SLEEP
from ._common import STATUS_IDLE  # bsd
from ._common import STATUS_LOCKED
from ._common import STATUS_RUNNING
from ._common import STATUS_SLEEPING
from ._common import STATUS_STOPPED
from ._common import STATUS_TRACING_STOP
from ._common import STATUS_WAITING  # bsd
from ._common import STATUS_WAKING
from ._common import STATUS_ZOMBIE

from ._common import CONN_CLOSE
from ._common import CONN_CLOSE_WAIT
from ._common import CONN_CLOSING
from ._common import CONN_ESTABLISHED
from ._common import CONN_FIN_WAIT1
from ._common import CONN_FIN_WAIT2
from ._common import CONN_LAST_ACK
from ._common import CONN_LISTEN
from ._common import CONN_NONE
from ._common import CONN_SYN_RECV
from ._common import CONN_SYN_SENT
from ._common import CONN_TIME_WAIT
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN

from ._common import AIX
from ._common import BSD
from ._common import FREEBSD  # NOQA
from ._common import LINUX
from ._common import NETBSD  # NOQA
from ._common import OPENBSD  # NOQA
from ._common import OSX
from ._common import POSIX  # NOQA
from ._common import SUNOS
from ._common import WINDOWS

from ._exceptions import AccessDenied
from ._exceptions import Error
from ._exceptions import NoSuchProcess
from ._exceptions import TimeoutExpired
from ._exceptions import ZombieProcess

if LINUX:
    # This is public API and it will be retrieved from _pslinux.py
    # via sys.modules.
    PROCFS_PATH = "/proc"

    from . import _pslinux as _psplatform

    from ._pslinux import IOPRIO_CLASS_BE  # NOQA
    from ._pslinux import IOPRIO_CLASS_IDLE  # NOQA
    from ._pslinux import IOPRIO_CLASS_NONE  # NOQA
    from ._pslinux import IOPRIO_CLASS_RT  # NOQA
    # Linux >= 2.6.36
    if _psplatform.HAS_PRLIMIT:
        from ._psutil_linux import RLIM_INFINITY  # NOQA
        from ._psutil_linux import RLIMIT_AS  # NOQA
        from ._psutil_linux import RLIMIT_CORE  # NOQA
        from ._psutil_linux import RLIMIT_CPU  # NOQA
        from ._psutil_linux import RLIMIT_DATA  # NOQA
        from ._psutil_linux import RLIMIT_FSIZE  # NOQA
        from ._psutil_linux import RLIMIT_LOCKS  # NOQA
        from ._psutil_linux import RLIMIT_MEMLOCK  # NOQA
        from ._psutil_linux import RLIMIT_NOFILE  # NOQA
        from ._psutil_linux import RLIMIT_NPROC  # NOQA
        from ._psutil_linux import RLIMIT_RSS  # NOQA
        from ._psutil_linux import RLIMIT_STACK  # NOQA
        # Kinda ugly but considerably faster than using hasattr() and
        # setattr() against the module object (we are at import time:
        # speed matters).
        from . import _psutil_linux
        try:
            RLIMIT_MSGQUEUE = _psutil_linux.RLIMIT_MSGQUEUE
        except AttributeError:
            pass
        try:
            RLIMIT_NICE = _psutil_linux.RLIMIT_NICE
        except AttributeError:
            pass
        try:
            RLIMIT_RTPRIO = _psutil_linux.RLIMIT_RTPRIO
        except AttributeError:
            pass
        try:
            RLIMIT_RTTIME = _psutil_linux.RLIMIT_RTTIME
        except AttributeError:
            pass
        try:
            RLIMIT_SIGPENDING = _psutil_linux.RLIMIT_SIGPENDING
        except AttributeError:
            pass

elif WINDOWS:
    from . import _pswindows as _psplatform
    from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS  # NOQA
    from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS  # NOQA
    from ._psutil_windows import HIGH_PRIORITY_CLASS  # NOQA
    from ._psutil_windows import IDLE_PRIORITY_CLASS  # NOQA
    from ._psutil_windows import NORMAL_PRIORITY_CLASS  # NOQA
    from ._psutil_windows import REALTIME_PRIORITY_CLASS  # NOQA
    from ._pswindows import CONN_DELETE_TCB  # NOQA

elif OSX:
    from . import _psosx as _psplatform

elif BSD:
    from . import _psbsd as _psplatform

elif SUNOS:
    from . import _pssunos as _psplatform
    from ._pssunos import CONN_BOUND  # NOQA
    from ._pssunos import CONN_IDLE  # NOQA

    # This is public writable API which is read from _pslinux.py and
    # _pssunos.py via sys.modules.
    PROCFS_PATH = "/proc"

elif AIX:
    from . import _psaix as _psplatform

    # This is public API and it will be retrieved from _pslinux.py
    # via sys.modules.
    PROCFS_PATH = "/proc"

else:  # pragma: no cover
    raise NotImplementedError('platform %s is not supported' % sys.platform)


__all__ = [
    # exceptions
    "Error", "NoSuchProcess", "ZombieProcess", "AccessDenied",
    "TimeoutExpired",

    # constants
    "version_info", "__version__",

    "STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
    "STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
    "STATUS_WAKING", "STATUS_LOCKED", "STATUS_WAITING", "STATUS_LOCKED",

    "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
    "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
    "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", "CONN_NONE",

    "AF_LINK",

    "NIC_DUPLEX_FULL", "NIC_DUPLEX_HALF", "NIC_DUPLEX_UNKNOWN",

    "POWER_TIME_UNKNOWN", "POWER_TIME_UNLIMITED",

    "BSD", "FREEBSD", "LINUX", "NETBSD", "OPENBSD", "OSX", "POSIX", "SUNOS",
    "WINDOWS", "AIX",

    # classes
    "Process", "Popen",

    # functions
    "pid_exists", "pids", "process_iter", "wait_procs",             # proc
    "virtual_memory", "swap_memory",                                # memory
    "cpu_times", "cpu_percent", "cpu_times_percent", "cpu_count",   # cpu
    "cpu_stats",  # "cpu_freq",
    "net_io_counters", "net_connections", "net_if_addrs",           # network
    "net_if_stats",
    "disk_io_counters", "disk_partitions", "disk_usage",            # disk
    # "sensors_temperatures", "sensors_battery", "sensors_fans"     # sensors
    "users", "boot_time",                                           # others
]
__all__.extend(_psplatform.__extra__all__)
__author__ = "Giampaolo Rodola'"
__version__ = "5.4.3"
version_info = tuple([int(num) for num in __version__.split('.')])
AF_LINK = _psplatform.AF_LINK
POWER_TIME_UNLIMITED = _common.POWER_TIME_UNLIMITED
POWER_TIME_UNKNOWN = _common.POWER_TIME_UNKNOWN
_TOTAL_PHYMEM = None
_timer = getattr(time, 'monotonic', time.time)


# Sanity check in case the user messed up with psutil installation
# or did something weird with sys.path. In this case we might end
# up importing a python module using a C extension module which
# was compiled for a different version of psutil.
# We want to prevent that by failing sooner rather than later.
# See: https://github.com/giampaolo/psutil/issues/564
if (int(__version__.replace('.', '')) !=
        getattr(_psplatform.cext, 'version', None)):
    msg = "version conflict: %r C extension module was built for another " \
          "version of psutil" % getattr(_psplatform.cext, "__file__")
    if hasattr(_psplatform.cext, 'version'):
        msg += " (%s instead of %s)" % (
            '.'.join([x for x in str(_psplatform.cext.version)]), __version__)
    else:
        msg += " (different than %s)" % __version__
    msg += "; you may try to 'pip uninstall psutil', manually remove %s" % (
        getattr(_psplatform.cext, "__file__",
                "the existing psutil install directory"))
    msg += " or clean the virtual env somehow, then reinstall"
    raise ImportError(msg)


# =====================================================================
# --- Utils
# =====================================================================


if hasattr(_psplatform, 'ppid_map'):
    # Faster version (Windows and Linux).
    _ppid_map = _psplatform.ppid_map
else:
    def _ppid_map():
        """Return a {pid: ppid, ...} dict for all running processes in
        one shot. Used to speed up Process.children().
        """
        ret = {}
        for pid in pids():
            try:
                proc = _psplatform.Process(pid)
                ppid = proc.ppid()
            except (NoSuchProcess, AccessDenied):
                # Note: AccessDenied is unlikely to happen.
                pass
            else:
                ret[pid] = ppid
        return ret


def _assert_pid_not_reused(fun):
    """Decorator which raises NoSuchProcess in case a process is no
    longer running or its PID has been reused.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        if not self.is_running():
            raise NoSuchProcess(self.pid, self._name)
        return fun(self, *args, **kwargs)
    return wrapper


def _pprint_secs(secs):
    """Format seconds in a human readable form."""
    now = time.time()
    secs_ago = int(now - secs)
    if secs_ago < 60 * 60 * 24:
        fmt = "%H:%M:%S"
    else:
        fmt = "%Y-%m-%d %H:%M:%S"
    return datetime.datetime.fromtimestamp(secs).strftime(fmt)


# =====================================================================
# --- Process class
# =====================================================================


class Process(object):
    """Represents an OS process with the given PID.
    If PID is omitted current process PID (os.getpid()) is used.
    Raise NoSuchProcess if PID does not exist.

    Note that most of the methods of this class do not make sure
    the PID of the process being queried has been reused over time.
    That means you might end up retrieving an information referring
    to another process in case the original one this instance
    refers to is gone in the meantime.

    The only exceptions for which process identity is pre-emptively
    checked and guaranteed are:

     - parent()
     - children()
     - nice() (set)
     - ionice() (set)
     - rlimit() (set)
     - cpu_affinity (set)
     - suspend()
     - resume()
     - send_signal()
     - terminate()
     - kill()

    To prevent this problem for all other methods you can:
     - use is_running() before querying the process
     - if you're continuously iterating over a set of Process
       instances use process_iter() which pre-emptively checks
     process identity for every yielded instance
    """

    def __init__(self, pid=None):
        self._init(pid)

    def _init(self, pid, _ignore_nsp=False):
        if pid is None:
            pid = os.getpid()
        else:
            if not _PY3 and not isinstance(pid, (int, long)):
                raise TypeError('pid must be an integer (got %r)' % pid)
            if pid < 0:
                raise ValueError('pid must be a positive integer (got %s)'
                                 % pid)
        self._pid = pid
        self._name = None
        self._exe = None
        self._create_time = None
        self._gone = False
        self._hash = None
        self._oneshot_inctx = False
        # used for caching on Windows only (on POSIX ppid may change)
        self._ppid = None
        # platform-specific modules define an _psplatform.Process
        # implementation class
        self._proc = _psplatform.Process(pid)
        self._last_sys_cpu_times = None
        self._last_proc_cpu_times = None
        # cache creation time for later use in is_running() method
        try:
            self.create_time()
        except AccessDenied:
            # We should never get here as AFAIK we're able to get
            # process creation time on all platforms even as a
            # limited user.
            pass
        except ZombieProcess:
            # Zombies can still be queried by this class (although
            # not always) and pids() return them so just go on.
            pass
        except NoSuchProcess:
            if not _ignore_nsp:
                msg = 'no process found with pid %s' % pid
                raise NoSuchProcess(pid, None, msg)
            else:
                self._gone = True
        # This pair is supposed to indentify a Process instance
        # univocally over time (the PID alone is not enough as
        # it might refer to a process whose PID has been reused).
        # This will be used later in __eq__() and is_running().
        self._ident = (self.pid, self._create_time)

    def __str__(self):
        try:
            info = collections.OrderedDict()
        except AttributeError:
            info = {}  # Python 2.6
        info["pid"] = self.pid
        try:
            info["name"] = self.name()
            if self._create_time:
                info['started'] = _pprint_secs(self._create_time)
        except ZombieProcess:
            info["status"] = "zombie"
        except NoSuchProcess:
            info["status"] = "terminated"
        except AccessDenied:
            pass
        return "%s.%s(%s)" % (
            self.__class__.__module__,
            self.__class__.__name__,
            ", ".join(["%s=%r" % (k, v) for k, v in info.items()]))

    __repr__ = __str__

    def __eq__(self, other):
        # Test for equality with another Process object based
        # on PID and creation time.
        if not isinstance(other, Process):
            return NotImplemented
        return self._ident == other._ident

    def __ne__(self, other):
        return not self == other

    def __hash__(self):
        if self._hash is None:
            self._hash = hash(self._ident)
        return self._hash

    @property
    def pid(self):
        """The process PID."""
        return self._pid

    # --- utility methods

    @contextlib.contextmanager
    def oneshot(self):
        """Utility context manager which considerably speeds up the
        retrieval of multiple process information at the same time.

        Internally different process info (e.g. name, ppid, uids,
        gids, ...) may be fetched by using the same routine, but
        only one information is returned and the others are discarded.
        When using this context manager the internal routine is
        executed once (in the example below on name()) and the
        other info are cached.

        The cache is cleared when exiting the context manager block.
        The advice is to use this every time you retrieve more than
        one information about the process. If you're lucky, you'll
        get a hell of a speedup.

        >>> import psutil
        >>> p = psutil.Process()
        >>> with p.oneshot():
        ...     p.name()  # collect multiple info
        ...     p.cpu_times()  # return cached value
        ...     p.cpu_percent()  # return cached value
        ...     p.create_time()  # return cached value
        ...
        >>>
        """
        if self._oneshot_inctx:
            # NOOP: this covers the use case where the user enters the
            # context twice. Since as_dict() internally uses oneshot()
            # I expect that the code below will be a pretty common
            # "mistake" that the user will make, so let's guard
            # against that:
            #
            # >>> with p.oneshot():
            # ...    p.as_dict()
            # ...
            yield
        else:
            self._oneshot_inctx = True
            try:
                # cached in case cpu_percent() is used
                self.cpu_times.cache_activate()
                # cached in case memory_percent() is used
                self.memory_info.cache_activate()
                # cached in case parent() is used
                self.ppid.cache_activate()
                # cached in case username() is used
                if POSIX:
                    self.uids.cache_activate()
                # specific implementation cache
                self._proc.oneshot_enter()
                yield
            finally:
                self.cpu_times.cache_deactivate()
                self.memory_info.cache_deactivate()
                self.ppid.cache_deactivate()
                if POSIX:
                    self.uids.cache_deactivate()
                self._proc.oneshot_exit()
                self._oneshot_inctx = False

    def as_dict(self, attrs=None, ad_value=None):
        """Utility method returning process information as a
        hashable dictionary.
        If *attrs* is specified it must be a list of strings
        reflecting available Process class' attribute names
        (e.g. ['cpu_times', 'name']) else all public (read
        only) attributes are assumed.
        *ad_value* is the value which gets assigned in case
        AccessDenied or ZombieProcess exception is raised when
        retrieving that particular process information.
        """
        valid_names = _as_dict_attrnames
        if attrs is not None:
            if not isinstance(attrs, (list, tuple, set, frozenset)):
                raise TypeError("invalid attrs type %s" % type(attrs))
            attrs = set(attrs)
            invalid_names = attrs - valid_names
            if invalid_names:
                raise ValueError("invalid attr name%s %s" % (
                    "s" if len(invalid_names) > 1 else "",
                    ", ".join(map(repr, invalid_names))))

        retdict = dict()
        ls = attrs or valid_names
        with self.oneshot():
            for name in ls:
                try:
                    if name == 'pid':
                        ret = self.pid
                    else:
                        meth = getattr(self, name)
                        ret = meth()
                except (AccessDenied, ZombieProcess):
                    ret = ad_value
                except NotImplementedError:
                    # in case of not implemented functionality (may happen
                    # on old or exotic systems) we want to crash only if
                    # the user explicitly asked for that particular attr
                    if attrs:
                        raise
                    continue
                retdict[name] = ret
        return retdict

    def parent(self):
        """Return the parent process as a Process object pre-emptively
        checking whether PID has been reused.
        If no parent is known return None.
        """
        ppid = self.ppid()
        if ppid is not None:
            ctime = self.create_time()
            try:
                parent = Process(ppid)
                if parent.create_time() <= ctime:
                    return parent
                # ...else ppid has been reused by another process
            except NoSuchProcess:
                pass

    def is_running(self):
        """Return whether this process is running.
        It also checks if PID has been reused by another process in
        which case return False.
        """
        if self._gone:
            return False
        try:
            # Checking if PID is alive is not enough as the PID might
            # have been reused by another process: we also want to
            # verify process identity.
            # Process identity / uniqueness over time is guaranteed by
            # (PID + creation time) and that is verified in __eq__.
            return self == Process(self.pid)
        except ZombieProcess:
            # We should never get here as it's already handled in
            # Process.__init__; here just for extra safety.
            return True
        except NoSuchProcess:
            self._gone = True
            return False

    # --- actual API

    @memoize_when_activated
    def ppid(self):
        """The process parent PID.
        On Windows the return value is cached after first call.
        """
        # On POSIX we don't want to cache the ppid as it may unexpectedly
        # change to 1 (init) in case this process turns into a zombie:
        # https://github.com/giampaolo/psutil/issues/321
        # http://stackoverflow.com/questions/356722/

        # XXX should we check creation time here rather than in
        # Process.parent()?
        if POSIX:
            return self._proc.ppid()
        else:  # pragma: no cover
            self._ppid = self._ppid or self._proc.ppid()
            return self._ppid

    def name(self):
        """The process name. The return value is cached after first call."""
        # Process name is only cached on Windows as on POSIX it may
        # change, see:
        # https://github.com/giampaolo/psutil/issues/692
        if WINDOWS and self._name is not None:
            return self._name
        name = self._proc.name()
        if POSIX and len(name) >= 15:
            # On UNIX the name gets truncated to the first 15 characters.
            # If it matches the first part of the cmdline we return that
            # one instead because it's usually more explicative.
            # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon".
            try:
                cmdline = self.cmdline()
            except AccessDenied:
                pass
            else:
                if cmdline:
                    extended_name = os.path.basename(cmdline[0])
                    if extended_name.startswith(name):
                        name = extended_name
        self._name = name
        self._proc._name = name
        return name

    def exe(self):
        """The process executable as an absolute path.
        May also be an empty string.
        The return value is cached after first call.
        """
        def guess_it(fallback):
            # try to guess exe from cmdline[0] in absence of a native
            # exe representation
            cmdline = self.cmdline()
            if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
                exe = cmdline[0]  # the possible exe
                # Attempt to guess only in case of an absolute path.
                # It is not safe otherwise as the process might have
                # changed cwd.
                if (os.path.isabs(exe) and
                        os.path.isfile(exe) and
                        os.access(exe, os.X_OK)):
                    return exe
            if isinstance(fallback, AccessDenied):
                raise fallback
            return fallback

        if self._exe is None:
            try:
                exe = self._proc.exe()
            except AccessDenied as err:
                return guess_it(fallback=err)
            else:
                if not exe:
                    # underlying implementation can legitimately return an
                    # empty string; if that's the case we don't want to
                    # raise AD while guessing from the cmdline
                    try:
                        exe = guess_it(fallback=exe)
                    except AccessDenied:
                        pass
                self._exe = exe
        return self._exe

    def cmdline(self):
        """The command line this process has been called with."""
        return self._proc.cmdline()

    def status(self):
        """The process current status as a STATUS_* constant."""
        try:
            return self._proc.status()
        except ZombieProcess:
            return STATUS_ZOMBIE

    def username(self):
        """The name of the user that owns the process.
        On UNIX this is calculated by using *real* process uid.
        """
        if POSIX:
            if pwd is None:
                # might happen if python was installed from sources
                raise ImportError(
                    "requires pwd module shipped with standard python")
            real_uid = self.uids().real
            try:
                return pwd.getpwuid(real_uid).pw_name
            except KeyError:
                # the uid can't be resolved by the system
                return str(real_uid)
        else:
            return self._proc.username()

    def create_time(self):
        """The process creation time as a floating point number
        expressed in seconds since the epoch, in UTC.
        The return value is cached after first call.
        """
        if self._create_time is None:
            self._create_time = self._proc.create_time()
        return self._create_time

    def cwd(self):
        """Process current working directory as an absolute path."""
        return self._proc.cwd()

    def nice(self, value=None):
        """Get or set process niceness (priority)."""
        if value is None:
            return self._proc.nice_get()
        else:
            if not self.is_running():
                raise NoSuchProcess(self.pid, self._name)
            self._proc.nice_set(value)

    if POSIX:

        @memoize_when_activated
        def uids(self):
            """Return process UIDs as a (real, effective, saved)
            namedtuple.
            """
            return self._proc.uids()

        def gids(self):
            """Return process GIDs as a (real, effective, saved)
            namedtuple.
            """
            return self._proc.gids()

        def terminal(self):
            """The terminal associated with this process, if any,
            else None.
            """
            return self._proc.terminal()

        def num_fds(self):
            """Return the number of file descriptors opened by this
            process (POSIX only).
            """
            return self._proc.num_fds()

    # Linux, BSD, AIX and Windows only
    if hasattr(_psplatform.Process, "io_counters"):

        def io_counters(self):
            """Return process I/O statistics as a
            (read_count, write_count, read_bytes, write_bytes)
            namedtuple.
            Those are the number of read/write calls performed and the
            amount of bytes read and written by the process.
            """
            return self._proc.io_counters()

    # Linux and Windows >= Vista only
    if hasattr(_psplatform.Process, "ionice_get"):

        def ionice(self, ioclass=None, value=None):
            """Get or set process I/O niceness (priority).

            On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
            *value* is a number which goes from 0 to 7. The higher the
            value, the lower the I/O priority of the process.

            On Windows only *ioclass* is used and it can be set to 2
            (normal), 1 (low) or 0 (very low).

            Available on Linux and Windows > Vista only.
            """
            if ioclass is None:
                if value is not None:
                    raise ValueError("'ioclass' argument must be specified")
                return self._proc.ionice_get()
            else:
                return self._proc.ionice_set(ioclass, value)

    # Linux only
    if hasattr(_psplatform.Process, "rlimit"):

        def rlimit(self, resource, limits=None):
            """Get or set process resource limits as a (soft, hard)
            tuple.

            *resource* is one of the RLIMIT_* constants.
            *limits* is supposed to be a (soft, hard)  tuple.

            See "man prlimit" for further info.
            Available on Linux only.
            """
            if limits is None:
                return self._proc.rlimit(resource)
            else:
                return self._proc.rlimit(resource, limits)

    # Windows, Linux and FreeBSD only
    if hasattr(_psplatform.Process, "cpu_affinity_get"):

        def cpu_affinity(self, cpus=None):
            """Get or set process CPU affinity.
            If specified, *cpus* must be a list of CPUs for which you
            want to set the affinity (e.g. [0, 1]).
            If an empty list is passed, all egible CPUs are assumed
            (and set).
            (Windows, Linux and BSD only).
            """
            # Automatically remove duplicates both on get and
            # set (for get it's not really necessary, it's
            # just for extra safety).
            if cpus is None:
                return list(set(self._proc.cpu_affinity_get()))
            else:
                if not cpus:
                    if hasattr(self._proc, "_get_eligible_cpus"):
                        cpus = self._proc._get_eligible_cpus()
                    else:
                        cpus = tuple(range(len(cpu_times(percpu=True))))
                self._proc.cpu_affinity_set(list(set(cpus)))

    # Linux, FreeBSD, SunOS
    if hasattr(_psplatform.Process, "cpu_num"):

        def cpu_num(self):
            """Return what CPU this process is currently running on.
            The returned number should be <= psutil.cpu_count()
            and <= len(psutil.cpu_percent(percpu=True)).
            It may be used in conjunction with
            psutil.cpu_percent(percpu=True) to observe the system
            workload distributed across CPUs.
            """
            return self._proc.cpu_num()

    # Linux, OSX and Windows only
    if hasattr(_psplatform.Process, "environ"):

        def environ(self):
            """The environment variables of the process as a dict.  Note: this
            might not reflect changes made after the process started.  """
            return self._proc.environ()

    if WINDOWS:

        def num_handles(self):
            """Return the number of handles opened by this process
            (Windows only).
            """
            return self._proc.num_handles()

    def num_ctx_switches(self):
        """Return the number of voluntary and involuntary context
        switches performed by this process.
        """
        return self._proc.num_ctx_switches()

    def num_threads(self):
        """Return the number of threads used by this process."""
        return self._proc.num_threads()

    if hasattr(_psplatform.Process, "threads"):

        def threads(self):
            """Return threads opened by process as a list of
            (id, user_time, system_time) namedtuples representing
            thread id and thread CPU times (user/system).
            On OpenBSD this method requires root access.
            """
            return self._proc.threads()

    @_assert_pid_not_reused
    def children(self, recursive=False):
        """Return the children of this process as a list of Process
        instances, pre-emptively checking whether PID has been reused.
        If *recursive* is True return all the parent descendants.

        Example (A == this process):

         A ─┐
            │
            ├─ B (child) ─┐
            │             └─ X (grandchild) ─┐
            │                                └─ Y (great grandchild)
            ├─ C (child)
            └─ D (child)

        >>> import psutil
        >>> p = psutil.Process()
        >>> p.children()
        B, C, D
        >>> p.children(recursive=True)
        B, X, Y, C, D

        Note that in the example above if process X disappears
        process Y won't be listed as the reference to process A
        is lost.
        """
        ppid_map = _ppid_map()
        ret = []
        if not recursive:
            for pid, ppid in ppid_map.items():
                if ppid == self.pid:
                    try:
                        child = Process(pid)
                        # if child happens to be older than its parent
                        # (self) it means child's PID has been reused
                        if self.create_time() <= child.create_time():
                            ret.append(child)
                    except (NoSuchProcess, ZombieProcess):
                        pass
        else:
            # Construct a {pid: [child pids]} dict
            reverse_ppid_map = collections.defaultdict(list)
            for pid, ppid in ppid_map.items():
                reverse_ppid_map[ppid].append(pid)
            # Recursively traverse that dict, starting from self.pid,
            # such that we only call Process() on actual children
            seen = set()
            stack = [self.pid]
            while stack:
                pid = stack.pop()
                if pid in seen:
                    # Since pids can be reused while the ppid_map is
                    # constructed, there may be rare instances where
                    # there's a cycle in the recorded process "tree".
                    continue
                seen.add(pid)
                for child_pid in reverse_ppid_map[pid]:
                    try:
                        child = Process(child_pid)
                        # if child happens to be older than its parent
                        # (self) it means child's PID has been reused
                        intime = self.create_time() <= child.create_time()
                        if intime:
                            ret.append(child)
                            stack.append(child_pid)
                    except (NoSuchProcess, ZombieProcess):
                        pass
        return ret

    def cpu_percent(self, interval=None):
        """Return a float representing the current process CPU
        utilization as a percentage.

        When *interval* is 0.0 or None (default) compares process times
        to system CPU times elapsed since last call, returning
        immediately (non-blocking). That means that the first time
        this is called it will return a meaningful 0.0 value.

        When *interval* is > 0.0 compares process times to system CPU
        times elapsed before and after the interval (blocking).

        In this case is recommended for accuracy that this function
        be called with at least 0.1 seconds between calls.

        A value > 100.0 can be returned in case of processes running
        multiple threads on different CPU cores.

        The returned value is explicitly NOT split evenly between
        all available logical CPUs. This means that a busy loop process
        running on a system with 2 logical CPUs will be reported as
        having 100% CPU utilization instead of 50%.

        Examples:

          >>> import psutil
          >>> p = psutil.Process(os.getpid())
          >>> # blocking
          >>> p.cpu_percent(interval=1)
          2.0
          >>> # non-blocking (percentage since last call)
          >>> p.cpu_percent(interval=None)
          2.9
          >>>
        """
        blocking = interval is not None and interval > 0.0
        if interval is not None and interval < 0:
            raise ValueError("interval is not positive (got %r)" % interval)
        num_cpus = cpu_count() or 1

        def timer():
            return _timer() * num_cpus

        if blocking:
            st1 = timer()
            pt1 = self._proc.cpu_times()
            time.sleep(interval)
            st2 = timer()
            pt2 = self._proc.cpu_times()
        else:
            st1 = self._last_sys_cpu_times
            pt1 = self._last_proc_cpu_times
            st2 = timer()
            pt2 = self._proc.cpu_times()
            if st1 is None or pt1 is None:
                self._last_sys_cpu_times = st2
                self._last_proc_cpu_times = pt2
                return 0.0

        delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
        delta_time = st2 - st1
        # reset values for next call in case of interval == None
        self._last_sys_cpu_times = st2
        self._last_proc_cpu_times = pt2

        try:
            # This is the utilization split evenly between all CPUs.
            # E.g. a busy loop process on a 2-CPU-cores system at this
            # point is reported as 50% instead of 100%.
            overall_cpus_percent = ((delta_proc / delta_time) * 100)
        except ZeroDivisionError:
            # interval was too low
            return 0.0
        else:
            # Note 1:
            # in order to emulate "top" we multiply the value for the num
            # of CPU cores. This way the busy process will be reported as
            # having 100% (or more) usage.
            #
            # Note 2:
            # taskmgr.exe on Windows differs in that it will show 50%
            # instead.
            #
            # Note 3:
            # a percentage > 100 is legitimate as it can result from a
            # process with multiple threads running on different CPU
            # cores (top does the same), see:
            # http://stackoverflow.com/questions/1032357
            # https://github.com/giampaolo/psutil/issues/474
            single_cpu_percent = overall_cpus_percent * num_cpus
            return round(single_cpu_percent, 1)

    @memoize_when_activated
    def cpu_times(self):
        """Return a (user, system, children_user, children_system)
        namedtuple representing the accumulated process time, in
        seconds.
        This is similar to os.times() but per-process.
        On OSX and Windows children_user and children_system are
        always set to 0.
        """
        return self._proc.cpu_times()

    @memoize_when_activated
    def memory_info(self):
        """Return a namedtuple with variable fields depending on the
        platform, representing memory information about the process.

        The "portable" fields available on all plaforms are `rss` and `vms`.

        All numbers are expressed in bytes.
        """
        return self._proc.memory_info()

    @deprecated_method(replacement="memory_info")
    def memory_info_ex(self):
        return self.memory_info()

    def memory_full_info(self):
        """This method returns the same information as memory_info(),
        plus, on some platform (Linux, OSX, Windows), also provides
        additional metrics (USS, PSS and swap).
        The additional metrics provide a better representation of actual
        process memory usage.

        Namely USS is the memory which is unique to a process and which
        would be freed if the process was terminated right now.

        It does so by passing through the whole process address.
        As such it usually requires higher user privileges than
        memory_info() and is considerably slower.
        """
        return self._proc.memory_full_info()

    def memory_percent(self, memtype="rss"):
        """Compare process memory to total physical system memory and
        calculate process memory utilization as a percentage.
        *memtype* argument is a string that dictates what type of
        process memory you want to compare against (defaults to "rss").
        The list of available strings can be obtained like this:

        >>> psutil.Process().memory_info()._fields
        ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
        """
        valid_types = list(_psplatform.pfullmem._fields)
        if memtype not in valid_types:
            raise ValueError("invalid memtype %r; valid types are %r" % (
                memtype, tuple(valid_types)))
        fun = self.memory_info if memtype in _psplatform.pmem._fields else \
            self.memory_full_info
        metrics = fun()
        value = getattr(metrics, memtype)

        # use cached value if available
        total_phymem = _TOTAL_PHYMEM or virtual_memory().total
        if not total_phymem > 0:
            # we should never get here
            raise ValueError(
                "can't calculate process memory percent because "
                "total physical system memory is not positive (%r)"
                % total_phymem)
        return (value / float(total_phymem)) * 100

    if hasattr(_psplatform.Process, "memory_maps"):
        # Available everywhere except OpenBSD and NetBSD.
        def memory_maps(self, grouped=True):
            """Return process' mapped memory regions as a list of namedtuples
            whose fields are variable depending on the platform.

            If *grouped* is True the mapped regions with the same 'path'
            are grouped together and the different memory fields are summed.

            If *grouped* is False every mapped region is shown as a single
            entity and the namedtuple will also include the mapped region's
            address space ('addr') and permission set ('perms').
            """
            it = self._proc.memory_maps()
            if grouped:
                d = {}
                for tupl in it:
                    path = tupl[2]
                    nums = tupl[3:]
                    try:
                        d[path] = map(lambda x, y: x + y, d[path], nums)
                    except KeyError:
                        d[path] = nums
                nt = _psplatform.pmmap_grouped
                return [nt(path, *d[path]) for path in d]  # NOQA
            else:
                nt = _psplatform.pmmap_ext
                return [nt(*x) for x in it]

    def open_files(self):
        """Return files opened by process as a list of
        (path, fd) namedtuples including the absolute file name
        and file descriptor number.
        """
        return self._proc.open_files()

    def connections(self, kind='inet'):
        """Return socket connections opened by process as a list of
        (fd, family, type, laddr, raddr, status) namedtuples.
        The *kind* parameter filters for connections that match the
        following criteria:

        +------------+----------------------------------------------------+
        | Kind Value | Connections using                                  |
        +------------+----------------------------------------------------+
        | inet       | IPv4 and IPv6                                      |
        | inet4      | IPv4                                               |
        | inet6      | IPv6                                               |
        | tcp        | TCP                                                |
        | tcp4       | TCP over IPv4                                      |
        | tcp6       | TCP over IPv6                                      |
        | udp        | UDP                                                |
        | udp4       | UDP over IPv4                                      |
        | udp6       | UDP over IPv6                                      |
        | unix       | UNIX socket (both UDP and TCP protocols)           |
        | all        | the sum of all the possible families and protocols |
        +------------+----------------------------------------------------+
        """
        return self._proc.connections(kind)

    # --- signals

    if POSIX:
        def _send_signal(self, sig):
            assert not self.pid < 0, self.pid
            if self.pid == 0:
                # see "man 2 kill"
                raise ValueError(
                    "preventing sending signal to process with PID 0 as it "
                    "would affect every process in the process group of the "
                    "calling process (os.getpid()) instead of PID 0")
            try:
                os.kill(self.pid, sig)
            except OSError as err:
                if err.errno == errno.ESRCH:
                    if OPENBSD and pid_exists(self.pid):
                        # We do this because os.kill() lies in case of
                        # zombie processes.
                        raise ZombieProcess(self.pid, self._name, self._ppid)
                    else:
                        self._gone = True
                        raise NoSuchProcess(self.pid, self._name)
                if err.errno in (errno.EPERM, errno.EACCES):
                    raise AccessDenied(self.pid, self._name)
                raise

    @_assert_pid_not_reused
    def send_signal(self, sig):
        """Send a signal *sig* to process pre-emptively checking
        whether PID has been reused (see signal module constants) .
        On Windows only SIGTERM is valid and is treated as an alias
        for kill().
        """
        if POSIX:
            self._send_signal(sig)
        else:  # pragma: no cover
            if sig == signal.SIGTERM:
                self._proc.kill()
            # py >= 2.7
            elif sig in (getattr(signal, "CTRL_C_EVENT", object()),
                         getattr(signal, "CTRL_BREAK_EVENT", object())):
                self._proc.send_signal(sig)
            else:
                raise ValueError(
                    "only SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals "
                    "are supported on Windows")

    @_assert_pid_not_reused
    def suspend(self):
        """Suspend process execution with SIGSTOP pre-emptively checking
        whether PID has been reused.
        On Windows this has the effect ot suspending all process threads.
        """
        if POSIX:
            self._send_signal(signal.SIGSTOP)
        else:  # pragma: no cover
            self._proc.suspend()

    @_assert_pid_not_reused
    def resume(self):
        """Resume process execution with SIGCONT pre-emptively checking
        whether PID has been reused.
        On Windows this has the effect of resuming all process threads.
        """
        if POSIX:
            self._send_signal(signal.SIGCONT)
        else:  # pragma: no cover
            self._proc.resume()

    @_assert_pid_not_reused
    def terminate(self):
        """Terminate the process with SIGTERM pre-emptively checking
        whether PID has been reused.
        On Windows this is an alias for kill().
        """
        if POSIX:
            self._send_signal(signal.SIGTERM)
        else:  # pragma: no cover
            self._proc.kill()

    @_assert_pid_not_reused
    def kill(self):
        """Kill the current process with SIGKILL pre-emptively checking
        whether PID has been reused.
        """
        if POSIX:
            self._send_signal(signal.SIGKILL)
        else:  # pragma: no cover
            self._proc.kill()

    def wait(self, timeout=None):
        """Wait for process to terminate and, if process is a children
        of os.getpid(), also return its exit code, else None.

        If the process is already terminated immediately return None
        instead of raising NoSuchProcess.

        If *timeout* (in seconds) is specified and process is still
        alive raise TimeoutExpired.

        To wait for multiple Process(es) use psutil.wait_procs().
        """
        if timeout is not None and not timeout >= 0:
            raise ValueError("timeout must be a positive integer")
        return self._proc.wait(timeout)


# =====================================================================
# --- Popen class
# =====================================================================


class Popen(Process):
    """A more convenient interface to stdlib subprocess.Popen class.
    It starts a sub process and deals with it exactly as when using
    subprocess.Popen class but in addition also provides all the
    properties and methods of psutil.Process class as a unified
    interface:

      >>> import psutil
      >>> from subprocess import PIPE
      >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
      >>> p.name()
      'python'
      >>> p.uids()
      user(real=1000, effective=1000, saved=1000)
      >>> p.username()
      'giampaolo'
      >>> p.communicate()
      ('hi\n', None)
      >>> p.terminate()
      >>> p.wait(timeout=2)
      0
      >>>

    For method names common to both classes such as kill(), terminate()
    and wait(), psutil.Process implementation takes precedence.

    Unlike subprocess.Popen this class pre-emptively checks whether PID
    has been reused on send_signal(), terminate() and kill() so that
    you don't accidentally terminate another process, fixing
    http://bugs.python.org/issue6973.

    For a complete documentation refer to:
    http://docs.python.org/library/subprocess.html
    """

    def __init__(self, *args, **kwargs):
        # Explicitly avoid to raise NoSuchProcess in case the process
        # spawned by subprocess.Popen terminates too quickly, see:
        # https://github.com/giampaolo/psutil/issues/193
        self.__subproc = subprocess.Popen(*args, **kwargs)
        self._init(self.__subproc.pid, _ignore_nsp=True)

    def __dir__(self):
        return sorted(set(dir(Popen) + dir(subprocess.Popen)))

    def __enter__(self):
        if hasattr(self.__subproc, '__enter__'):
            self.__subproc.__enter__()
        return self

    def __exit__(self, *args, **kwargs):
        if hasattr(self.__subproc, '__exit__'):
            return self.__subproc.__exit__(*args, **kwargs)
        else:
            if self.stdout:
                self.stdout.close()
            if self.stderr:
                self.stderr.close()
            try:
                # Flushing a BufferedWriter may raise an error.
                if self.stdin:
                    self.stdin.close()
            finally:
                # Wait for the process to terminate, to avoid zombies.
                self.wait()

    def __getattribute__(self, name):
        try:
            return object.__getattribute__(self, name)
        except AttributeError:
            try:
                return object.__getattribute__(self.__subproc, name)
            except AttributeError:
                raise AttributeError("%s instance has no attribute '%s'"
                                     % (self.__class__.__name__, name))

    def wait(self, timeout=None):
        if self.__subproc.returncode is not None:
            return self.__subproc.returncode
        ret = super(Popen, self).wait(timeout)
        self.__subproc.returncode = ret
        return ret


# The valid attr names which can be processed by Process.as_dict().
_as_dict_attrnames = set(
    [x for x in dir(Process) if not x.startswith('_') and x not in
     ['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
      'is_running', 'as_dict', 'parent', 'children', 'rlimit',
      'memory_info_ex', 'oneshot']])


# =====================================================================
# --- system processes related functions
# =====================================================================


def pids():
    """Return a list of current running PIDs."""
    return _psplatform.pids()


def pid_exists(pid):
    """Return True if given PID exists in the current process list.
    This is faster than doing "pid in psutil.pids()" and
    should be preferred.
    """
    if pid < 0:
        return False
    elif pid == 0 and POSIX:
        # On POSIX we use os.kill() to determine PID existence.
        # According to "man 2 kill" PID 0 has a special meaning
        # though: it refers to <<every process in the process
        # group of the calling process>> and that is not we want
        # to do here.
        return pid in pids()
    else:
        return _psplatform.pid_exists(pid)


_pmap = {}


def process_iter(attrs=None, ad_value=None):
    """Return a generator yielding a Process instance for all
    running processes.

    Every new Process instance is only created once and then cached
    into an internal table which is updated every time this is used.

    Cached Process instances are checked for identity so that you're
    safe in case a PID has been reused by another process, in which
    case the cached instance is updated.

    The sorting order in which processes are yielded is based on
    their PIDs.

    *attrs* and *ad_value* have the same meaning as in
    Process.as_dict(). If *attrs* is specified as_dict() is called
    and the resulting dict is stored as a 'info' attribute attached
    to returned Process instance.
    If *attrs* is an empty list it will retrieve all process info
    (slow).
    """
    def add(pid):
        proc = Process(pid)
        if attrs is not None:
            proc.info = proc.as_dict(attrs=attrs, ad_value=ad_value)
        _pmap[proc.pid] = proc
        return proc

    def remove(pid):
        _pmap.pop(pid, None)

    a = set(pids())
    b = set(_pmap.keys())
    new_pids = a - b
    gone_pids = b - a

    for pid in gone_pids:
        remove(pid)
    for pid, proc in sorted(list(_pmap.items()) +
                            list(dict.fromkeys(new_pids).items())):
        try:
            if proc is None:  # new process
                yield add(pid)
            else:
                # use is_running() to check whether PID has been reused by
                # another process in which case yield a new Process instance
                if proc.is_running():
                    if attrs is not None:
                        proc.info = proc.as_dict(
                            attrs=attrs, ad_value=ad_value)
                    yield proc
                else:
                    yield add(pid)
        except NoSuchProcess:
            remove(pid)
        except AccessDenied:
            # Process creation time can't be determined hence there's
            # no way to tell whether the pid of the cached process
            # has been reused. Just return the cached version.
            if proc is None and pid in _pmap:
                try:
                    yield _pmap[pid]
                except KeyError:
                    # If we get here it is likely that 2 threads were
                    # using process_iter().
                    pass
            else:
                raise


def wait_procs(procs, timeout=None, callback=None):
    """Convenience function which waits for a list of processes to
    terminate.

    Return a (gone, alive) tuple indicating which processes
    are gone and which ones are still alive.

    The gone ones will have a new *returncode* attribute indicating
    process exit status (may be None).

    *callback* is a function which gets called every time a process
    terminates (a Process instance is passed as callback argument).

    Function will return as soon as all processes terminate or when
    *timeout* occurs.
    Differently from Process.wait() it will not raise TimeoutExpired if
    *timeout* occurs.

    Typical use case is:

     - send SIGTERM to a list of processes
     - give them some time to terminate
     - send SIGKILL to those ones which are still alive

    Example:

    >>> def on_terminate(proc):
    ...     print("process {} terminated".format(proc))
    ...
    >>> for p in procs:
    ...    p.terminate()
    ...
    >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
    >>> for p in alive:
    ...     p.kill()
    """
    def check_gone(proc, timeout):
        try:
            returncode = proc.wait(timeout=timeout)
        except TimeoutExpired:
            pass
        else:
            if returncode is not None or not proc.is_running():
                proc.returncode = returncode
                gone.add(proc)
                if callback is not None:
                    callback(proc)

    if timeout is not None and not timeout >= 0:
        msg = "timeout must be a positive integer, got %s" % timeout
        raise ValueError(msg)
    gone = set()
    alive = set(procs)
    if callback is not None and not callable(callback):
        raise TypeError("callback %r is not a callable" % callable)
    if timeout is not None:
        deadline = _timer() + timeout

    while alive:
        if timeout is not None and timeout <= 0:
            break
        for proc in alive:
            # Make sure that every complete iteration (all processes)
            # will last max 1 sec.
            # We do this because we don't want to wait too long on a
            # single process: in case it terminates too late other
            # processes may disappear in the meantime and their PID
            # reused.
            max_timeout = 1.0 / len(alive)
            if timeout is not None:
                timeout = min((deadline - _timer()), max_timeout)
                if timeout <= 0:
                    break
                check_gone(proc, timeout)
            else:
                check_gone(proc, max_timeout)
        alive = alive - gone

    if alive:
        # Last attempt over processes survived so far.
        # timeout == 0 won't make this function wait any further.
        for proc in alive:
            check_gone(proc, 0)
        alive = alive - gone

    return (list(gone), list(alive))


# =====================================================================
# --- CPU related functions
# =====================================================================


def cpu_count(logical=True):
    """Return the number of logical CPUs in the system (same as
    os.cpu_count() in Python 3.4).

    If *logical* is False return the number of physical cores only
    (e.g. hyper thread CPUs are excluded).

    Return None if undetermined.

    The return value is cached after first call.
    If desired cache can be cleared like this:

    >>> psutil.cpu_count.cache_clear()
    """
    if logical:
        ret = _psplatform.cpu_count_logical()
    else:
        ret = _psplatform.cpu_count_physical()
    if ret is not None and ret < 1:
        ret = None
    return ret


def cpu_times(percpu=False):
    """Return system-wide CPU times as a namedtuple.
    Every CPU time represents the seconds the CPU has spent in the
    given mode. The namedtuple's fields availability varies depending on the
    platform:

     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
     - steal (Linux >= 2.6.11)
     - guest (Linux >= 2.6.24)
     - guest_nice (Linux >= 3.2.0)

    When *percpu* is True return a list of namedtuples for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.
    """
    if not percpu:
        return _psplatform.cpu_times()
    else:
        return _psplatform.per_cpu_times()


try:
    _last_cpu_times = cpu_times()
except Exception:
    # Don't want to crash at import time.
    _last_cpu_times = None
    traceback.print_exc()

try:
    _last_per_cpu_times = cpu_times(percpu=True)
except Exception:
    # Don't want to crash at import time.
    _last_per_cpu_times = None
    traceback.print_exc()


def _cpu_tot_time(times):
    """Given a cpu_time() ntuple calculates the total CPU time
    (including idle time).
    """
    tot = sum(times)
    if LINUX:
        # On Linux guest times are already accounted in "user" or
        # "nice" times, so we subtract them from total.
        # Htop does the same. References:
        # https://github.com/giampaolo/psutil/pull/940
        # http://unix.stackexchange.com/questions/178045
        # https://github.com/torvalds/linux/blob/
        #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/
        #     cputime.c#L158
        tot -= getattr(times, "guest", 0)  # Linux 2.6.24+
        tot -= getattr(times, "guest_nice", 0)  # Linux 3.2.0+
    return tot


def _cpu_busy_time(times):
    """Given a cpu_time() ntuple calculates the busy CPU time.
    We do so by subtracting all idle CPU times.
    """
    busy = _cpu_tot_time(times)
    busy -= times.idle
    # Linux: "iowait" is time during which the CPU does not do anything
    # (waits for IO to complete). On Linux IO wait is *not* accounted
    # in "idle" time so we subtract it. Htop does the same.
    # References:
    # https://github.com/torvalds/linux/blob/
    #     447976ef4fd09b1be88b316d1a81553f1aa7cd07/kernel/sched/cputime.c#L244
    busy -= getattr(times, "iowait", 0)
    return busy


def cpu_percent(interval=None, percpu=False):
    """Return a float representing the current system-wide CPU
    utilization as a percentage.

    When *interval* is > 0.0 compares system CPU times elapsed before
    and after the interval (blocking).

    When *interval* is 0.0 or None compares system CPU times elapsed
    since last call or module import, returning immediately (non
    blocking). That means the first time this is called it will
    return a meaningless 0.0 value which you should ignore.
    In this case is recommended for accuracy that this function be
    called with at least 0.1 seconds between calls.

    When *percpu* is True returns a list of floats representing the
    utilization as a percentage for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.

    Examples:

      >>> # blocking, system-wide
      >>> psutil.cpu_percent(interval=1)
      2.0
      >>>
      >>> # blocking, per-cpu
      >>> psutil.cpu_percent(interval=1, percpu=True)
      [2.0, 1.0]
      >>>
      >>> # non-blocking (percentage since last call)
      >>> psutil.cpu_percent(interval=None)
      2.9
      >>>
    """
    global _last_cpu_times
    global _last_per_cpu_times
    blocking = interval is not None and interval > 0.0
    if interval is not None and interval < 0:
        raise ValueError("interval is not positive (got %r)" % interval)

    def calculate(t1, t2):
        t1_all = _cpu_tot_time(t1)
        t1_busy = _cpu_busy_time(t1)

        t2_all = _cpu_tot_time(t2)
        t2_busy = _cpu_busy_time(t2)

        # this usually indicates a float precision issue
        if t2_busy <= t1_busy:
            return 0.0

        busy_delta = t2_busy - t1_busy
        all_delta = t2_all - t1_all
        try:
            busy_perc = (busy_delta / all_delta) * 100
        except ZeroDivisionError:
            return 0.0
        else:
            return round(busy_perc, 1)

    # system-wide usage
    if not percpu:
        if blocking:
            t1 = cpu_times()
            time.sleep(interval)
        else:
            t1 = _last_cpu_times
            if t1 is None:
                # Something bad happened at import time. We'll
                # get a meaningful result on the next call. See:
                # https://github.com/giampaolo/psutil/pull/715
                t1 = cpu_times()
        _last_cpu_times = cpu_times()
        return calculate(t1, _last_cpu_times)
    # per-cpu usage
    else:
        ret = []
        if blocking:
            tot1 = cpu_times(percpu=True)
            time.sleep(interval)
        else:
            tot1 = _last_per_cpu_times
            if tot1 is None:
                # Something bad happened at import time. We'll
                # get a meaningful result on the next call. See:
                # https://github.com/giampaolo/psutil/pull/715
                tot1 = cpu_times(percpu=True)
        _last_per_cpu_times = cpu_times(percpu=True)
        for t1, t2 in zip(tot1, _last_per_cpu_times):
            ret.append(calculate(t1, t2))
        return ret


# Use separate global vars for cpu_times_percent() so that it's
# independent from cpu_percent() and they can both be used within
# the same program.
_last_cpu_times_2 = _last_cpu_times
_last_per_cpu_times_2 = _last_per_cpu_times


def cpu_times_percent(interval=None, percpu=False):
    """Same as cpu_percent() but provides utilization percentages
    for each specific CPU time as is returned by cpu_times().
    For instance, on Linux we'll get:

      >>> cpu_times_percent()
      cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
                 irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
      >>>

    *interval* and *percpu* arguments have the same meaning as in
    cpu_percent().
    """
    global _last_cpu_times_2
    global _last_per_cpu_times_2
    blocking = interval is not None and interval > 0.0
    if interval is not None and interval < 0:
        raise ValueError("interval is not positive (got %r)" % interval)

    def calculate(t1, t2):
        nums = []
        all_delta = _cpu_tot_time(t2) - _cpu_tot_time(t1)
        for field in t1._fields:
            field_delta = getattr(t2, field) - getattr(t1, field)
            try:
                field_perc = (100 * field_delta) / all_delta
            except ZeroDivisionError:
                field_perc = 0.0
            field_perc = round(field_perc, 1)
            # CPU times are always supposed to increase over time
            # or at least remain the same and that's because time
            # cannot go backwards.
            # Surprisingly sometimes this might not be the case (at
            # least on Windows and Linux), see:
            # https://github.com/giampaolo/psutil/issues/392
            # https://github.com/giampaolo/psutil/issues/645
            # I really don't know what to do about that except
            # forcing the value to 0 or 100.
            if field_perc > 100.0:
                field_perc = 100.0
            # `<=` because `-0.0 == 0.0` evaluates to True
            elif field_perc <= 0.0:
                field_perc = 0.0
            nums.append(field_perc)
        return _psplatform.scputimes(*nums)

    # system-wide usage
    if not percpu:
        if blocking:
            t1 = cpu_times()
            time.sleep(interval)
        else:
            t1 = _last_cpu_times_2
            if t1 is None:
                # Something bad happened at import time. We'll
                # get a meaningful result on the next call. See:
                # https://github.com/giampaolo/psutil/pull/715
                t1 = cpu_times()
        _last_cpu_times_2 = cpu_times()
        return calculate(t1, _last_cpu_times_2)
    # per-cpu usage
    else:
        ret = []
        if blocking:
            tot1 = cpu_times(percpu=True)
            time.sleep(interval)
        else:
            tot1 = _last_per_cpu_times_2
            if tot1 is None:
                # Something bad happened at import time. We'll
                # get a meaningful result on the next call. See:
                # https://github.com/giampaolo/psutil/pull/715
                tot1 = cpu_times(percpu=True)
        _last_per_cpu_times_2 = cpu_times(percpu=True)
        for t1, t2 in zip(tot1, _last_per_cpu_times_2):
            ret.append(calculate(t1, t2))
        return ret


def cpu_stats():
    """Return CPU statistics."""
    return _psplatform.cpu_stats()


if hasattr(_psplatform, "cpu_freq"):

    def cpu_freq(percpu=False):
        """Return CPU frequency as a nameduple including current,
        min and max frequency expressed in Mhz.

        If *percpu* is True and the system supports per-cpu frequency
        retrieval (Linux only) a list of frequencies is returned for
        each CPU. If not a list with one element is returned.
        """
        ret = _psplatform.cpu_freq()
        if percpu:
            return ret
        else:
            num_cpus = float(len(ret))
            if num_cpus == 0:
                return None
            elif num_cpus == 1:
                return ret[0]
            else:
                currs, mins, maxs = 0.0, 0.0, 0.0
                for cpu in ret:
                    currs += cpu.current
                    mins += cpu.min
                    maxs += cpu.max
                current = currs / num_cpus
                min_ = mins / num_cpus
                max_ = maxs / num_cpus
                return _common.scpufreq(current, min_, max_)

    __all__.append("cpu_freq")


# =====================================================================
# --- system memory related functions
# =====================================================================


def virtual_memory():
    """Return statistics about system memory usage as a namedtuple
    including the following fields, expressed in bytes:

     - total:
       total physical memory available.

     - available:
       the memory that can be given instantly to processes without the
       system going into swap.
       This is calculated by summing different memory values depending
       on the platform and it is supposed to be used to monitor actual
       memory usage in a cross platform fashion.

     - percent:
       the percentage usage calculated as (total - available) / total * 100

     - used:
        memory used, calculated differently depending on the platform and
        designed for informational purposes only:
        OSX: active + inactive + wired
        BSD: active + wired + cached
        LINUX: total - free

     - free:
       memory not being used at all (zeroed) that is readily available;
       note that this doesn't reflect the actual memory available
       (use 'available' instead)

    Platform-specific fields:

     - active (UNIX):
       memory currently in use or very recently used, and so it is in RAM.

     - inactive (UNIX):
       memory that is marked as not used.

     - buffers (BSD, Linux):
       cache for things like file system metadata.

     - cached (BSD, OSX):
       cache for various things.

     - wired (OSX, BSD):
       memory that is marked to always stay in RAM. It is never moved to disk.

     - shared (BSD):
       memory that may be simultaneously accessed by multiple processes.

    The sum of 'used' and 'available' does not necessarily equal total.
    On Windows 'available' and 'free' are the same.
    """
    global _TOTAL_PHYMEM
    ret = _psplatform.virtual_memory()
    # cached for later use in Process.memory_percent()
    _TOTAL_PHYMEM = ret.total
    return ret


def swap_memory():
    """Return system swap memory statistics as a namedtuple including
    the following fields:

     - total:   total swap memory in bytes
     - used:    used swap memory in bytes
     - free:    free swap memory in bytes
     - percent: the percentage usage
     - sin:     no. of bytes the system has swapped in from disk (cumulative)
     - sout:    no. of bytes the system has swapped out from disk (cumulative)

    'sin' and 'sout' on Windows are meaningless and always set to 0.
    """
    return _psplatform.swap_memory()


# =====================================================================
# --- disks/paritions related functions
# =====================================================================


def disk_usage(path):
    """Return disk usage statistics about the given *path* as a
    namedtuple including total, used and free space expressed in bytes
    plus the percentage usage.
    """
    return _psplatform.disk_usage(path)


def disk_partitions(all=False):
    """Return mounted partitions as a list of
    (device, mountpoint, fstype, opts) namedtuple.
    'opts' field is a raw string separated by commas indicating mount
    options which may vary depending on the platform.

    If *all* parameter is False return physical devices only and ignore
    all others.
    """
    return _psplatform.disk_partitions(all)


def disk_io_counters(perdisk=False, nowrap=True):
    """Return system disk I/O statistics as a namedtuple including
    the following fields:

     - read_count:  number of reads
     - write_count: number of writes
     - read_bytes:  number of bytes read
     - write_bytes: number of bytes written
     - read_time:   time spent reading from disk (in ms)
     - write_time:  time spent writing to disk (in ms)

    Platform specific:

     - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
     - read_merged_count (Linux): number of merged reads
     - write_merged_count (Linux): number of merged writes

    If *perdisk* is True return the same information for every
    physical disk installed on the system as a dictionary
    with partition names as the keys and the namedtuple
    described above as the values.

    If *nowrap* is True it detects and adjust the numbers which overflow
    and wrap (restart from 0) and add "old value" to "new value" so that
    the returned numbers will always be increasing or remain the same,
    but never decrease.
    "disk_io_counters.cache_clear()" can be used to invalidate the
    cache.

    On recent Windows versions 'diskperf -y' command may need to be
    executed first otherwise this function won't find any disk.
    """
    rawdict = _psplatform.disk_io_counters()
    if not rawdict:
        return {} if perdisk else None
    if nowrap:
        rawdict = _wrap_numbers(rawdict, 'psutil.disk_io_counters')
    nt = getattr(_psplatform, "sdiskio", _common.sdiskio)
    if perdisk:
        for disk, fields in rawdict.items():
            rawdict[disk] = nt(*fields)
        return rawdict
    else:
        return nt(*[sum(x) for x in zip(*rawdict.values())])


disk_io_counters.cache_clear = functools.partial(
    _wrap_numbers.cache_clear, 'psutil.disk_io_counters')
disk_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"


# =====================================================================
# --- network related functions
# =====================================================================


def net_io_counters(pernic=False, nowrap=True):
    """Return network I/O statistics as a namedtuple including
    the following fields:

     - bytes_sent:   number of bytes sent
     - bytes_recv:   number of bytes received
     - packets_sent: number of packets sent
     - packets_recv: number of packets received
     - errin:        total number of errors while receiving
     - errout:       total number of errors while sending
     - dropin:       total number of incoming packets which were dropped
     - dropout:      total number of outgoing packets which were dropped
                     (always 0 on OSX and BSD)

    If *pernic* is True return the same information for every
    network interface installed on the system as a dictionary
    with network interface names as the keys and the namedtuple
    described above as the values.

    If *nowrap* is True it detects and adjust the numbers which overflow
    and wrap (restart from 0) and add "old value" to "new value" so that
    the returned numbers will always be increasing or remain the same,
    but never decrease.
    "disk_io_counters.cache_clear()" can be used to invalidate the
    cache.
    """
    rawdict = _psplatform.net_io_counters()
    if not rawdict:
        return {} if pernic else None
    if nowrap:
        rawdict = _wrap_numbers(rawdict, 'psutil.net_io_counters')
    if pernic:
        for nic, fields in rawdict.items():
            rawdict[nic] = _common.snetio(*fields)
        return rawdict
    else:
        return _common.snetio(*[sum(x) for x in zip(*rawdict.values())])


net_io_counters.cache_clear = functools.partial(
    _wrap_numbers.cache_clear, 'psutil.net_io_counters')
net_io_counters.cache_clear.__doc__ = "Clears nowrap argument cache"


def net_connections(kind='inet'):
    """Return system-wide socket connections as a list of
    (fd, family, type, laddr, raddr, status, pid) namedtuples.
    In case of limited privileges 'fd' and 'pid' may be set to -1
    and None respectively.
    The *kind* parameter filters for connections that fit the
    following criteria:

    +------------+----------------------------------------------------+
    | Kind Value | Connections using                                  |
    +------------+----------------------------------------------------+
    | inet       | IPv4 and IPv6                                      |
    | inet4      | IPv4                                               |
    | inet6      | IPv6                                               |
    | tcp        | TCP                                                |
    | tcp4       | TCP over IPv4                                      |
    | tcp6       | TCP over IPv6                                      |
    | udp        | UDP                                                |
    | udp4       | UDP over IPv4                                      |
    | udp6       | UDP over IPv6                                      |
    | unix       | UNIX socket (both UDP and TCP protocols)           |
    | all        | the sum of all the possible families and protocols |
    +------------+----------------------------------------------------+

    On OSX this function requires root privileges.
    """
    return _psplatform.net_connections(kind)


def net_if_addrs():
    """Return the addresses associated to each NIC (network interface
    card) installed on the system as a dictionary whose keys are the
    NIC names and value is a list of namedtuples for each address
    assigned to the NIC. Each namedtuple includes 5 fields:

     - family: can be either socket.AF_INET, socket.AF_INET6 or
               psutil.AF_LINK, which refers to a MAC address.
     - address: is the primary address and it is always set.
     - netmask: and 'broadcast' and 'ptp' may be None.
     - ptp: stands for "point to point" and references the
            destination address on a point to point interface
            (typically a VPN).
     - broadcast: and *ptp* are mutually exclusive.

    Note: you can have more than one address of the same family
    associated with each interface.
    """
    has_enums = sys.version_info >= (3, 4)
    if has_enums:
        import socket
    rawlist = _psplatform.net_if_addrs()
    rawlist.sort(key=lambda x: x[1])  # sort by family
    ret = collections.defaultdict(list)
    for name, fam, addr, mask, broadcast, ptp in rawlist:
        if has_enums:
            try:
                fam = socket.AddressFamily(fam)
            except ValueError:
                if WINDOWS and fam == -1:
                    fam = _psplatform.AF_LINK
                elif (hasattr(_psplatform, "AF_LINK") and
                        _psplatform.AF_LINK == fam):
                    # Linux defines AF_LINK as an alias for AF_PACKET.
                    # We re-set the family here so that repr(family)
                    # will show AF_LINK rather than AF_PACKET
                    fam = _psplatform.AF_LINK
        if fam == _psplatform.AF_LINK:
            # The underlying C function may return an incomplete MAC
            # address in which case we fill it with null bytes, see:
            # https://github.com/giampaolo/psutil/issues/786
            separator = ":" if POSIX else "-"
            while addr.count(separator) < 5:
                addr += "%s00" % separator
        ret[name].append(_common.snic(fam, addr, mask, broadcast, ptp))
    return dict(ret)


def net_if_stats():
    """Return information about each NIC (network interface card)
    installed on the system as a dictionary whose keys are the
    NIC names and value is a namedtuple with the following fields:

     - isup: whether the interface is up (bool)
     - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
               NIC_DUPLEX_UNKNOWN
     - speed: the NIC speed expressed in mega bits (MB); if it can't
              be determined (e.g. 'localhost') it will be set to 0.
     - mtu: the maximum transmission unit expressed in bytes.
    """
    return _psplatform.net_if_stats()


# =====================================================================
# --- sensors
# =====================================================================


# Linux
if hasattr(_psplatform, "sensors_temperatures"):

    def sensors_temperatures(fahrenheit=False):
        """Return hardware temperatures. Each entry is a namedtuple
        representing a certain hardware sensor (it may be a CPU, an
        hard disk or something else, depending on the OS and its
        configuration).
        All temperatures are expressed in celsius unless *fahrenheit*
        is set to True.
        """
        def convert(n):
            if n is not None:
                return (float(n) * 9 / 5) + 32 if fahrenheit else n

        ret = collections.defaultdict(list)
        rawdict = _psplatform.sensors_temperatures()

        for name, values in rawdict.items():
            while values:
                label, current, high, critical = values.pop(0)
                current = convert(current)
                high = convert(high)
                critical = convert(critical)

                if high and not critical:
                    critical = high
                elif critical and not high:
                    high = critical

                ret[name].append(
                    _common.shwtemp(label, current, high, critical))

        return dict(ret)

    __all__.append("sensors_temperatures")


# Linux
if hasattr(_psplatform, "sensors_fans"):

    def sensors_fans():
        """Return fans speed. Each entry is a namedtuple
        representing a certain hardware sensor.
        All speed are expressed in RPM (rounds per minute).
        """
        return _psplatform.sensors_fans()

    __all__.append("sensors_fans")


# Linux, Windows, FreeBSD, OSX
if hasattr(_psplatform, "sensors_battery"):

    def sensors_battery():
        """Return battery information. If no battery is installed
        returns None.

         - percent: battery power left as a percentage.
         - secsleft: a rough approximation of how many seconds are left
                     before the battery runs out of power. May be
                     POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
         - power_plugged: True if the AC power cable is connected.
        """
        return _psplatform.sensors_battery()

    __all__.append("sensors_battery")


# =====================================================================
# --- other system related functions
# =====================================================================


def boot_time():
    """Return the system boot time expressed in seconds since the epoch."""
    # Note: we are not caching this because it is subject to
    # system clock updates.
    return _psplatform.boot_time()


def users():
    """Return users currently connected on the system as a list of
    namedtuples including the following fields.

     - user: the name of the user
     - terminal: the tty or pseudo-tty associated with the user, if any.
     - host: the host name associated with the entry, if any.
     - started: the creation time as a floating point number expressed in
       seconds since the epoch.
    """
    return _psplatform.users()


# =====================================================================
# --- Windows services
# =====================================================================


if WINDOWS:

    def win_service_iter():
        """Return a generator yielding a WindowsService instance for all
        Windows services installed.
        """
        return _psplatform.win_service_iter()

    def win_service_get(name):
        """Get a Windows service by *name*.
        Raise NoSuchProcess if no service with such name exists.
        """
        return _psplatform.win_service_get(name)


# =====================================================================


def test():  # pragma: no cover
    """List info of all currently running processes emulating ps aux
    output.
    """
    today_day = datetime.date.today()
    templ = "%-10s %5s %4s %7s %7s %-13s %5s %7s  %s"
    attrs = ['pid', 'memory_percent', 'name', 'cpu_times', 'create_time',
             'memory_info']
    if POSIX:
        attrs.append('uids')
        attrs.append('terminal')
    print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "TTY", "START", "TIME",
                   "COMMAND"))
    for p in process_iter(attrs=attrs, ad_value=''):
        if p.info['create_time']:
            ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
            if ctime.date() == today_day:
                ctime = ctime.strftime("%H:%M")
            else:
                ctime = ctime.strftime("%b%d")
        else:
            ctime = ''
        cputime = time.strftime("%M:%S",
                                time.localtime(sum(p.info['cpu_times'])))
        try:
            user = p.username()
        except Error:
            user = ''
        if WINDOWS and '\\' in user:
            user = user.split('\\')[1]
        vms = p.info['memory_info'] and \
            int(p.info['memory_info'].vms / 1024) or '?'
        rss = p.info['memory_info'] and \
            int(p.info['memory_info'].rss / 1024) or '?'
        memp = p.info['memory_percent'] and \
            round(p.info['memory_percent'], 1) or '?'
        print(templ % (
            user[:10],
            p.info['pid'],
            memp,
            vms,
            rss,
            p.info.get('terminal', '') or '?',
            ctime,
            cputime,
            p.info['name'].strip() or '?'))


del memoize, memoize_when_activated, division, deprecated_method
if sys.version_info[0] < 3:
    del num, x

if __name__ == "__main__":
    test()
_psutil_linux.cpython-36m-x86_64-linux-gnu.so000075500000072130150466730530014772 0ustar00ELF>�$@m@8	@MM x[x[ x[ �� �[�[ �[ 888$$�L�L�L  S�td�L�L�L  P�td(F(F(F��Q�tdR�tdx[x[ x[ ��GNU�=b�����z��'��W�N�E� 	UR EKPBE��,>o���|�ȷԸfW�~���:hde�qX.����H���ذ�$���r:,�c:c�j% ��]��@�rx����.�c�F q��C����0���R�~����{>Dp�, ��F"��ct� c ��&��0c 1`0WU�%�'I�$c H�0�� c ��&3(c Np>�}`1�0&__gmon_start___ITM_deregisterTMCloneTable_ITM_registerTMCloneTable__cxa_finalizeNoSuchProcessPyExc_OSErrorPyObject_CallFunctionPyErr_SetObjectstrerrorAccessDeniedpsutil_set_testingPSUTIL_TESTING_Py_NoneStructpsutil_debugstderrfwrite__vfprintf_chkfputc__stack_chk_failpsutil_setupgetenvPSUTIL_DEBUGPyModule_GetStatePyArg_ParseTuplesocketstrncpyioctlclose_Py_TrueStructPy_BuildValuePyErr_SetFromErrno_Py_FalseStructgetnameinfo__sprintf_chkPyList_NewgetifaddrsPyList_Appendfreeifaddrssetpriority__errno_locationgetprioritypsutil_pid_existskillpsutil_raise_for_pidPyExc_RuntimeErrorPyErr_FormatPyInit__psutil_posixPyModule_Create2PyLong_AsLongprlimit64PyErr_OccurredsetutentPyUnicode_DecodeFSDefaultgetutentendutentPyEval_SaveThreadsetmntentPyEval_RestoreThreadgetmntentendmntentPyErr_SetFromErrnoWithFilenamePySequence_CheckPySequence_Fastsched_setaffinityPyExc_TypeErrorPyExc_ValueErrorPyErr_SetString__sched_cpuallocsched_getaffinity__sched_cpufreePyExc_OverflowErrorPyErr_NoMemory__sched_cpucountPyLong_FromLongsysinfosyscallPyInit__psutil_linuxPyModule_AddIntConstantPyModule_AddObjectlibpython3.6m.so.1.0libpthread.so.0libc.so.6_edata__bss_start_endGLIBC_2.2.5GLIBC_2.7GLIBC_2.3GLIBC_2.13GLIBC_2.4GLIBC_2.6GLIBC_2.3.4		� ui	��ii
	�ii
�����ii
ii

ti	ui	�x[ �%�[ `%�[ �[ (` �@@` �` P` �(X`  (�` �@�` �/�` �@�` �@�` 0/�` �@�` �@�` �+�` A�` A�` �)�` (Aa 9Aa �(a FAha C�a �a �a  ;�a �1�a C�a �=�a C�a 7C�a  =�a GCb `Cb  9b xD b vC(b 78b �D@b �CHb @5Xb �D`b �Chb @3xb PE�b �C�b �;�b �E�b �C�b `;�b �E�b �C�b �1�b F�b �C�b �C�_ 
�_ �_ �_ �_  �_ !�_ #�_ %�_ K�_ .�_ 3�_ O�_ =�_ @�_ A�b N�] �] �] �] �] �] �] �] �] 	�] �] ^ 
^ ^ ^  ^ (^ F0^ 8^ @^ H^ P^ X^ `^ h^ p^ x^ �^ �^ "�^ $�^ &�^ '�^ (�^ )�^ *�^ +�^ ,�^ -�^ /�^ 0�^ 1�^ H�^ I_ 2_ 4_ 5_ 6 _ 7(_ 80_ 98_ :@_ ;H_ <P_ >X_ ?`_ @h_ Jp_ Bx_ C�_ D��H��H�iB H��t��H����52@ �%3@ ��h�������h��������h�������h�������h�������h�������h�������h��q������h��a������h	��Q������h
��A������h��1������h��!������h
��������h��������h������h�������h��������h�������h�������h�������h�������h�������h��q������h��a������h��Q������h��A������h��1������h��!������h��������h��������h������h �������h!��������h"�������h#�������h$�������h%�������h&�������h'��q������h(��a������h)��Q������h*��A������h+��1������h,��!������h-��������h.��������h/������h0�������h1��������h2�������h3�������h4�������h5�������h6�������h7��q������h8��a������h9��Q������h:��A������h;��1�������%m< D���%e< D���%]< D���%U< D���%M< D���%E< D���%=< D���%5< D���%-< D���%%< D���%< D���%< D���%
< D���%< D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%�; D���%}; D���%u; D���%m; D���%e; D���%]; D���%U; D���%M; D���%E; D���%=; D���%5; D���%-; D���%%; D���%; D���%; D���%
; D���%; D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: D���%�: DH�=)> H�"> H9�tH�~: H��t	�����H�=�= H�5�= H)�H��H��H��?H�H�tH��: H��t��fD�����=�= u+UH�=z: H��tH�=6 �����d�����= ]������w������UH��SH���?t^H�-�9 H�5�1��H�}� ���H�}H��H������H��tH�+tH��1�[]�DH�CH��P0H��1�[]�D��f���H��듐��UH��SH���?t^H�-_9 H�51��
H�}���H�}H��H�����H��tH�+tH��1�[]�DH�CH��P0H��1�[]�D�
���H��듐��H�
9 �H�9 H����UH��SH���H�t$(H�T$0H�L$8L�D$@L�L$H��t7)D$P)L$`)T$p)�$�)�$�)�$�)�$�)�$�dH�%(H�D$1���H��8 H��$�H�=��$H�H�D$H�D$ �D$0H�D$���H�;H��H�����H�3�
���H�D$dH3%(u
H���[]��G������H��H�=��L���H��t
H��7 �H�=t�.���H��t
H��7 �H������UH��SH������H�H��tH�����H�H�+tH��1�[]��H�CH��P0H��1�[]�ff.�f���ATI��UH��SH�����H�8tH�����[L��H�8H��]A\��D[1�]A\Ð��SH��H�5�H��@dH�%(H�D$81�H�T$������1���tk1Ҿ������Ã��t{H�L$H�t$�H���|�������H��1��+������tF���/����D$ tXH�5�6 H�=b1����H�L$8dH3%(uGH��@[�f.���t@�����H�6 H�8�2����H�5	6 H�=
1��[�����T���@��SH��H�5�H��@dH�%(H�D$81�H�T$������1���t^1Ҿ������Ã��tkH�L$H�t$�H���|����!���H��1��+������t6���/����t$ H�=�1����H�L$8dH3%(u-H��@[����t@����H�"5 H�8�B������{���ff.�AWAVAUATUSH��dH�%(H��$1�H��t'����tU��uD�wM����f.�H��4 H�H��$dH3%(��H��[]A\A]A^A_�@����H��E�H���H��jE1�E1��,���ZY��u�H��H�=�1�����I��H��N�,7L��L�%�@D�CH��L���1�H��H������L9�u�K�vL��H�=��D�1��E����+����;���ff.���AW1�AVAUATUSH��(dH�%(H�D$1��7���H�D$H����H�|$�o��������H�\$H�����h���H��3 H�I��I��H��H�sD��M��ATI��L��H�=1����I��XZM����H�|$L���H�������I�.u
I�FL���P0I�/u
I�GL���P0H�mu
H�EH��P0I�mu
I�EL��P0I�,$uI�D$L��P0H�H����H�{H��t�D�7D�����H;�2 I��t�H����H�{ D���j���H��H�����C���H�{(D���G���L�%p2 I��H�f2 H�M����������E1�H�|$H��t�b���H�T$H�H�D$H��H���M��tI�.u
I�FL���P0M��tI�/u
I�GL���P0H��tH�mu
H�EH��P0M��tI�mu
I�EL��P0M��tI�,$��H�D$H�L$dH3%(H�D$��H��([]A\A]A^A_ÐH�{(D���T���L�-}1 I��H�s1 H�M��������@H�BH��P0M���*����5����I�D$L��P0�n���H�\$H���C����e���fDH�|$E1�E1�1�E1�H����������f.�H�|$E1�E1�E1�H����������H��0 E1�E1�1�E1�E1�H�8���a������ff.�f���H��(H��H�5MdH�%(H�D$1�H�T$H�L$�O�1҅�t�T$�t$1������t%H�N0 H�H�t$dH34%(H��uH��(�f�H�0 H�8�!�H�����W����UH��SH��dH�%(H�D$1���H��H�5�H���H��1����1���t �4$1�����u)��H�=�1����H�L$dH3%(uH��[]�f�H�a/ H�8������f.���H��1��@H��1���¸��t,����t��tH�
/ H�8�*������1�H���f���UH��SH��H������ueH������t)H��. H��H�5�H�81��^�H��1�[]�DH��H��H�=C��H�=:��H��1�[]�f�H�a. H�8��H��1�[]������H�=�. ���f.����UH��SH����H�H��tH����H�H�+tH��1�[]��H�CH��P0H��1�[]�ff.�f���H��XH��H�5�dH�%(H�D$H1�H�L$H�T$H�D$L�L$L�D$H�D$�����H�|$H��tq��H�D$0H�����H�|$���H�D$8H������t$�|$H�L$ H�T$0�=�����H�=- H�H�t$HdH34%(��H��X�H�|$u��t$�|$1�H�L$ ������tOH�T$(H�t$ H�=�1��'��D�;�H���n���1��fD�#�H���=���1��z���H��, H�8���c���������AW1�AVAUATUSH�����I��H��������L�-9, H�{,��H��H���SH�{�{�I��H���oH�{L�f�I��H����f�D�KH��M���*�TL��H��H�=�
�Z��)�H��H����H��L���������H�mu
H�EH��P0I�,$uI�D$L��P0I�/u
I�GL���P0H�+����H��H��t f�;����L�-w+ ����f.��;�H��L��[]A\A]A^A_�f�1�H�mu
H�EH��P0I�,$uI�D$L��P0M��tI�/u
I�GL���P0H��tH�+u
H�CH��P0I�.t���E1�놐I�FL��E1��P0���n���f�H�mu�H�EH��P0�DH�CH��P0����f���AW1�AVAUATUSH�����H���7I��L�=V��H�5>H�=9H����H��I���.�M�����PH�;�h�H��H���,H�{�S�I��H����H�KL�CH��H��L��1��/�H��H��t_H��L�������uPH�mu
H�EH��P0I�,$uI�D$L��P0H�+��L���C�H��H���g���L�����YDL����H�mu
H�EH��P0I�,$uI�D$L��P0H��tH�+u
H�CH��P0I�mu
I�EL��P0E1�H��L��[]A\A]A^A_�f�L����H�mu�H�EH��P0�DH�CH��P0�F����L���x��fDH��( H�5�
H�8�J��}���D��AWH��H�5�
AVAUATUSH��dH�%(H��$�1�H�L$H���a�����H�|$������OH�|$H�5��f�I��H����H�PL�l$�1�L���H������B�1�A�L�4��N�I�D$H�<��H��H���tQ�T�H��uGH���wH��L����H��H��I	T�H��L9�tyI�D$���u�I�|�1�H��H���u���H����I�,$t31�H��$�dH34%(��H�Ĩ[]A\A]A^A_��I�D$L��P01���<$L�꾀����uoI�,$uI�D$L��P0H�#' H��DH�D$H�5<H�@H�PH��& H�81����[���fDH��& H�5�H�8�"��3���H��& H�8���������@��AWH��H�5{AVAUA�ATA�@USH��dH�%(H�D$1�H���P���u���E�Ic�H�_?�a�H��H��H��H�����<$H��H�����A�ƅ���H���������8�>A��u�H��% H�5r
E1�H�8�?�H�L$dH3%(L���H��[]A\A]A^A_�H��I�u
I�GL���P0H���~�I�,$uI�D$L��P0@E1����I���fD1����I��H����H��H����A��u�rf�A��Ic�H��H��H9�s�H��H��H�D�L��s��&�I��H���d���H��L������I��;���H��I�u
I�GL���P0A��A��u�H�������f.�H��$ H�8��I���������@��ATI��UH��SH���
�H�8tH����[L��H�8H��]A\��D[1�]A\Ð��H��dH�%(H�D$x1�H������uQ�D$hH�=LP1��t$PL�L$PL�D$@H�L$HH�T$8H�t$0�Y�ZYH�T$xdH3%(u H�Ĉ��H��# H�8������"�f���ATH��H�5WUSH�ĀdH�%(H�D$x1�H�T$����1�����1Ҿ����Ã����H�L$H�t$�H���A�f�F���H��H�D$@D$DH�D$ H��1�D$TH�D$d�D$@������t_�l$ND�d$L����1�D���H�='�J�H��tH�L$xdH3%(u@H��[]A\�@����H��" H�8����������_t��u�E1�������H��(H��H�5�dH�%(H�D$1�H�T$H�L$L�D$�Z�1҅�t0�L$�T$1������
L$�t����t'H�H" H�H�t$dH34%(H��uH��(�@H��! H�8��H�����O�ff.�@��H��H��H�5�dH�%(H�D$1�H������1���t2�$���������t7�‰�H�=�1�����
���H�L$dH3%(uH����H�Q! H�8�q�����f.���S��H�=�" ���H�5_H��H������	H�5PH�����H�5FH����1�H�5AH�����H�58H�����H�50H���r��
H�5)H���^��H�5"H���J��H�5H���6��H�5H���"��H�5H����H�ߺH�5��H������N�H��tH��H�5�H����H�ߺH�5����H�ߺ
H�5���H�ߺH�5���H�ߺH�5���H�ߺH�5��s�H��1�H�5��b�H�ߺH�5��N�H�ߺ�H�5��:��u�H��[���H��H���(is)psutil-dubug> PSUTIL_DEBUGPSUTIL_TESTING%02x:(siOOOO)li%s syscall failedpsutil_posixgetpriorityReturn process prioritysetprioritySet process prioritynet_if_addrsRetrieve NICs informationnet_if_mtuRetrieve NIC MTUnet_if_flagsRetrieve NIC flags%s syscall failed and PID %i no longer exists; assume NoSuchProcessli|OOll(OOOfOi)r/etc/mtab(OOss)lOinvalid CPU value(kkkkkkI)[ii]liiversionRLIMIT_ASRLIMIT_CORERLIMIT_CPURLIMIT_DATARLIMIT_FSIZERLIMIT_LOCKSRLIMIT_MEMLOCKRLIMIT_NOFILERLIMIT_NPROCRLIMIT_RSSRLIMIT_STACKRLIM_INFINITYRLIMIT_MSGQUEUERLIMIT_NICERLIMIT_RTPRIORLIMIT_RTTIMERLIMIT_SIGPENDINGDUPLEX_HALFDUPLEX_FULLDUPLEX_UNKNOWNpsutil_linuxproc_ioprio_getGet process I/O priorityproc_ioprio_setSet process I/O priorityproc_cpu_affinity_getproc_cpu_affinity_setdisk_partitionsusersnet_if_duplex_speedlinux_sysinfolinux_prlimitset_testingSet psutil in testing modesequence argument expected, got %sexpected a sequence or integercould not allocate a large enough CPU setReturn process CPU affinity as a Python long (the bitmask).Set process CPU affinity; expects a bitmask.Return disk mounted partitions as a list of tuples including device, mount point and filesystem typeReturn currently connected users as a list of tuplesReturn duplex and speed info about a NICA wrapper around sysinfo(), return system memory usage statisticsGet or set process resource limits.;�8����@���X������������ X�T������x����0�����8�����8�,X�@��t������(��x���8�������(����\����xH����zRx�$���FJw�?:*3$"D����4\(��E�D�D A
CAFN
CAF4�p��E�D�D A
CAFN
CAF����(�����E�D�G��
AAA���IH@0$���SE�D�D f
CAINCA4X���?F�D�D �W
JBGACB ���E�NP�
AK ����E�NP�
AHX���5B�B�B �B(�A0�A8�G�h
8A0A(B BBBEW�J�L�A�X4��CF�D�B �B(�A0�A8�D`ihLpXhA`�
8A0A(B BBBB�t��H0e
C(����E�D�D0n
AAC�\�WTB<����E�D�G v
CAFb
CAJSCA0�0D�SE�D�D f
CAINCAx<�YH`�
AH����F�D�B �B(�A0�A8�D@%
8D0A(B BBBJH�4��F�D�B �B(�A0�A8�D@L
8D0A(B BBBCL,��F�L�B �B(�A0�A8�G�.
8A0A(B BBBIH|x��F�L�B �H(�G0�A8�DP�
8A0A(B BBBA4�,�?F�D�D �W
JBGACB(4��K�h�F�_�A�W
H0,��0F�K�A �D��
 AABE`��H0{
E|(�H p
H����E��GNU��%`%�[ ���@
@@x[ �[ ���o`�
�
 �] ����	���o���oX���o�o����o7�[ p�������� 0@P`p�������� 0@P`p��������    0 @ P ` p � � � � � � � � !! !�@�` �( (�@�/�@�@0/�@�@�+AA�)(A9A�(FAC�a  ;�1C�=C7C =GC`C 9xDvC7�D�C@5�D�C@3PE�C�;�E�C`;�E�C�1F�C�CGA$3a1@M@
GA$3p965�%@@GA*GA$annobin gcc 8.5.0 20210514GA$running gcc 8.5.0 20210514GA*GA*GA!
GA*FORTIFYGA+GLIBCXX_ASSERTIONSGA*GOW*�GA*cf_protectionGA+omit_frame_pointerGA+stack_clashGA!stack_realign
GA$3p965 (u1GA*GA$annobin gcc 8.5.0 20210514GA$running gcc 8.5.0 20210514GA*GA*GA!
GA*FORTIFYGA+GLIBCXX_ASSERTIONSGA*GOW*�GA*cf_protectionGA+omit_frame_pointerGA+stack_clashGA!stack_realign
GA*FORTIFY�%�1GA+GLIBCXX_ASSERTIONSGA*cf_protection_psutil_linux.cpython-36m-x86_64-linux-gnu.so-5.4.3-11.el8.x86_64.debug�l�7zXZ�ִF!t/��o`]?�E�h=��ڊ�2N�	ih'��fi���2�]H�=�g2�fE�]�g�\Rͣ�U{�M���`�j�����ivm�0��$�e�ֳ��E���_��y�}�-��HF��=K�@��C1��Y�kVl �?�(Zr�ӵ���iP5����l���f�߃h��Uj���6O�
�j�vtn����d���~]����Z�˫�&4���8����a�����$��ˇ�w#J���)t6��������ОV�P��M;���
�{4���,��DK�{����B����B}�)�70,Ep��ӋZ���S����b�FP�e�t⁠rX
�M4ެ�vvF��ެZ���tg�;����{�X|��
H��;�ձ�/�@�((fʫ�"O�O5t)�xw�\Z���_l*v޽�#F~�4p���\�]�W��R6��}>�+�M�x�盺n�����oLw��<bv ��-a�ɲ�z{�kG#r�:�$<��.���6M�b����wE���mB쓣��I���-'{T�r`�D���O^�LV�w%-(��з��|�V9�Րޢω6��GI9�n�$|rqj��JS�'{�t2�j�#��H��P(�H�~�Y�p���-[���D���J�۲���+��XV��ld�'�������U�,b$՜Gm��Q��v%[�$T�Z1�pk*��U�(]6:ӣ�m����m�ܿ(JԽO똿�s�A!�w�v�@����whq������8�@5��!�1��dH9:�o��@�o4��#^.���MK6�ص��p��W���Ne��*�X��>�.��V(-.�V�̰w&���k�6�Ge�6�M��_�í�����ǡ�����
�V&��-�W�@��ò��zyG�g�=SE�eU�K�-��x�[-)O����$��*�F��
~�*��@wB�S
_4�Q�O;~��К�@}PK�6*yX�p�fC\O�"���=܇�
�� b�\!7�����9$�bg�l���X�au�l"X:�S1�ݤ�9������I�R#���V��$��P<�2(4�H��Lyx��ё�TN�|ſX���$�W(��g�YZ.shstrtab.note.gnu.build-id.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.plt.sec.text.fini.rodata.eh_frame_hdr.eh_frame.note.gnu.property.init_array.fini_array.data.rel.ro.dynamic.got.data.bss.gnu.build.attributes.gnu_debuglink.gnu_debugdata88$���o``d(���0�
�
 8���o���E���oXX�T���^B���h@@c``�n0!0!�w�$�$P}@@@@
�2P@P@��(F(F��(G(G���L�L �x[ x[��[ �[��[ �[��[ �[��] �]p�` `  � c  c�0c` c�
gLPg��k(_common.py000064400000042674150466730530006573 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Common objects shared by __init__.py and _ps*.py modules."""

# Note: this module is imported by setup.py so it should not import
# psutil or third-party modules.

from __future__ import division

import contextlib
import errno
import functools
import os
import socket
import stat
import sys
import threading
import warnings
from collections import defaultdict
from collections import namedtuple
from socket import AF_INET
from socket import SOCK_DGRAM
from socket import SOCK_STREAM
try:
    from socket import AF_INET6
except ImportError:
    AF_INET6 = None
try:
    from socket import AF_UNIX
except ImportError:
    AF_UNIX = None

if sys.version_info >= (3, 4):
    import enum
else:
    enum = None

# can't take it from _common.py as this script is imported by setup.py
PY3 = sys.version_info[0] == 3

__all__ = [
    # constants
    'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'OSX', 'POSIX', 'SUNOS',
    'WINDOWS',
    'ENCODING', 'ENCODING_ERRS', 'AF_INET6',
    # connection constants
    'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED',
    'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN',
    'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT',
    # net constants
    'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN',
    # process status constants
    'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED',
    'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED',
    'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL',
    'STATUS_WAKING', 'STATUS_ZOMBIE',
    # named tuples
    'pconn', 'pcputimes', 'pctxsw', 'pgids', 'pio', 'pionice', 'popenfile',
    'pthread', 'puids', 'sconn', 'scpustats', 'sdiskio', 'sdiskpart',
    'sdiskusage', 'snetio', 'snic', 'snicstats', 'sswap', 'suser',
    # utility functions
    'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize',
    'parse_environ_block', 'path_exists_strict', 'usage_percent',
    'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers",
]


# ===================================================================
# --- OS constants
# ===================================================================


POSIX = os.name == "posix"
WINDOWS = os.name == "nt"
LINUX = sys.platform.startswith("linux")
OSX = sys.platform.startswith("darwin")
FREEBSD = sys.platform.startswith("freebsd")
OPENBSD = sys.platform.startswith("openbsd")
NETBSD = sys.platform.startswith("netbsd")
BSD = FREEBSD or OPENBSD or NETBSD
SUNOS = sys.platform.startswith("sunos") or sys.platform.startswith("solaris")
AIX = sys.platform.startswith("aix")


# ===================================================================
# --- API constants
# ===================================================================


# Process.status()
STATUS_RUNNING = "running"
STATUS_SLEEPING = "sleeping"
STATUS_DISK_SLEEP = "disk-sleep"
STATUS_STOPPED = "stopped"
STATUS_TRACING_STOP = "tracing-stop"
STATUS_ZOMBIE = "zombie"
STATUS_DEAD = "dead"
STATUS_WAKE_KILL = "wake-kill"
STATUS_WAKING = "waking"
STATUS_IDLE = "idle"  # FreeBSD, OSX
STATUS_LOCKED = "locked"  # FreeBSD
STATUS_WAITING = "waiting"  # FreeBSD
STATUS_SUSPENDED = "suspended"  # NetBSD

# Process.connections() and psutil.net_connections()
CONN_ESTABLISHED = "ESTABLISHED"
CONN_SYN_SENT = "SYN_SENT"
CONN_SYN_RECV = "SYN_RECV"
CONN_FIN_WAIT1 = "FIN_WAIT1"
CONN_FIN_WAIT2 = "FIN_WAIT2"
CONN_TIME_WAIT = "TIME_WAIT"
CONN_CLOSE = "CLOSE"
CONN_CLOSE_WAIT = "CLOSE_WAIT"
CONN_LAST_ACK = "LAST_ACK"
CONN_LISTEN = "LISTEN"
CONN_CLOSING = "CLOSING"
CONN_NONE = "NONE"

# net_if_stats()
if enum is None:
    NIC_DUPLEX_FULL = 2
    NIC_DUPLEX_HALF = 1
    NIC_DUPLEX_UNKNOWN = 0
else:
    class NicDuplex(enum.IntEnum):
        NIC_DUPLEX_FULL = 2
        NIC_DUPLEX_HALF = 1
        NIC_DUPLEX_UNKNOWN = 0

    globals().update(NicDuplex.__members__)

# sensors_battery()
if enum is None:
    POWER_TIME_UNKNOWN = -1
    POWER_TIME_UNLIMITED = -2
else:
    class BatteryTime(enum.IntEnum):
        POWER_TIME_UNKNOWN = -1
        POWER_TIME_UNLIMITED = -2

    globals().update(BatteryTime.__members__)

# --- others

ENCODING = sys.getfilesystemencoding()
if not PY3:
    ENCODING_ERRS = "replace"
else:
    try:
        ENCODING_ERRS = sys.getfilesystemencodeerrors()  # py 3.6
    except AttributeError:
        ENCODING_ERRS = "surrogateescape" if POSIX else "replace"


# ===================================================================
# --- namedtuples
# ===================================================================

# --- for system functions

# psutil.swap_memory()
sswap = namedtuple('sswap', ['total', 'used', 'free', 'percent', 'sin',
                             'sout'])
# psutil.disk_usage()
sdiskusage = namedtuple('sdiskusage', ['total', 'used', 'free', 'percent'])
# psutil.disk_io_counters()
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
                                 'read_bytes', 'write_bytes',
                                 'read_time', 'write_time'])
# psutil.disk_partitions()
sdiskpart = namedtuple('sdiskpart', ['device', 'mountpoint', 'fstype', 'opts'])
# psutil.net_io_counters()
snetio = namedtuple('snetio', ['bytes_sent', 'bytes_recv',
                               'packets_sent', 'packets_recv',
                               'errin', 'errout',
                               'dropin', 'dropout'])
# psutil.users()
suser = namedtuple('suser', ['name', 'terminal', 'host', 'started', 'pid'])
# psutil.net_connections()
sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr',
                             'status', 'pid'])
# psutil.net_if_addrs()
snic = namedtuple('snic', ['family', 'address', 'netmask', 'broadcast', 'ptp'])
# psutil.net_if_stats()
snicstats = namedtuple('snicstats', ['isup', 'duplex', 'speed', 'mtu'])
# psutil.cpu_stats()
scpustats = namedtuple(
    'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'])
# psutil.cpu_freq()
scpufreq = namedtuple('scpufreq', ['current', 'min', 'max'])
# psutil.sensors_temperatures()
shwtemp = namedtuple(
    'shwtemp', ['label', 'current', 'high', 'critical'])
# psutil.sensors_battery()
sbattery = namedtuple('sbattery', ['percent', 'secsleft', 'power_plugged'])
# psutil.sensors_battery()
sfan = namedtuple('sfan', ['label', 'current'])

# --- for Process methods

# psutil.Process.cpu_times()
pcputimes = namedtuple('pcputimes',
                       ['user', 'system', 'children_user', 'children_system'])
# psutil.Process.open_files()
popenfile = namedtuple('popenfile', ['path', 'fd'])
# psutil.Process.threads()
pthread = namedtuple('pthread', ['id', 'user_time', 'system_time'])
# psutil.Process.uids()
puids = namedtuple('puids', ['real', 'effective', 'saved'])
# psutil.Process.gids()
pgids = namedtuple('pgids', ['real', 'effective', 'saved'])
# psutil.Process.io_counters()
pio = namedtuple('pio', ['read_count', 'write_count',
                         'read_bytes', 'write_bytes'])
# psutil.Process.ionice()
pionice = namedtuple('pionice', ['ioclass', 'value'])
# psutil.Process.ctx_switches()
pctxsw = namedtuple('pctxsw', ['voluntary', 'involuntary'])
# psutil.Process.connections()
pconn = namedtuple('pconn', ['fd', 'family', 'type', 'laddr', 'raddr',
                             'status'])

# psutil.connections() and psutil.Process.connections()
addr = namedtuple('addr', ['ip', 'port'])


# ===================================================================
# --- Process.connections() 'kind' parameter mapping
# ===================================================================


conn_tmap = {
    "all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
    "tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]),
    "tcp4": ([AF_INET], [SOCK_STREAM]),
    "udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]),
    "udp4": ([AF_INET], [SOCK_DGRAM]),
    "inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
    "inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]),
    "inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
}

if AF_INET6 is not None:
    conn_tmap.update({
        "tcp6": ([AF_INET6], [SOCK_STREAM]),
        "udp6": ([AF_INET6], [SOCK_DGRAM]),
    })

if AF_UNIX is not None:
    conn_tmap.update({
        "unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
    })

del AF_INET, AF_UNIX, SOCK_STREAM, SOCK_DGRAM


# ===================================================================
# --- utils
# ===================================================================


def usage_percent(used, total, _round=None):
    """Calculate percentage usage of 'used' against 'total'."""
    try:
        ret = (used / total) * 100
    except ZeroDivisionError:
        ret = 0.0 if isinstance(used, float) or isinstance(total, float) else 0
    if _round is not None:
        return round(ret, _round)
    else:
        return ret


def memoize(fun):
    """A simple memoize decorator for functions supporting (hashable)
    positional arguments.
    It also provides a cache_clear() function for clearing the cache:

    >>> @memoize
    ... def foo()
    ...     return 1
        ...
    >>> foo()
    1
    >>> foo.cache_clear()
    >>>
    """
    @functools.wraps(fun)
    def wrapper(*args, **kwargs):
        key = (args, frozenset(sorted(kwargs.items())))
        try:
            return cache[key]
        except KeyError:
            ret = cache[key] = fun(*args, **kwargs)
            return ret

    def cache_clear():
        """Clear cache."""
        cache.clear()

    cache = {}
    wrapper.cache_clear = cache_clear
    return wrapper


def memoize_when_activated(fun):
    """A memoize decorator which is disabled by default. It can be
    activated and deactivated on request.
    For efficiency reasons it can be used only against class methods
    accepting no arguments.

    >>> class Foo:
    ...     @memoize
    ...     def foo()
    ...         print(1)
    ...
    >>> f = Foo()
    >>> # deactivated (default)
    >>> foo()
    1
    >>> foo()
    1
    >>>
    >>> # activated
    >>> foo.cache_activate()
    >>> foo()
    1
    >>> foo()
    >>> foo()
    >>>
    """
    @functools.wraps(fun)
    def wrapper(self):
        if not wrapper.cache_activated:
            return fun(self)
        else:
            try:
                ret = cache[fun]
            except KeyError:
                ret = cache[fun] = fun(self)
            return ret

    def cache_activate():
        """Activate cache."""
        wrapper.cache_activated = True

    def cache_deactivate():
        """Deactivate and clear cache."""
        wrapper.cache_activated = False
        cache.clear()

    cache = {}
    wrapper.cache_activated = False
    wrapper.cache_activate = cache_activate
    wrapper.cache_deactivate = cache_deactivate
    return wrapper


def isfile_strict(path):
    """Same as os.path.isfile() but does not swallow EACCES / EPERM
    exceptions, see:
    http://mail.python.org/pipermail/python-dev/2012-June/120787.html
    """
    try:
        st = os.stat(path)
    except OSError as err:
        if err.errno in (errno.EPERM, errno.EACCES):
            raise
        return False
    else:
        return stat.S_ISREG(st.st_mode)


def path_exists_strict(path):
    """Same as os.path.exists() but does not swallow EACCES / EPERM
    exceptions, see:
    http://mail.python.org/pipermail/python-dev/2012-June/120787.html
    """
    try:
        os.stat(path)
    except OSError as err:
        if err.errno in (errno.EPERM, errno.EACCES):
            raise
        return False
    else:
        return True


@memoize
def supports_ipv6():
    """Return True if IPv6 is supported on this platform."""
    if not socket.has_ipv6 or AF_INET6 is None:
        return False
    try:
        sock = socket.socket(AF_INET6, socket.SOCK_STREAM)
        with contextlib.closing(sock):
            sock.bind(("::1", 0))
        return True
    except socket.error:
        return False


def parse_environ_block(data):
    """Parse a C environ block of environment variables into a dictionary."""
    # The block is usually raw data from the target process.  It might contain
    # trailing garbage and lines that do not look like assignments.
    ret = {}
    pos = 0

    # localize global variable to speed up access.
    WINDOWS_ = WINDOWS
    while True:
        next_pos = data.find("\0", pos)
        # nul byte at the beginning or double nul byte means finish
        if next_pos <= pos:
            break
        # there might not be an equals sign
        equal_pos = data.find("=", pos, next_pos)
        if equal_pos > pos:
            key = data[pos:equal_pos]
            value = data[equal_pos + 1:next_pos]
            # Windows expects environment variables to be uppercase only
            if WINDOWS_:
                key = key.upper()
            ret[key] = value
        pos = next_pos + 1

    return ret


def sockfam_to_enum(num):
    """Convert a numeric socket family value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    """
    if enum is None:
        return num
    else:  # pragma: no cover
        try:
            return socket.AddressFamily(num)
        except (ValueError, AttributeError):
            return num


def socktype_to_enum(num):
    """Convert a numeric socket type value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    """
    if enum is None:
        return num
    else:  # pragma: no cover
        try:
            return socket.AddressType(num)
        except (ValueError, AttributeError):
            return num


def deprecated_method(replacement):
    """A decorator which can be used to mark a method as deprecated
    'replcement' is the method name which will be called instead.
    """
    def outer(fun):
        msg = "%s() is deprecated and will be removed; use %s() instead" % (
            fun.__name__, replacement)
        if fun.__doc__ is None:
            fun.__doc__ = msg

        @functools.wraps(fun)
        def inner(self, *args, **kwargs):
            warnings.warn(msg, category=FutureWarning, stacklevel=2)
            return getattr(self, replacement)(*args, **kwargs)
        return inner
    return outer


class _WrapNumbers:
    """Watches numbers so that they don't overflow and wrap
    (reset to zero).
    """

    def __init__(self):
        self.lock = threading.Lock()
        self.cache = {}
        self.reminders = {}
        self.reminder_keys = {}

    def _add_dict(self, input_dict, name):
        assert name not in self.cache
        assert name not in self.reminders
        assert name not in self.reminder_keys
        self.cache[name] = input_dict
        self.reminders[name] = defaultdict(int)
        self.reminder_keys[name] = defaultdict(set)

    def _remove_dead_reminders(self, input_dict, name):
        """In case the number of keys changed between calls (e.g. a
        disk disappears) this removes the entry from self.reminders.
        """
        old_dict = self.cache[name]
        gone_keys = set(old_dict.keys()) - set(input_dict.keys())
        for gone_key in gone_keys:
            for remkey in self.reminder_keys[name][gone_key]:
                del self.reminders[name][remkey]
            del self.reminder_keys[name][gone_key]

    def run(self, input_dict, name):
        """Cache dict and sum numbers which overflow and wrap.
        Return an updated copy of `input_dict`
        """
        if name not in self.cache:
            # This was the first call.
            self._add_dict(input_dict, name)
            return input_dict

        self._remove_dead_reminders(input_dict, name)

        old_dict = self.cache[name]
        new_dict = {}
        for key in input_dict.keys():
            input_tuple = input_dict[key]
            try:
                old_tuple = old_dict[key]
            except KeyError:
                # The input dict has a new key (e.g. a new disk or NIC)
                # which didn't exist in the previous call.
                new_dict[key] = input_tuple
                continue

            bits = []
            for i in range(len(input_tuple)):
                input_value = input_tuple[i]
                old_value = old_tuple[i]
                remkey = (key, i)
                if input_value < old_value:
                    # it wrapped!
                    self.reminders[name][remkey] += old_value
                    self.reminder_keys[name][key].add(remkey)
                bits.append(input_value + self.reminders[name][remkey])

            new_dict[key] = tuple(bits)

        self.cache[name] = input_dict
        return new_dict

    def cache_clear(self, name=None):
        """Clear the internal cache, optionally only for function 'name'."""
        with self.lock:
            if name is None:
                self.cache.clear()
                self.reminders.clear()
                self.reminder_keys.clear()
            else:
                self.cache.pop(name, None)
                self.reminders.pop(name, None)
                self.reminder_keys.pop(name, None)

    def cache_info(self):
        """Return internal cache dicts as a tuple of 3 elements."""
        with self.lock:
            return (self.cache, self.reminders, self.reminder_keys)


def wrap_numbers(input_dict, name):
    """Given an `input_dict` and a function `name`, adjust the numbers
    which "wrap" (restart from zero) across different calls by adding
    "old value" to "new value" and return an updated dict.
    """
    with _wn.lock:
        return _wn.run(input_dict, name)


_wn = _WrapNumbers()
wrap_numbers.cache_clear = _wn.cache_clear
wrap_numbers.cache_info = _wn.cache_info
_pswindows.py000064400000100541150466730530007324 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Windows platform implementation."""

import contextlib
import errno
import functools
import os
import sys
from collections import namedtuple

from . import _common
try:
    from . import _psutil_windows as cext
except ImportError as err:
    if str(err).lower().startswith("dll load failed") and \
            sys.getwindowsversion()[0] < 6:
        # We may get here if:
        # 1) we are on an old Windows version
        # 2) psutil was installed via pip + wheel
        # See: https://github.com/giampaolo/psutil/issues/811
        # It must be noted that psutil can still (kind of) work
        # on outdated systems if compiled / installed from sources,
        # but if we get here it means this this was a wheel (or exe).
        msg = "this Windows version is too old (< Windows Vista); "
        msg += "psutil 3.4.2 is the latest version which supports Windows "
        msg += "2000, XP and 2003 server; it may be possible that psutil "
        msg += "will work if compiled from sources though"
        raise RuntimeError(msg)
    else:
        raise

from ._common import conn_tmap
from ._common import ENCODING
from ._common import ENCODING_ERRS
from ._common import isfile_strict
from ._common import memoize_when_activated
from ._common import parse_environ_block
from ._common import sockfam_to_enum
from ._common import socktype_to_enum
from ._common import usage_percent
from ._compat import long
from ._compat import lru_cache
from ._compat import PY3
from ._compat import unicode
from ._compat import xrange
from ._exceptions import AccessDenied
from ._exceptions import NoSuchProcess
from ._exceptions import TimeoutExpired
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS
from ._psutil_windows import HIGH_PRIORITY_CLASS
from ._psutil_windows import IDLE_PRIORITY_CLASS
from ._psutil_windows import NORMAL_PRIORITY_CLASS
from ._psutil_windows import REALTIME_PRIORITY_CLASS

if sys.version_info >= (3, 4):
    import enum
else:
    enum = None

# process priority constants, import from __init__.py:
# http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
__extra__all__ = [
    "win_service_iter", "win_service_get",
    "ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
    "HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS",
    "NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS",
    "CONN_DELETE_TCB",
    "AF_LINK",
]


# =====================================================================
# --- globals
# =====================================================================

CONN_DELETE_TCB = "DELETE_TCB"
WAIT_TIMEOUT = 0x00000102  # 258 in decimal
ACCESS_DENIED_ERRSET = frozenset([errno.EPERM, errno.EACCES,
                                  cext.ERROR_ACCESS_DENIED])
NO_SUCH_SERVICE_ERRSET = frozenset([cext.ERROR_INVALID_NAME,
                                    cext.ERROR_SERVICE_DOES_NOT_EXIST])


if enum is None:
    AF_LINK = -1
else:
    AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1})
    AF_LINK = AddressFamily.AF_LINK

TCP_STATUSES = {
    cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED,
    cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT,
    cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV,
    cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1,
    cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2,
    cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT,
    cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE,
    cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
    cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK,
    cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN,
    cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING,
    cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB,
    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}

if enum is not None:
    class Priority(enum.IntEnum):
        ABOVE_NORMAL_PRIORITY_CLASS = ABOVE_NORMAL_PRIORITY_CLASS
        BELOW_NORMAL_PRIORITY_CLASS = BELOW_NORMAL_PRIORITY_CLASS
        HIGH_PRIORITY_CLASS = HIGH_PRIORITY_CLASS
        IDLE_PRIORITY_CLASS = IDLE_PRIORITY_CLASS
        NORMAL_PRIORITY_CLASS = NORMAL_PRIORITY_CLASS
        REALTIME_PRIORITY_CLASS = REALTIME_PRIORITY_CLASS

    globals().update(Priority.__members__)

pinfo_map = dict(
    num_handles=0,
    ctx_switches=1,
    user_time=2,
    kernel_time=3,
    create_time=4,
    num_threads=5,
    io_rcount=6,
    io_wcount=7,
    io_rbytes=8,
    io_wbytes=9,
    io_count_others=10,
    io_bytes_others=11,
    num_page_faults=12,
    peak_wset=13,
    wset=14,
    peak_paged_pool=15,
    paged_pool=16,
    peak_non_paged_pool=17,
    non_paged_pool=18,
    pagefile=19,
    peak_pagefile=20,
    mem_private=21,
)


# =====================================================================
# --- named tuples
# =====================================================================


# psutil.cpu_times()
scputimes = namedtuple('scputimes',
                       ['user', 'system', 'idle', 'interrupt', 'dpc'])
# psutil.virtual_memory()
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
# psutil.Process.memory_info()
pmem = namedtuple(
    'pmem', ['rss', 'vms',
             'num_page_faults', 'peak_wset', 'wset', 'peak_paged_pool',
             'paged_pool', 'peak_nonpaged_pool', 'nonpaged_pool',
             'pagefile', 'peak_pagefile', 'private'])
# psutil.Process.memory_full_info()
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss'])
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
    'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
# psutil.Process.io_counters()
pio = namedtuple('pio', ['read_count', 'write_count',
                         'read_bytes', 'write_bytes',
                         'other_count', 'other_bytes'])


# =====================================================================
# --- utils
# =====================================================================


@lru_cache(maxsize=512)
def convert_dos_path(s):
    r"""Convert paths using native DOS format like:
        "\Device\HarddiskVolume1\Windows\systemew\file.txt"
    into:
        "C:\Windows\systemew\file.txt"
    """
    rawdrive = '\\'.join(s.split('\\')[:3])
    driveletter = cext.win32_QueryDosDevice(rawdrive)
    return os.path.join(driveletter, s[len(rawdrive):])


def py2_strencode(s):
    """Encode a unicode string to a byte string by using the default fs
    encoding + "replace" error handler.
    """
    if PY3:
        return s
    else:
        if isinstance(s, str):
            return s
        else:
            return s.encode(ENCODING, errors=ENCODING_ERRS)


# =====================================================================
# --- memory
# =====================================================================


def virtual_memory():
    """System virtual memory as a namedtuple."""
    mem = cext.virtual_mem()
    totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem
    #
    total = totphys
    avail = availphys
    free = availphys
    used = total - avail
    percent = usage_percent((total - avail), total, _round=1)
    return svmem(total, avail, percent, used, free)


def swap_memory():
    """Swap system memory as a (total, used, free, sin, sout) tuple."""
    mem = cext.virtual_mem()
    total = mem[2]
    free = mem[3]
    used = total - free
    percent = usage_percent(used, total, _round=1)
    return _common.sswap(total, used, free, percent, 0, 0)


# =====================================================================
# --- disk
# =====================================================================


disk_io_counters = cext.disk_io_counters


def disk_usage(path):
    """Return disk usage associated with path."""
    if PY3 and isinstance(path, bytes):
        # XXX: do we want to use "strict"? Probably yes, in order
        # to fail immediately. After all we are accepting input here...
        path = path.decode(ENCODING, errors="strict")
    total, free = cext.disk_usage(path)
    used = total - free
    percent = usage_percent(used, total, _round=1)
    return _common.sdiskusage(total, used, free, percent)


def disk_partitions(all):
    """Return disk partitions."""
    rawlist = cext.disk_partitions(all)
    return [_common.sdiskpart(*x) for x in rawlist]


# =====================================================================
# --- CPU
# =====================================================================


def cpu_times():
    """Return system CPU times as a named tuple."""
    user, system, idle = cext.cpu_times()
    # Internally, GetSystemTimes() is used, and it doesn't return
    # interrupt and dpc times. cext.per_cpu_times() does, so we
    # rely on it to get those only.
    percpu_summed = scputimes(*[sum(n) for n in zip(*cext.per_cpu_times())])
    return scputimes(user, system, idle,
                     percpu_summed.interrupt, percpu_summed.dpc)


def per_cpu_times():
    """Return system per-CPU times as a list of named tuples."""
    ret = []
    for user, system, idle, interrupt, dpc in cext.per_cpu_times():
        item = scputimes(user, system, idle, interrupt, dpc)
        ret.append(item)
    return ret


def cpu_count_logical():
    """Return the number of logical CPUs in the system."""
    return cext.cpu_count_logical()


def cpu_count_physical():
    """Return the number of physical CPUs in the system."""
    return cext.cpu_count_phys()


def cpu_stats():
    """Return CPU statistics."""
    ctx_switches, interrupts, dpcs, syscalls = cext.cpu_stats()
    soft_interrupts = 0
    return _common.scpustats(ctx_switches, interrupts, soft_interrupts,
                             syscalls)


def cpu_freq():
    """Return CPU frequency.
    On Windows per-cpu frequency is not supported.
    """
    curr, max_ = cext.cpu_freq()
    min_ = 0.0
    return [_common.scpufreq(float(curr), min_, float(max_))]


# =====================================================================
# --- network
# =====================================================================


def net_connections(kind, _pid=-1):
    """Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    """
    if kind not in conn_tmap:
        raise ValueError("invalid %r kind argument; choose between %s"
                         % (kind, ', '.join([repr(x) for x in conn_tmap])))
    families, types = conn_tmap[kind]
    rawlist = cext.net_connections(_pid, families, types)
    ret = set()
    for item in rawlist:
        fd, fam, type, laddr, raddr, status, pid = item
        if laddr:
            laddr = _common.addr(*laddr)
        if raddr:
            raddr = _common.addr(*raddr)
        status = TCP_STATUSES[status]
        fam = sockfam_to_enum(fam)
        type = socktype_to_enum(type)
        if _pid == -1:
            nt = _common.sconn(fd, fam, type, laddr, raddr, status, pid)
        else:
            nt = _common.pconn(fd, fam, type, laddr, raddr, status)
        ret.add(nt)
    return list(ret)


def net_if_stats():
    """Get NIC stats (isup, duplex, speed, mtu)."""
    ret = {}
    rawdict = cext.net_if_stats()
    for name, items in rawdict.items():
        if not PY3:
            assert isinstance(name, unicode), type(name)
            name = py2_strencode(name)
        isup, duplex, speed, mtu = items
        if hasattr(_common, 'NicDuplex'):
            duplex = _common.NicDuplex(duplex)
        ret[name] = _common.snicstats(isup, duplex, speed, mtu)
    return ret


def net_io_counters():
    """Return network I/O statistics for every network interface
    installed on the system as a dict of raw tuples.
    """
    ret = cext.net_io_counters()
    return dict([(py2_strencode(k), v) for k, v in ret.items()])


def net_if_addrs():
    """Return the addresses associated to each NIC."""
    ret = []
    for items in cext.net_if_addrs():
        items = list(items)
        items[0] = py2_strencode(items[0])
        ret.append(items)
    return ret


# =====================================================================
# --- sensors
# =====================================================================


def sensors_battery():
    """Return battery information."""
    # For constants meaning see:
    # https://msdn.microsoft.com/en-us/library/windows/desktop/
    #     aa373232(v=vs.85).aspx
    acline_status, flags, percent, secsleft = cext.sensors_battery()
    power_plugged = acline_status == 1
    no_battery = bool(flags & 128)
    charging = bool(flags & 8)

    if no_battery:
        return None
    if power_plugged or charging:
        secsleft = _common.POWER_TIME_UNLIMITED
    elif secsleft == -1:
        secsleft = _common.POWER_TIME_UNKNOWN

    return _common.sbattery(percent, secsleft, power_plugged)


# =====================================================================
# --- other system functions
# =====================================================================


_last_btime = 0


def boot_time():
    """The system boot time expressed in seconds since the epoch."""
    # This dirty hack is to adjust the precision of the returned
    # value which may have a 1 second fluctuation, see:
    # https://github.com/giampaolo/psutil/issues/1007
    global _last_btime
    ret = float(cext.boot_time())
    if abs(ret - _last_btime) <= 1:
        return _last_btime
    else:
        _last_btime = ret
        return ret


def users():
    """Return currently connected users as a list of namedtuples."""
    retlist = []
    rawlist = cext.users()
    for item in rawlist:
        user, hostname, tstamp = item
        user = py2_strencode(user)
        nt = _common.suser(user, None, hostname, tstamp, None)
        retlist.append(nt)
    return retlist


# =====================================================================
# --- Windows services
# =====================================================================


def win_service_iter():
    """Yields a list of WindowsService instances."""
    for name, display_name in cext.winservice_enumerate():
        yield WindowsService(py2_strencode(name), py2_strencode(display_name))


def win_service_get(name):
    """Open a Windows service and return it as a WindowsService instance."""
    service = WindowsService(name, None)
    service._display_name = service._query_config()['display_name']
    return service


class WindowsService(object):
    """Represents an installed Windows service."""

    def __init__(self, name, display_name):
        self._name = name
        self._display_name = display_name

    def __str__(self):
        details = "(name=%r, display_name=%r)" % (
            self._name, self._display_name)
        return "%s%s" % (self.__class__.__name__, details)

    def __repr__(self):
        return "<%s at %s>" % (self.__str__(), id(self))

    def __eq__(self, other):
        # Test for equality with another WindosService object based
        # on name.
        if not isinstance(other, WindowsService):
            return NotImplemented
        return self._name == other._name

    def __ne__(self, other):
        return not self == other

    def _query_config(self):
        with self._wrap_exceptions():
            display_name, binpath, username, start_type = \
                cext.winservice_query_config(self._name)
        # XXX - update _self.display_name?
        return dict(
            display_name=py2_strencode(display_name),
            binpath=py2_strencode(binpath),
            username=py2_strencode(username),
            start_type=py2_strencode(start_type))

    def _query_status(self):
        with self._wrap_exceptions():
            status, pid = cext.winservice_query_status(self._name)
        if pid == 0:
            pid = None
        return dict(status=status, pid=pid)

    @contextlib.contextmanager
    def _wrap_exceptions(self):
        """Ctx manager which translates bare OSError and WindowsError
        exceptions into NoSuchProcess and AccessDenied.
        """
        try:
            yield
        except WindowsError as err:
            if err.errno in ACCESS_DENIED_ERRSET:
                raise AccessDenied(
                    pid=None, name=self._name,
                    msg="service %r is not querable (not enough privileges)" %
                        self._name)
            elif err.errno in NO_SUCH_SERVICE_ERRSET or \
                    err.winerror in NO_SUCH_SERVICE_ERRSET:
                raise NoSuchProcess(
                    pid=None, name=self._name,
                    msg="service %r does not exist)" % self._name)
            else:
                raise

    # config query

    def name(self):
        """The service name. This string is how a service is referenced
        and can be passed to win_service_get() to get a new
        WindowsService instance.
        """
        return self._name

    def display_name(self):
        """The service display name. The value is cached when this class
        is instantiated.
        """
        return self._display_name

    def binpath(self):
        """The fully qualified path to the service binary/exe file as
        a string, including command line arguments.
        """
        return self._query_config()['binpath']

    def username(self):
        """The name of the user that owns this service."""
        return self._query_config()['username']

    def start_type(self):
        """A string which can either be "automatic", "manual" or
        "disabled".
        """
        return self._query_config()['start_type']

    # status query

    def pid(self):
        """The process PID, if any, else None. This can be passed
        to Process class to control the service's process.
        """
        return self._query_status()['pid']

    def status(self):
        """Service status as a string."""
        return self._query_status()['status']

    def description(self):
        """Service long description."""
        return py2_strencode(cext.winservice_query_descr(self.name()))

    # utils

    def as_dict(self):
        """Utility method retrieving all the information above as a
        dictionary.
        """
        d = self._query_config()
        d.update(self._query_status())
        d['name'] = self.name()
        d['display_name'] = self.display_name()
        d['description'] = self.description()
        return d

    # actions
    # XXX: the necessary C bindings for start() and stop() are
    # implemented but for now I prefer not to expose them.
    # I may change my mind in the future. Reasons:
    # - they require Administrator privileges
    # - can't implement a timeout for stop() (unless by using a thread,
    #   which sucks)
    # - would require adding ServiceAlreadyStarted and
    #   ServiceAlreadyStopped exceptions, adding two new APIs.
    # - we might also want to have modify(), which would basically mean
    #   rewriting win32serviceutil.ChangeServiceConfig, which involves a
    #   lot of stuff (and API constants which would pollute the API), see:
    #   http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/
    #       win32/lib/win32serviceutil.py.html#0175
    # - psutil is typically about "read only" monitoring stuff;
    #   win_service_* APIs should only be used to retrieve a service and
    #   check whether it's running

    # def start(self, timeout=None):
    #     with self._wrap_exceptions():
    #         cext.winservice_start(self.name())
    #         if timeout:
    #             giveup_at = time.time() + timeout
    #             while True:
    #                 if self.status() == "running":
    #                     return
    #                 else:
    #                     if time.time() > giveup_at:
    #                         raise TimeoutExpired(timeout)
    #                     else:
    #                         time.sleep(.1)

    # def stop(self):
    #     # Note: timeout is not implemented because it's just not
    #     # possible, see:
    #     # http://stackoverflow.com/questions/11973228/
    #     with self._wrap_exceptions():
    #         return cext.winservice_stop(self.name())


# =====================================================================
# --- processes
# =====================================================================


pids = cext.pids
pid_exists = cext.pid_exists
ppid_map = cext.ppid_map  # used internally by Process.children()


def wrap_exceptions(fun):
    """Decorator which translates bare OSError and WindowsError
    exceptions into NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            if err.errno in ACCESS_DENIED_ERRSET:
                raise AccessDenied(self.pid, self._name)
            if err.errno == errno.ESRCH:
                raise NoSuchProcess(self.pid, self._name)
            raise
    return wrapper


class Process(object):
    """Wrapper class around underlying C implementation."""

    __slots__ = ["pid", "_name", "_ppid"]

    def __init__(self, pid):
        self.pid = pid
        self._name = None
        self._ppid = None

    # --- oneshot() stuff

    def oneshot_enter(self):
        self.oneshot_info.cache_activate()

    def oneshot_exit(self):
        self.oneshot_info.cache_deactivate()

    @memoize_when_activated
    def oneshot_info(self):
        """Return multiple information about this process as a
        raw tuple.
        """
        ret = cext.proc_info(self.pid)
        assert len(ret) == len(pinfo_map)
        return ret

    @wrap_exceptions
    def name(self):
        """Return process name, which on Windows is always the final
        part of the executable.
        """
        # This is how PIDs 0 and 4 are always represented in taskmgr
        # and process-hacker.
        if self.pid == 0:
            return "System Idle Process"
        elif self.pid == 4:
            return "System"
        else:
            try:
                # Note: this will fail with AD for most PIDs owned
                # by another user but it's faster.
                return py2_strencode(os.path.basename(self.exe()))
            except AccessDenied:
                return py2_strencode(cext.proc_name(self.pid))

    @wrap_exceptions
    def exe(self):
        # Note: os.path.exists(path) may return False even if the file
        # is there, see:
        # http://stackoverflow.com/questions/3112546/os-path-exists-lies

        # see https://github.com/giampaolo/psutil/issues/414
        # see https://github.com/giampaolo/psutil/issues/528
        if self.pid in (0, 4):
            raise AccessDenied(self.pid, self._name)
        return py2_strencode(convert_dos_path(cext.proc_exe(self.pid)))

    @wrap_exceptions
    def cmdline(self):
        ret = cext.proc_cmdline(self.pid)
        if PY3:
            return ret
        else:
            return [py2_strencode(s) for s in ret]

    @wrap_exceptions
    def environ(self):
        ustr = cext.proc_environ(self.pid)
        if ustr and not PY3:
            assert isinstance(ustr, unicode), type(ustr)
        return parse_environ_block(py2_strencode(ustr))

    def ppid(self):
        try:
            return ppid_map()[self.pid]
        except KeyError:
            raise NoSuchProcess(self.pid, self._name)

    def _get_raw_meminfo(self):
        try:
            return cext.proc_memory_info(self.pid)
        except OSError as err:
            if err.errno in ACCESS_DENIED_ERRSET:
                # TODO: the C ext can probably be refactored in order
                # to get this from cext.proc_info()
                info = self.oneshot_info()
                return (
                    info[pinfo_map['num_page_faults']],
                    info[pinfo_map['peak_wset']],
                    info[pinfo_map['wset']],
                    info[pinfo_map['peak_paged_pool']],
                    info[pinfo_map['paged_pool']],
                    info[pinfo_map['peak_non_paged_pool']],
                    info[pinfo_map['non_paged_pool']],
                    info[pinfo_map['pagefile']],
                    info[pinfo_map['peak_pagefile']],
                    info[pinfo_map['mem_private']],
                )
            raise

    @wrap_exceptions
    def memory_info(self):
        # on Windows RSS == WorkingSetSize and VSM == PagefileUsage.
        # Underlying C function returns fields of PROCESS_MEMORY_COUNTERS
        # struct.
        t = self._get_raw_meminfo()
        rss = t[2]  # wset
        vms = t[7]  # pagefile
        return pmem(*(rss, vms, ) + t)

    @wrap_exceptions
    def memory_full_info(self):
        basic_mem = self.memory_info()
        uss = cext.proc_memory_uss(self.pid)
        return pfullmem(*basic_mem + (uss, ))

    def memory_maps(self):
        try:
            raw = cext.proc_memory_maps(self.pid)
        except OSError as err:
            # XXX - can't use wrap_exceptions decorator as we're
            # returning a generator; probably needs refactoring.
            if err.errno in ACCESS_DENIED_ERRSET:
                raise AccessDenied(self.pid, self._name)
            if err.errno == errno.ESRCH:
                raise NoSuchProcess(self.pid, self._name)
            raise
        else:
            for addr, perm, path, rss in raw:
                path = convert_dos_path(path)
                if not PY3:
                    assert isinstance(path, unicode), type(path)
                    path = py2_strencode(path)
                addr = hex(addr)
                yield (addr, perm, path, rss)

    @wrap_exceptions
    def kill(self):
        return cext.proc_kill(self.pid)

    @wrap_exceptions
    def send_signal(self, sig):
        os.kill(self.pid, sig)

    @wrap_exceptions
    def wait(self, timeout=None):
        if timeout is None:
            cext_timeout = cext.INFINITE
        else:
            # WaitForSingleObject() expects time in milliseconds
            cext_timeout = int(timeout * 1000)
        while True:
            ret = cext.proc_wait(self.pid, cext_timeout)
            if ret == WAIT_TIMEOUT:
                raise TimeoutExpired(timeout, self.pid, self._name)
            if pid_exists(self.pid):
                if timeout is None:
                    continue
                else:
                    raise TimeoutExpired(timeout, self.pid, self._name)
            return ret

    @wrap_exceptions
    def username(self):
        if self.pid in (0, 4):
            return 'NT AUTHORITY\\SYSTEM'
        domain, user = cext.proc_username(self.pid)
        return py2_strencode(domain) + '\\' + py2_strencode(user)

    @wrap_exceptions
    def create_time(self):
        # special case for kernel process PIDs; return system boot time
        if self.pid in (0, 4):
            return boot_time()
        try:
            return cext.proc_create_time(self.pid)
        except OSError as err:
            if err.errno in ACCESS_DENIED_ERRSET:
                return self.oneshot_info()[pinfo_map['create_time']]
            raise

    @wrap_exceptions
    def num_threads(self):
        return self.oneshot_info()[pinfo_map['num_threads']]

    @wrap_exceptions
    def threads(self):
        rawlist = cext.proc_threads(self.pid)
        retlist = []
        for thread_id, utime, stime in rawlist:
            ntuple = _common.pthread(thread_id, utime, stime)
            retlist.append(ntuple)
        return retlist

    @wrap_exceptions
    def cpu_times(self):
        try:
            user, system = cext.proc_cpu_times(self.pid)
        except OSError as err:
            if err.errno in ACCESS_DENIED_ERRSET:
                info = self.oneshot_info()
                user = info[pinfo_map['user_time']]
                system = info[pinfo_map['kernel_time']]
            else:
                raise
        # Children user/system times are not retrievable (set to 0).
        return _common.pcputimes(user, system, 0.0, 0.0)

    @wrap_exceptions
    def suspend(self):
        return cext.proc_suspend(self.pid)

    @wrap_exceptions
    def resume(self):
        return cext.proc_resume(self.pid)

    @wrap_exceptions
    def cwd(self):
        if self.pid in (0, 4):
            raise AccessDenied(self.pid, self._name)
        # return a normalized pathname since the native C function appends
        # "\\" at the and of the path
        path = cext.proc_cwd(self.pid)
        return py2_strencode(os.path.normpath(path))

    @wrap_exceptions
    def open_files(self):
        if self.pid in (0, 4):
            return []
        ret = set()
        # Filenames come in in native format like:
        # "\Device\HarddiskVolume1\Windows\systemew\file.txt"
        # Convert the first part in the corresponding drive letter
        # (e.g. "C:\") by using Windows's QueryDosDevice()
        raw_file_names = cext.proc_open_files(self.pid)
        for _file in raw_file_names:
            _file = convert_dos_path(_file)
            if isfile_strict(_file):
                if not PY3:
                    _file = py2_strencode(_file)
                ntuple = _common.popenfile(_file, -1)
                ret.add(ntuple)
        return list(ret)

    @wrap_exceptions
    def connections(self, kind='inet'):
        return net_connections(kind, _pid=self.pid)

    @wrap_exceptions
    def nice_get(self):
        value = cext.proc_priority_get(self.pid)
        if enum is not None:
            value = Priority(value)
        return value

    @wrap_exceptions
    def nice_set(self, value):
        return cext.proc_priority_set(self.pid, value)

    # available on Windows >= Vista
    if hasattr(cext, "proc_io_priority_get"):
        @wrap_exceptions
        def ionice_get(self):
            return cext.proc_io_priority_get(self.pid)

        @wrap_exceptions
        def ionice_set(self, value, _):
            if _:
                raise TypeError("set_proc_ionice() on Windows takes only "
                                "1 argument (2 given)")
            if value not in (2, 1, 0):
                raise ValueError("value must be 2 (normal), 1 (low) or 0 "
                                 "(very low); got %r" % value)
            return cext.proc_io_priority_set(self.pid, value)

    @wrap_exceptions
    def io_counters(self):
        try:
            ret = cext.proc_io_counters(self.pid)
        except OSError as err:
            if err.errno in ACCESS_DENIED_ERRSET:
                info = self.oneshot_info()
                ret = (
                    info[pinfo_map['io_rcount']],
                    info[pinfo_map['io_wcount']],
                    info[pinfo_map['io_rbytes']],
                    info[pinfo_map['io_wbytes']],
                    info[pinfo_map['io_count_others']],
                    info[pinfo_map['io_bytes_others']],
                )
            else:
                raise
        return pio(*ret)

    @wrap_exceptions
    def status(self):
        suspended = cext.proc_is_suspended(self.pid)
        if suspended:
            return _common.STATUS_STOPPED
        else:
            return _common.STATUS_RUNNING

    @wrap_exceptions
    def cpu_affinity_get(self):
        def from_bitmask(x):
            return [i for i in xrange(64) if (1 << i) & x]
        bitmask = cext.proc_cpu_affinity_get(self.pid)
        return from_bitmask(bitmask)

    @wrap_exceptions
    def cpu_affinity_set(self, value):
        def to_bitmask(l):
            if not l:
                raise ValueError("invalid argument %r" % l)
            out = 0
            for b in l:
                out |= 2 ** b
            return out

        # SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
        # is returned for an invalid CPU but this seems not to be true,
        # therefore we check CPUs validy beforehand.
        allcpus = list(range(len(per_cpu_times())))
        for cpu in value:
            if cpu not in allcpus:
                if not isinstance(cpu, (int, long)):
                    raise TypeError(
                        "invalid CPU %r; an integer is required" % cpu)
                else:
                    raise ValueError("invalid CPU %r" % cpu)

        bitmask = to_bitmask(value)
        cext.proc_cpu_affinity_set(self.pid, bitmask)

    @wrap_exceptions
    def num_handles(self):
        try:
            return cext.proc_num_handles(self.pid)
        except OSError as err:
            if err.errno in ACCESS_DENIED_ERRSET:
                return self.oneshot_info()[pinfo_map['num_handles']]
            raise

    @wrap_exceptions
    def num_ctx_switches(self):
        ctx_switches = self.oneshot_info()[pinfo_map['ctx_switches']]
        # only voluntary ctx switches are supported
        return _common.pctxsw(ctx_switches, 0)
_compat.py000064400000017752150466730530006565 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Module which provides compatibility with older Python versions."""

import collections
import functools
import os
import sys

__all__ = ["PY3", "long", "xrange", "unicode", "basestring", "u", "b",
           "callable", "lru_cache", "which"]

PY3 = sys.version_info[0] == 3

if PY3:
    long = int
    xrange = range
    unicode = str
    basestring = str

    def u(s):
        return s

    def b(s):
        return s.encode("latin-1")
else:
    long = long
    xrange = xrange
    unicode = unicode
    basestring = basestring

    def u(s):
        return unicode(s, "unicode_escape")

    def b(s):
        return s


# removed in 3.0, reintroduced in 3.2
try:
    callable = callable
except NameError:
    def callable(obj):
        return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)


# --- stdlib additions


# py 3.2 functools.lru_cache
# Taken from: http://code.activestate.com/recipes/578078
# Credit: Raymond Hettinger
try:
    from functools import lru_cache
except ImportError:
    try:
        from threading import RLock
    except ImportError:
        from dummy_threading import RLock

    _CacheInfo = collections.namedtuple(
        "CacheInfo", ["hits", "misses", "maxsize", "currsize"])

    class _HashedSeq(list):
        __slots__ = 'hashvalue'

        def __init__(self, tup, hash=hash):
            self[:] = tup
            self.hashvalue = hash(tup)

        def __hash__(self):
            return self.hashvalue

    def _make_key(args, kwds, typed,
                  kwd_mark=(object(), ),
                  fasttypes=set((int, str, frozenset, type(None))),
                  sorted=sorted, tuple=tuple, type=type, len=len):
        key = args
        if kwds:
            sorted_items = sorted(kwds.items())
            key += kwd_mark
            for item in sorted_items:
                key += item
        if typed:
            key += tuple(type(v) for v in args)
            if kwds:
                key += tuple(type(v) for k, v in sorted_items)
        elif len(key) == 1 and type(key[0]) in fasttypes:
            return key[0]
        return _HashedSeq(key)

    def lru_cache(maxsize=100, typed=False):
        """Least-recently-used cache decorator, see:
        http://docs.python.org/3/library/functools.html#functools.lru_cache
        """
        def decorating_function(user_function):
            cache = dict()
            stats = [0, 0]
            HITS, MISSES = 0, 1
            make_key = _make_key
            cache_get = cache.get
            _len = len
            lock = RLock()
            root = []
            root[:] = [root, root, None, None]
            nonlocal_root = [root]
            PREV, NEXT, KEY, RESULT = 0, 1, 2, 3
            if maxsize == 0:
                def wrapper(*args, **kwds):
                    result = user_function(*args, **kwds)
                    stats[MISSES] += 1
                    return result
            elif maxsize is None:
                def wrapper(*args, **kwds):
                    key = make_key(args, kwds, typed)
                    result = cache_get(key, root)
                    if result is not root:
                        stats[HITS] += 1
                        return result
                    result = user_function(*args, **kwds)
                    cache[key] = result
                    stats[MISSES] += 1
                    return result
            else:
                def wrapper(*args, **kwds):
                    if kwds or typed:
                        key = make_key(args, kwds, typed)
                    else:
                        key = args
                    lock.acquire()
                    try:
                        link = cache_get(key)
                        if link is not None:
                            root, = nonlocal_root
                            link_prev, link_next, key, result = link
                            link_prev[NEXT] = link_next
                            link_next[PREV] = link_prev
                            last = root[PREV]
                            last[NEXT] = root[PREV] = link
                            link[PREV] = last
                            link[NEXT] = root
                            stats[HITS] += 1
                            return result
                    finally:
                        lock.release()
                    result = user_function(*args, **kwds)
                    lock.acquire()
                    try:
                        root, = nonlocal_root
                        if key in cache:
                            pass
                        elif _len(cache) >= maxsize:
                            oldroot = root
                            oldroot[KEY] = key
                            oldroot[RESULT] = result
                            root = nonlocal_root[0] = oldroot[NEXT]
                            oldkey = root[KEY]
                            root[KEY] = root[RESULT] = None
                            del cache[oldkey]
                            cache[key] = oldroot
                        else:
                            last = root[PREV]
                            link = [last, root, key, result]
                            last[NEXT] = root[PREV] = cache[key] = link
                        stats[MISSES] += 1
                    finally:
                        lock.release()
                    return result

            def cache_info():
                """Report cache statistics"""
                lock.acquire()
                try:
                    return _CacheInfo(stats[HITS], stats[MISSES], maxsize,
                                      len(cache))
                finally:
                    lock.release()

            def cache_clear():
                """Clear the cache and cache statistics"""
                lock.acquire()
                try:
                    cache.clear()
                    root = nonlocal_root[0]
                    root[:] = [root, root, None, None]
                    stats[:] = [0, 0]
                finally:
                    lock.release()

            wrapper.__wrapped__ = user_function
            wrapper.cache_info = cache_info
            wrapper.cache_clear = cache_clear
            return functools.update_wrapper(wrapper, user_function)

        return decorating_function


# python 3.3
try:
    from shutil import which
except ImportError:
    def which(cmd, mode=os.F_OK | os.X_OK, path=None):
        """Given a command, mode, and a PATH string, return the path which
        conforms to the given mode on the PATH, or None if there is no such
        file.

        `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
        of os.environ.get("PATH"), or can be overridden with a custom search
        path.
        """
        def _access_check(fn, mode):
            return (os.path.exists(fn) and os.access(fn, mode) and
                    not os.path.isdir(fn))

        if os.path.dirname(cmd):
            if _access_check(cmd, mode):
                return cmd
            return None

        if path is None:
            path = os.environ.get("PATH", os.defpath)
        if not path:
            return None
        path = path.split(os.pathsep)

        if sys.platform == "win32":
            if os.curdir not in path:
                path.insert(0, os.curdir)

            pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
            if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
                files = [cmd]
            else:
                files = [cmd + ext for ext in pathext]
        else:
            files = [cmd]

        seen = set()
        for dir in path:
            normdir = os.path.normcase(dir)
            if normdir not in seen:
                seen.add(normdir)
                for thefile in files:
                    name = os.path.join(dir, thefile)
                    if _access_check(name, mode):
                        return name
        return None
__pycache__/_exceptions.cpython-36.opt-1.pyc000064400000006323150466730530014676 0ustar003

��JZ��@sTGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd	�d	e�Zd
S)c@s&eZdZdZddd�Zdd�ZeZdS)	�ErrorzQBase exception class. All other psutil exceptions inherit
    from this one.
    �cCstj||�||_dS)N)�	Exception�__init__�msg)�selfr�r�#/usr/lib64/python3.6/_exceptions.pyrszError.__init__cCsd|jj|jf}|j�S)Nzpsutil.%s %s)�	__class__�__name__r�strip)r�retrrr�__repr__szError.__repr__N)r)r
�
__module__�__qualname__�__doc__rr
�__str__rrrrrs
rc@seZdZdZddd�ZdS)�
NoSuchProcesszXException raised when a process with a certain PID doesn't
    or no longer exists.
    NcCsXtj||�||_||_||_|dkrT|r@d|jt|j�f}n
d|j}d||_dS)Nz(pid=%s, name=%s)z(pid=%s)zprocess no longer exists )rr�pid�namer�repr)rrrr�detailsrrrrs
zNoSuchProcess.__init__)NN)r
rrrrrrrrrsrc@seZdZdZddd�ZdS)�
ZombieProcessa/Exception raised when querying a zombie process. This is
    raised on OSX, BSD and Solaris only, and not always: depending
    on the query the OS may be able to succeed anyway.
    On Linux all zombie processes are querable (hence this is never
    raised). Windows doesn't have zombie processes.
    NcCs~tj||�||_||_||_||_|dkrzd|g}|rN|jdt|j��|rb|jd|j�ddj|�}d||_dS)Nzpid=%szname=%szppid=%sz(%s)z, z'process still exists but it's a zombie )	rrr�ppidrr�appendr�join)rrrrr�argsrrrrr0s
zZombieProcess.__init__)NNN)r
rrrrrrrrr(src@seZdZdZddd�ZdS)�AccessDeniedz@Exception raised when permission to perform an action is denied.NcCsjtj||�||_||_||_|dkrf|dk	rJ|dk	rJd|t|�f|_n|dk	r`d|j|_nd|_dS)Nz(pid=%s, name=%s)z(pid=%s)r)rrrrrr)rrrrrrrrCszAccessDenied.__init__)NNN)r
rrrrrrrrr@src@seZdZdZddd�ZdS)�TimeoutExpiredzWRaised on Process.wait(timeout) if timeout expires and process
    is still alive.
    NcCsntj|d|�||_||_||_|dk	rN|dk	rN|jd|t|�f7_n|dk	rj|jd|j7_dS)Nztimeout after %s secondsz (pid=%s, name=%s)z	 (pid=%s))rr�secondsrrrr)rrrrrrrrVszTimeoutExpired.__init__)NN)r
rrrrrrrrrQsrN)rrrrrrrrrr�<module>s__pycache__/_common.cpython-36.opt-1.pyc000064400000031566150466730530014014 0ustar003

��JZ�E�V@s.dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlm
Z
ddlmZddlmZddlmZddlmZydd	lmZWnek
r�dZYnXydd
lmZWnek
r�dZYnXe	jd�k�r�ddlZndZe	jddkZd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRgFZejdSkZejdTkZe	jjdU�Ze	jjdV�Ze	jjdW�Z e	jjdX�Z!e	jjdY�Z"e �p�e!�p�e"Z#e	jjdZ��pe	jjd[�Z$e	jjd\�Z%d]Z&d^Z'd_Z(d`Z)daZ*dbZ+dcZ,ddZ-deZ.dfZ/dgZ0dhZ1diZ2djZ3dkZ4dlZ5dmZ6dnZ7doZ8dpZ9dqZ:drZ;dsZ<dtZ=duZ>edk�r�dvZ?dwZ@dZAn Gdxdy�dyejB�ZCeD�jEeCjF�edk�r�d�ZGd�ZHn Gdzd{�d{ejB�ZIeD�jEeIjF�e	jJ�ZKe�s
d|ZLn2ye	jM�ZLWn$eNk
�r:e�r2d}nd|ZLYnXedFd~dd�d�d�d�g�ZOedBd~dd�d�g�ZPed@d�d�d�d�d�d�g�ZQedAd�d�d�d�g�ZRedCd�d�d�d�d�d�d�d�g�ZSedGd�d�d�d�d�g�ZTed>d�d�d�d�d�d�d�g�ZUedDd�d�d�d�d�g�ZVedEd�d�d�d�g�ZWed?d�d�d�d�g�ZXed�d�d�d�g�ZYed�d�d�d�d�g�ZZed�d�d�d�g�Z[ed�d�d�g�Z\ed6d�d�d�d�g�Z]ed;d�d�g�Z^ed<d�d�d�g�Z_ed=d�d�d�g�Z`ed8d�d�d�g�Zaed9d�d�d�d�g�Zbed:d�d�g�Zced7d�d�g�Zded5d�d�d�d�d�d�g�Zeed�d�d�g�Zfeeegeegfeegegfegegfeegegfegegfeegeegfegeegfegeegfd˜Zgedk	�r~egjEegegfegegfd̜�edk	�r�egjEd�egeegfi�[[[[d�d�dN�Zhd�dK�Zid�dфZjd�dJ�Zkd�dM�Zleid�dO��Zmd�dL�Znd�dP�Zod�dQ�Zpd�dI�ZqGd�dڄdڃZrd�dR�Zser�Ztetjues_uetjves_vdS)�z9Common objects shared by __init__.py and _ps*.py modules.�)�divisionN)�defaultdict)�
namedtuple)�AF_INET)�
SOCK_DGRAM)�SOCK_STREAM)�AF_INET6)�AF_UNIX���FREEBSD�BSD�LINUX�NETBSD�OPENBSD�OSX�POSIX�SUNOS�WINDOWS�ENCODING�
ENCODING_ERRSr�
CONN_CLOSE�CONN_CLOSE_WAIT�CONN_CLOSING�CONN_ESTABLISHED�CONN_FIN_WAIT1�CONN_FIN_WAIT2�
CONN_LAST_ACK�CONN_LISTEN�	CONN_NONE�
CONN_SYN_RECV�
CONN_SYN_SENT�CONN_TIME_WAIT�NIC_DUPLEX_FULL�NIC_DUPLEX_HALF�NIC_DUPLEX_UNKNOWN�STATUS_DEAD�STATUS_DISK_SLEEP�STATUS_IDLE�
STATUS_LOCKED�STATUS_RUNNING�STATUS_SLEEPING�STATUS_STOPPED�STATUS_SUSPENDED�STATUS_TRACING_STOP�STATUS_WAITING�STATUS_WAKE_KILL�
STATUS_WAKING�
STATUS_ZOMBIE�pconn�	pcputimes�pctxsw�pgids�pio�pionice�	popenfile�pthread�puids�sconn�	scpustats�sdiskio�	sdiskpart�
sdiskusage�snetio�snic�	snicstats�sswap�suser�	conn_tmap�deprecated_method�
isfile_strict�memoize�parse_environ_block�path_exists_strict�
usage_percent�
supports_ipv6�sockfam_to_enum�socktype_to_enum�wrap_numbers�posix�nt�linux�darwinZfreebsdZopenbsdZnetbsd�sunos�solaris�aixZrunningZsleepingz
disk-sleepZstoppedztracing-stopZzombieZdeadz	wake-killZwakingZidle�lockedZwaitingZ	suspendedZESTABLISHEDZSYN_SENTZSYN_RECVZ	FIN_WAIT1Z	FIN_WAIT2Z	TIME_WAITZCLOSEZ
CLOSE_WAITZLAST_ACKZLISTENZCLOSINGZNONE��c@seZdZdZdZdZdS)�	NicDuplexrYrZrN)�__name__�
__module__�__qualname__r#r$r%�r_r_�/usr/lib64/python3.6/_common.pyr[sr[c@seZdZdZdZdS)�BatteryTimerZrYN������)r\r]r^�POWER_TIME_UNKNOWN�POWER_TIME_UNLIMITEDr_r_r_r`ra�sra�replace�surrogateescape�total�usedZfreeZpercentZsinZsoutZ
read_countZwrite_countZ
read_bytesZwrite_bytesZ	read_timeZ
write_timeZdeviceZ
mountpointZfstypeZoptsZ
bytes_sentZ
bytes_recvZpackets_sentZpackets_recvZerrinZerroutZdropinZdropout�nameZterminal�hostZstarted�pid�fdZfamily�typeZladdrZraddrZstatusZaddressZnetmaskZ	broadcastZptpZisupZduplexZspeedZmtuZctx_switchesZ
interruptsZsoft_interruptsZsyscalls�scpufreqZcurrent�min�max�shwtempZlabelZhighZcritical�sbatteryZsecsleftZ
power_plugged�sfan�user�system�
children_user�children_system�path�idZ	user_timeZsystem_time�realZ	effectiveZsavedZioclass�valueZ	voluntaryZinvoluntary�addrZipZport)�allZtcpZtcp4ZudpZudp4ZinetZinet4Zinet6)Ztcp6Zudp6ZunixcCs\y||d}Wn0tk
r@t|t�s4t|t�r8dnd}YnX|dk	rTt||�S|SdS)z5Calculate percentage usage of 'used' against 'total'.�dgrN)�ZeroDivisionError�
isinstance�float�round)rirhZ_round�retr_r_r`rLs"
cs2tj����fdd��}�fdd�}i�||_|S)aA simple memoize decorator for functions supporting (hashable)
    positional arguments.
    It also provides a cache_clear() function for clearing the cache:

    >>> @memoize
    ... def foo()
    ...     return 1
        ...
    >>> foo()
    1
    >>> foo.cache_clear()
    >>>
    csH|tt|j���f}y�|Stk
rB�||�}�|<|SXdS)N)�	frozenset�sorted�items�KeyError)�args�kwargs�keyr�)�cache�funr_r`�wrapper"szmemoize.<locals>.wrappercs�j�dS)zClear cache.N)�clearr_)r�r_r`�cache_clear+szmemoize.<locals>.cache_clear)�	functools�wrapsr�)r�r�r�r_)r�r�r`rIs
	csNtj�����fdd����fdd�}��fdd�}i�d�_|�_|�_�S)a�A memoize decorator which is disabled by default. It can be
    activated and deactivated on request.
    For efficiency reasons it can be used only against class methods
    accepting no arguments.

    >>> class Foo:
    ...     @memoize
    ...     def foo()
    ...         print(1)
    ...
    >>> f = Foo()
    >>> # deactivated (default)
    >>> foo()
    1
    >>> foo()
    1
    >>>
    >>> # activated
    >>> foo.cache_activate()
    >>> foo()
    1
    >>> foo()
    >>> foo()
    >>>
    csH�js�|�Sy��}Wn$tk
r>�|�}��<YnX|SdS)N)�cache_activatedr�)�selfr�)r�r�r�r_r`r�Nsz'memoize_when_activated.<locals>.wrappercs
d�_dS)zActivate cache.TN)r�r_)r�r_r`�cache_activateYsz.memoize_when_activated.<locals>.cache_activatecsd�_�j�dS)zDeactivate and clear cache.FN)r�r�r_)r�r�r_r`�cache_deactivate]sz0memoize_when_activated.<locals>.cache_deactivateF)r�r�r�r�r�)r�r�r�r_)r�r�r�r`�memoize_when_activated4sr�cCsTytj|�}Wn4tk
rB}z|jtjtjfkr4�dSd}~XnXtj|j�SdS)z�Same as os.path.isfile() but does not swallow EACCES / EPERM
    exceptions, see:
    http://mail.python.org/pipermail/python-dev/2012-June/120787.html
    FN)�os�stat�OSError�errno�EPERM�EACCES�S_ISREG�st_mode)ry�st�errr_r_r`rHiscCsLytj|�Wn4tk
rB}z|jtjtjfkr4�dSd}~XnXdSdS)z�Same as os.path.exists() but does not swallow EACCES / EPERM
    exceptions, see:
    http://mail.python.org/pipermail/python-dev/2012-June/120787.html
    FNT)r�r�r�r�r�r�)ryr�r_r_r`rKxscCsbtjstdkrdSy2tjttj�}tj|��|jd�WdQRXdStjk
r\dSXdS)z2Return True if IPv6 is supported on this platform.NF�::1rT)r�r)�socketZhas_ipv6rr�
contextlib�closingZbind�error)Zsockr_r_r`rM�scCszi}d}t}xh|jd|�}||kr$P|jd||�}||krj|||�}||d|�}|rb|j�}|||<|d}qW|S)zCParse a C environ block of environment variables into a dictionary.r��=rZ)r�find�upper)�datar��posZWINDOWS_Znext_posZ	equal_posr�r|r_r_r`rJ�s cCs4tdkr|Sy
tj|�Sttfk
r.|SXdS)z�Convert a numeric socket family value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    N)�enumr�Z
AddressFamily�
ValueError�AttributeError)�numr_r_r`rN�s
cCs4tdkr|Sy
tj|�Sttfk
r.|SXdS)zConvert a numeric socket type value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    N)r�r�ZAddressTyper�r�)r�r_r_r`rO�s
cs�fdd�}|S)z�A decorator which can be used to mark a method as deprecated
    'replcement' is the method name which will be called instead.
    cs:d|j�f�|jdkr�|_tj|���fdd��}|S)Nz8%s() is deprecated and will be removed; use %s() insteadcs tj�tdd�t|��||�S)NrY)�category�
stacklevel)�warnings�warn�
FutureWarning�getattr)r�r�r�)�msg�replacementr_r`�inner�sz/deprecated_method.<locals>.outer.<locals>.inner)r\�__doc__r�r�)r�r�)r�)r�r`�outer�s
z deprecated_method.<locals>.outerr_)r�r�r_)r�r`rG�sc@sBeZdZdZdd�Zdd�Zdd�Zdd	�Zddd�Zd
d�Z	d
S)�_WrapNumberszNWatches numbers so that they don't overflow and wrap
    (reset to zero).
    cCs tj�|_i|_i|_i|_dS)N)�	threadingZLock�lockr��	reminders�
reminder_keys)r�r_r_r`�__init__�s
z_WrapNumbers.__init__cCs*||j|<tt�|j|<tt�|j|<dS)N)r�r�intr��setr�)r��
input_dictrjr_r_r`�	_add_dict�s
z_WrapNumbers._add_dictcCsd|j|}t|j��t|j��}x<|D]4}x"|j||D]}|j||=q<W|j||=q(WdS)z�In case the number of keys changed between calls (e.g. a
        disk disappears) this removes the entry from self.reminders.
        N)r�r��keysr�r�)r�r�rj�old_dictZ	gone_keysZgone_key�remkeyr_r_r`�_remove_dead_reminders�s

z#_WrapNumbers._remove_dead_remindersc
Cs||jkr|j||�|S|j||�|j|}i}x�|j�D]�}||}y||}Wntk
rt|||<w>YnXg}xvtt|��D]f}	||	}
||	}||	f}|
|kr�|j|||7<|j||j	|�|j
|
|j||�q�Wt|�||<q>W||j|<|S)zkCache dict and sum numbers which overflow and wrap.
        Return an updated copy of `input_dict`
        )r�r�r�r�r��range�lenr�r��add�append�tuple)
r�r�rjr�Znew_dictr�Zinput_tupleZ	old_tuple�bits�iZinput_valueZ	old_valuer�r_r_r`�run�s2


z_WrapNumbers.runNc
Csh|j�X|dkr0|jj�|jj�|jj�n*|jj|d�|jj|d�|jj|d�WdQRXdS)z>Clear the internal cache, optionally only for function 'name'.N)r�r�r�r�r��pop)r�rjr_r_r`r�"s

z_WrapNumbers.cache_clearc
Cs"|j�|j|j|jfSQRXdS)z5Return internal cache dicts as a tuple of 3 elements.N)r�r�r�r�)r�r_r_r`�
cache_info.sz_WrapNumbers.cache_info)N)
r\r]r^r�r�r�r�r�r�r�r_r_r_r`r��s'
r�c
Cstj�tj||�SQRXdS)z�Given an `input_dict` and a function `name`, adjust the numbers
    which "wrap" (restart from zero) across different calls by adding
    "old value" to "new value" and return an updated dict.
    N)�_wnr�r�)r�rjr_r_r`rP4s)r
rrbrc)N)wr�Z
__future__rr�r�r�r�r�r��sysr�r��collectionsrrrrrr�ImportErrorr	�version_infor�ZPY3�__all__rjrr�platform�
startswithrrrrrr
rZAIXr*r+r'r,r.r2r&r0r1r(r)r/r-rr!r rrr"rrrrrrr#r$r%�IntEnumr[�globals�update�__members__rdrera�getfilesystemencodingrr�getfilesystemencodeerrorsr�rDr@r>r?rArEr<rBrCr=rorrrsrtr4r9r:r;r6r7r8r5r3r}rFrLrIr�rHrKrMrJrNrOrGr�rPr�r�r�r_r_r_r`�<module>sH


	

	






	





 5

W	__pycache__/_pswindows.cpython-36.opt-1.pyc000064400000062344150466730530014557 0ustar003

��JZa��(@s�dZddlZddlZddlZddlZddlZddlmZddlm	Z	yddlm
ZWnlek
r�Z
zPee
�j�jd�r�ej�ddkr�d	Zed
7Zed7Zed7Zee��n�WYddZ
[
XnXdd
l	mZddl	mZddl	mZddl	mZddl	mZddl	mZddl	mZddl	mZddl	mZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl#m$Z$ddl#m%Z%ddl#m&Z&ddl
m'Z'ddl
m(Z(dd l
m)Z)dd!l
m*Z*dd"l
m+Z+dd#l
m,Z,ej-d�k�r�ddl.Z.ndZ.d&d'd(d)d*d+d,d-d.d/g
Z/d0Z0d1Z1e2ej3ej4ej5g�Z6e2ej7ej8g�Z9e.dk�rDd�Z:ne.j;d2d/d�i�Z<e<j:Z:ej=e	j>ej?e	j@ejAe	jBejCe	jDejEe	jFejGe	jHejIe	jJejKe	jLejMe	jNejOe	jPejQe	jRejSe0ejTe	jUi
ZVe.dk	�r�Gd3d4�d4e.j;�ZWeX�jYeWjZ�e[ddd5d$d%d6dd7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdF�Z\edGdHdIdJdKdLg�Z]edMdNdOdPdQdRg�Z^edSdTdUdVdWdXdYdZd[d\d]d^d_g�Z_ed`e_j`d��ZaedbdcdTg�Zbedddedfjcebj`��Zdedgdhdidjdkdldmg�Zeedndo�dpdq��Zfdrds�Zgdtdu�Zhdvdw�ZiejjZjdxdy�Zkdzd{�Zld|d}�Zmd~d�Znd�d��Zod�d��Zpd�d��Zqd�d��Zrd�d�d��Zsd�d��Ztd�d��Zud�d��Zvd�d��Zwdaxd�d��Zyd�d��Zzd�d&�Z{d�d'�Z|Gd�d��d�e}�Z~ejZej�Z�ej�Z�d�d��Z�Gd�d��d�e}�Z�dS)�z Windows platform implementation.�N)�
namedtuple�)�_common)�_psutil_windowszdll load failed�z3this Windows version is too old (< Windows Vista); z:psutil 3.4.2 is the latest version which supports Windows z92000, XP and 2003 server; it may be possible that psutil z)will work if compiled from sources though)�	conn_tmap)�ENCODING)�
ENCODING_ERRS)�
isfile_strict)�memoize_when_activated)�parse_environ_block)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�long)�	lru_cache)�PY3)�unicode)�xrange)�AccessDenied)�
NoSuchProcess)�TimeoutExpired)�ABOVE_NORMAL_PRIORITY_CLASS)�BELOW_NORMAL_PRIORITY_CLASS)�HIGH_PRIORITY_CLASS)�IDLE_PRIORITY_CLASS)�NORMAL_PRIORITY_CLASS)�REALTIME_PRIORITY_CLASS���win_service_iter�win_service_getrrrrrr�CONN_DELETE_TCB�AF_LINKZ
DELETE_TCBi�
AddressFamilyc@s$eZdZeZeZeZeZeZeZdS)�PriorityN)	�__name__�
__module__�__qualname__rrrrrr�r)r)�"/usr/lib64/python3.6/_pswindows.pyr%osr%�����	�
���
��������)�num_handles�ctx_switches�	user_time�kernel_time�create_time�num_threads�	io_rcount�	io_wcount�	io_rbytes�	io_wbytes�io_count_others�io_bytes_others�num_page_faults�	peak_wset�wset�peak_paged_pool�
paged_pool�peak_non_paged_pool�non_paged_pool�pagefile�
peak_pagefile�mem_private�	scputimes�user�system�idle�	interrupt�dpc�svmem�totalZ	available�percent�used�free�pmem�rss�vmsrHrIrJrKrLZpeak_nonpaged_poolZ
nonpaged_poolrOrPZprivate�pfullmem�uss�
pmmap_grouped�path�	pmmap_extzaddr perms � �pioZ
read_countZwrite_countZ
read_bytesZwrite_bytes�other_countZother_bytesi)�maxsizecCs<dj|jd�dd��}tj|�}tjj||t|�d��S)z�Convert paths using native DOS format like:
        "\Device\HarddiskVolume1\Windows\systemew\file.txt"
    into:
        "C:\Windows\systemew\file.txt"
    �\Nr)�join�split�cextZwin32_QueryDosDevice�osrc�len)�sZrawdriveZdriveletterr)r)r*�convert_dos_path�s
rpcCs(tr|St|t�r|S|jttd�SdS)zmEncode a unicode string to a byte string by using the default fs
    encoding + "replace" error handler.
    )�errorsN)r�
isinstance�str�encoderr	)ror)r)r*�
py2_strencode�s

rucCsNtj�}|\}}}}}}|}|}|}	||}
t|||dd�}t||||
|	�S)z&System virtual memory as a namedtuple.r)�_round)rl�virtual_memrrX)�memZtotphysZ	availphysZtotpagefZ
availpagefZtotvirtZfreevirtrYZavailr\r[rZr)r)r*�virtual_memory�srycCsBtj�}|d}|d}||}t||dd�}tj||||dd�S)z=Swap system memory as a (total, used, free, sin, sout) tuple.r+rr)rvr)rlrwrrZsswap)rxrYr\r[rZr)r)r*�swap_memory�srzcCsPtrt|t�r|jtdd�}tj|�\}}||}t||dd�}tj	||||�S)z'Return disk usage associated with path.�strict)rqr)rv)
rrr�bytes�decoderrl�
disk_usagerrZ
sdiskusage)rcrYr\r[rZr)r)r*r~�sr~cCstj|�}dd�|D�S)zReturn disk partitions.cSsg|]}tj|��qSr))rZ	sdiskpart)�.0�xr)r)r*�
<listcomp>sz#disk_partitions.<locals>.<listcomp>)rl�disk_partitions)�all�rawlistr)r)r*r��s
r�cCs<tj�\}}}tdd�ttj��D��}t||||j|j�S)z)Return system CPU times as a named tuple.cSsg|]}t|��qSr))�sum)r�nr)r)r*r�szcpu_times.<locals>.<listcomp>)rl�	cpu_timesrR�zip�
per_cpu_timesrVrW)rSrTrUZ
percpu_summedr)r)r*r�	sr�cCs>g}x4tj�D](\}}}}}t|||||�}|j|�qW|S)z6Return system per-CPU times as a list of named tuples.)rlr�rR�append)�retrSrTrUrVrW�itemr)r)r*r�s
r�cCstj�S)z0Return the number of logical CPUs in the system.)rl�cpu_count_logicalr)r)r)r*r�sr�cCstj�S)z1Return the number of physical CPUs in the system.)rlZcpu_count_physr)r)r)r*�cpu_count_physical"sr�cCs$tj�\}}}}d}tj||||�S)zReturn CPU statistics.r)rl�	cpu_statsrZ	scpustats)r=Z
interruptsZdpcsZsyscallsZsoft_interruptsr)r)r*r�'s
r�cCs(tj�\}}d}tjt|�|t|��gS)zMReturn CPU frequency.
    On Windows per-cpu frequency is not supported.
    g)rl�cpu_freqrZscpufreq�float)ZcurrZmax_Zmin_r)r)r*r�/sr�c	Cs�|tkr(td|djdd�tD��f��t|\}}tj|||�}t�}x�|D]�}|\}}}	}
}}}
|
rrtj|
�}
|r�tj|�}t|}t	|�}t
|	�}	|dkr�tj|||	|
|||
�}ntj|||	|
||�}|j
|�qNWt|�S)z�Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    z+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr))�repr)rr�r)r)r*r�Csz#net_connections.<locals>.<listcomp>r���)r�
ValueErrorrjrl�net_connections�setr�addr�TCP_STATUSESr
rZsconnZpconn�add�list)�kind�_pidZfamilies�typesr�r�r��fdZfam�typeZladdrZraddr�status�pid�ntr)r)r*r�=s(


r�cCsfi}tj�}xT|j�D]H\}}ts*t|�}|\}}}}ttd�rJtj|�}tj||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)	rl�net_if_stats�itemsrru�hasattrrr�Z	snicstats)r�Zrawdict�namer�ZisupZduplexZspeedZmtur)r)r*r�Xs

r�cCstj�}tdd�|j�D��S)zsReturn network I/O statistics for every network interface
    installed on the system as a dict of raw tuples.
    cSsg|]\}}t|�|f�qSr))ru)r�k�vr)r)r*r�lsz#net_io_counters.<locals>.<listcomp>)rl�net_io_counters�dictr�)r�r)r)r*r�gsr�cCs<g}x2tj�D]&}t|�}t|d�|d<|j|�qW|S)z,Return the addresses associated to each NIC.r)rl�net_if_addrsr�rur�)r�r�r)r)r*r�osr�cCsdtj�\}}}}|dk}t|d@�}t|d@�}|r8dS|s@|rHtj}n|dkrVtj}tj|||�S)zReturn battery information.r�r.Nr�)rl�sensors_battery�boolrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)Z
acline_status�flagsrZZsecsleftZ
power_pluggedZ
no_batteryZchargingr)r)r*r�~sr�cCs,ttj��}t|t�dkr tS|a|SdS)z:The system boot time expressed in seconds since the epoch.rN)r�rl�	boot_time�abs�_last_btime)r�r)r)r*r��s
r�cCsLg}tj�}x:|D]2}|\}}}t|�}tj|d||d�}|j|�qW|S)z:Return currently connected users as a list of namedtuples.N)rl�usersrurZsuserr�)�retlistr�r�rSZhostnameZtstampr�r)r)r*r��s

r�ccs.x(tj�D]\}}tt|�t|��Vq
WdS)z*Yields a list of WindowsService instances.N)rlZwinservice_enumerate�WindowsServiceru)r��display_namer)r)r*r �scCst|d�}|j�d|_|S)zBOpen a Windows service and return it as a WindowsService instance.Nr�)r��
_query_config�
_display_name)r�Zservicer)r)r*r!�s
c@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
ejdd��Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$S)%r�z(Represents an installed Windows service.cCs||_||_dS)N)�_namer�)�selfr�r�r)r)r*�__init__�szWindowsService.__init__cCs d|j|jf}d|jj|fS)Nz(name=%r, display_name=%r)z%s%s)r�r��	__class__r&)r�Zdetailsr)r)r*�__str__�szWindowsService.__str__cCsd|j�t|�fS)Nz
<%s at %s>)r��id)r�r)r)r*�__repr__�szWindowsService.__repr__cCst|t�stS|j|jkS)N)rrr��NotImplementedr�)r��otherr)r)r*�__eq__�s
zWindowsService.__eq__cCs
||kS)Nr))r�r�r)r)r*�__ne__�szWindowsService.__ne__c
CsH|j��tj|j�\}}}}WdQRXtt|�t|�t|�t|�d�S)N)r��binpath�username�
start_type)�_wrap_exceptionsrlZwinservice_query_configr�r�ru)r�r�r�r�r�r)r)r*r��s
zWindowsService._query_configcCs<|j��tj|j�\}}WdQRX|dkr0d}t||d�S)Nr)r�r�)r�rlZwinservice_query_statusr�r�)r�r�r�r)r)r*�
_query_status�s

zWindowsService._query_statusccs�y
dVWnrtk
r|}zV|jtkr>td|jd|jd��n.|jtksR|jtkrjtd|jd|jd��n�WYdd}~XnXdS)z{Ctx manager which translates bare OSError and WindowsError
        exceptions into NoSuchProcess and AccessDenied.
        Nz2service %r is not querable (not enough privileges))r�r��msgzservice %r does not exist))ZWindowsError�errno�ACCESS_DENIED_ERRSETrr��NO_SUCH_SERVICE_ERRSETZwinerrorr)r��errr)r)r*r��s



zWindowsService._wrap_exceptionscCs|jS)z�The service name. This string is how a service is referenced
        and can be passed to win_service_get() to get a new
        WindowsService instance.
        )r�)r�r)r)r*r�szWindowsService.namecCs|jS)z_The service display name. The value is cached when this class
        is instantiated.
        )r�)r�r)r)r*r�szWindowsService.display_namecCs|j�dS)zwThe fully qualified path to the service binary/exe file as
        a string, including command line arguments.
        r�)r�)r�r)r)r*r�szWindowsService.binpathcCs|j�dS)z,The name of the user that owns this service.r�)r�)r�r)r)r*r�szWindowsService.usernamecCs|j�dS)zRA string which can either be "automatic", "manual" or
        "disabled".
        r�)r�)r�r)r)r*r�szWindowsService.start_typecCs|j�dS)zzThe process PID, if any, else None. This can be passed
        to Process class to control the service's process.
        r�)r�)r�r)r)r*r�'szWindowsService.pidcCs|j�dS)zService status as a string.r�)r�)r�r)r)r*r�-szWindowsService.statuscCsttj|j���S)zService long description.)rurlZwinservice_query_descrr�)r�r)r)r*�description1szWindowsService.descriptioncCs>|j�}|j|j��|j�|d<|j�|d<|j�|d<|S)zUUtility method retrieving all the information above as a
        dictionary.
        r�r�r�)r��updater�r�r�r�)r��dr)r)r*�as_dict7szWindowsService.as_dictN)r&r'r(�__doc__r�r�r�r�r�r�r��
contextlib�contextmanagerr�r�r�r�r�r�r�r�r�r�r)r)r)r*r��s$r�cstj���fdd��}|S)zqDecorator which translates bare OSError and WindowsError
    exceptions into NoSuchProcess and AccessDenied.
    csly�|f|�|�Stk
rf}z:|jtkr:t|j|j��|jtjkrTt|j|j���WYdd}~XnXdS)N)�OSErrorr�r�rr�r��ESRCHr)r��args�kwargsr�)�funr)r*�wrapperxs
z wrap_exceptions.<locals>.wrapper)�	functools�wraps)r�r�r))r�r*�wrap_exceptionsts
r�c@s�eZdZdZdddgZdd�Zdd�Zd	d
�Zedd��Z	e
d
d��Ze
dd��Ze
dd��Z
e
dd��Zdd�Zdd�Ze
dd��Ze
dd��Zdd�Ze
dd ��Ze
d!d"��Ze
dPd$d%��Ze
d&d'��Ze
d(d)��Ze
d*d+��Ze
d,d-��Ze
d.d/��Ze
d0d1��Ze
d2d3��Ze
d4d5��Ze
d6d7��Ze
dQd9d:��Z e
d;d<��Z!e
d=d>��Z"e#e$d?��rve
d@dA��Z%e
dBdC��Z&e
dDdE��Z'e
dFdG��Z(e
dHdI��Z)e
dJdK��Z*e
dLdM��Z+e
dNdO��Z,d#S)R�Processz1Wrapper class around underlying C implementation.r�r��_ppidcCs||_d|_d|_dS)N)r�r�r�)r�r�r)r)r*r��szProcess.__init__cCs|jj�dS)N)�oneshot_infoZcache_activate)r�r)r)r*�
oneshot_enter�szProcess.oneshot_entercCs|jj�dS)N)r�Zcache_deactivate)r�r)r)r*�oneshot_exit�szProcess.oneshot_exitcCstj|j�}|S)zOReturn multiple information about this process as a
        raw tuple.
        )rlZ	proc_infor�)r�r�r)r)r*r��szProcess.oneshot_infocCsV|jdkrdS|jdkrdSyttjj|j���Stk
rPttj|j��SXdS)zbReturn process name, which on Windows is always the final
        part of the executable.
        rzSystem Idle ProcessrZSystemN)	r�rurmrc�basename�exerrlZ	proc_name)r�r)r)r*r��s

zProcess.namecCs,|jdkrt|j|j��tttj|j���S)Nrr)rr)r�rr�rurprlZproc_exe)r�r)r)r*r��s
zProcess.execCs&tj|j�}tr|Sdd�|D�SdS)NcSsg|]}t|��qSr))ru)rror)r)r*r��sz#Process.cmdline.<locals>.<listcomp>)rlZproc_cmdliner�r)r�r�r)r)r*�cmdline�szProcess.cmdlinecCs"tj|j�}|rtrtt|��S)N)rlZproc_environr�rrru)r�Zustrr)r)r*�environ�s
zProcess.environcCs4yt�|jStk
r.t|j|j��YnXdS)N)�ppid_mapr��KeyErrorrr�)r�r)r)r*�ppid�szProcess.ppidcCs�ytj|j�Stk
r�}z�|jtkr�|j�}|td|td|td|td|td|td|td|td|td	|td
f
S�WYdd}~XnXdS)NrHrIrJrKrLrMrNrOrPrQ)rlZproc_memory_infor�r�r�r�r��	pinfo_map)r�r��infor)r)r*�_get_raw_meminfo�s 









zProcess._get_raw_meminfocCs(|j�}|d}|d}t||f|�S)Nr+r-)r�r])r��tr^r_r)r)r*�memory_info�szProcess.memory_infocCs"|j�}tj|j�}t||f�S)N)r�rlZproc_memory_ussr�r`)r�Z	basic_memrar)r)r*�memory_full_info�szProcess.memory_full_infoccs�ytj|j�}WnVtk
rf}z:|jtkr:t|j|j��|jtjkrTt	|j|j���WYdd}~XnBXx>|D]6\}}}}t
|�}ts�t|�}t
|�}||||fVqnWdS)N)rlZproc_memory_mapsr�r�r�r�rr�r�rrprru�hex)r��rawr�r�Zpermrcr^r)r)r*�memory_maps�s
zProcess.memory_mapscCstj|j�S)N)rlZ	proc_killr�)r�r)r)r*�killszProcess.killcCstj|j|�dS)N)rmr�r�)r�Zsigr)r)r*�send_signalszProcess.send_signalNcCsr|dkrtj}nt|d�}xPtj|j|�}|tkrDt||j|j��t|j�rj|dkrZqnt||j|j��|SdS)Ni�)	rlZINFINITE�intZ	proc_waitr��WAIT_TIMEOUTrr��
pid_exists)r�ZtimeoutZcext_timeoutr�r)r)r*�waits
zProcess.waitcCs2|jdkrdStj|j�\}}t|�dt|�S)NrrzNT AUTHORITY\SYSTEMri)rr)r�rlZ
proc_usernameru)r�ZdomainrSr)r)r*r�(s
zProcess.usernamecCs`|jdkrt�Sytj|j�Stk
rZ}z"|jtkrH|j�tdS�WYdd}~XnXdS)Nrrr@)rr)	r�r�rlZproc_create_timer�r�r�r�r�)r�r�r)r)r*r@/s

zProcess.create_timecCs|j�tdS)NrA)r�r�)r�r)r)r*rA;szProcess.num_threadscCs@tj|j�}g}x*|D]"\}}}tj|||�}|j|�qW|S)N)rlZproc_threadsr�rZpthreadr�)r�r�r�Z	thread_id�utimeZstime�ntupler)r)r*�threads?szProcess.threadscCsvytj|j�\}}WnPtk
rd}z4|jtkrR|j�}|td}|td}n�WYdd}~XnXtj	||dd�S)Nr>r?g)
rlZproc_cpu_timesr�r�r�r�r�r�rZ	pcputimes)r�rSrTr�r�r)r)r*r�Hs
zProcess.cpu_timescCstj|j�S)N)rlZproc_suspendr�)r�r)r)r*�suspendVszProcess.suspendcCstj|j�S)N)rlZproc_resumer�)r�r)r)r*�resumeZszProcess.resumecCs4|jdkrt|j|j��tj|j�}ttjj|��S)Nrr)rr)	r�rr�rlZproc_cwdrurmrc�normpath)r�rcr)r)r*�cwd^s
zProcess.cwdcCsh|jdkrgSt�}tj|j�}x>|D]6}t|�}t|�r&tsFt|�}tj	|d�}|j
|�q&Wt|�S)Nrrr)rrr�)r�r�rlZproc_open_filesrpr
rrurZ	popenfiler�r�)r�r�Zraw_file_namesZ_filer�r)r)r*�
open_filesgs

zProcess.open_files�inetcCst||jd�S)N)r�)r�r�)r�r�r)r)r*�connectionszszProcess.connectionscCs tj|j�}tdk	rt|�}|S)N)rlZproc_priority_getr��enumr%)r��valuer)r)r*�nice_get~szProcess.nice_getcCstj|j|�S)N)rlZproc_priority_setr�)r�rr)r)r*�nice_set�szProcess.nice_set�proc_io_priority_getcCstj|j�S)N)rlrr�)r�r)r)r*�
ionice_get�szProcess.ionice_getcCs.|rtd��|dkr td|��tj|j|�S)Nz<set_proc_ionice() on Windows takes only 1 argument (2 given)r+rrz9value must be 2 (normal), 1 (low) or 0 (very low); got %r)r+rr)�	TypeErrorr�rlZproc_io_priority_setr�)r�r�_r)r)r*�
ionice_set�szProcess.ionice_setcCs�ytj|j�}Wnxtk
r�}z\|jtkrv|j�}|td|td|td|td|td|tdf}n�WYdd}~XnXt|�S)NrBrCrDrErFrG)	rlZproc_io_countersr�r�r�r�r�r�rf)r�r�r�r�r)r)r*�io_counters�s





zProcess.io_counterscCs tj|j�}|rtjStjSdS)N)rlZproc_is_suspendedr�rZSTATUS_STOPPEDZSTATUS_RUNNING)r�Z	suspendedr)r)r*r��szProcess.statuscCsdd�}tj|j�}||�S)Ncs�fdd�td�D�S)Ncsg|]}d|>�@r|�qS)rr))r�i)r�r)r*r��szBProcess.cpu_affinity_get.<locals>.from_bitmask.<locals>.<listcomp>�@)r)r�r))r�r*�from_bitmask�sz.Process.cpu_affinity_get.<locals>.from_bitmask)rlZproc_cpu_affinity_getr�)r�r�bitmaskr)r)r*�cpu_affinity_get�szProcess.cpu_affinity_getcCsrdd�}tttt����}x<|D]4}||kr t|ttf�sHtd|��q td|��q W||�}t	j
|j|�dS)NcSs2|std|��d}x|D]}|d|O}qW|S)Nzinvalid argument %rrr+)r�)�l�out�br)r)r*�
to_bitmask�s
z,Process.cpu_affinity_set.<locals>.to_bitmaskz&invalid CPU %r; an integer is requiredzinvalid CPU %r)r��rangernr�rrr�rr
r�rlZproc_cpu_affinity_setr�)r�rrZallcpusZcpurr)r)r*�cpu_affinity_set�s
zProcess.cpu_affinity_setcCsPytj|j�Stk
rJ}z"|jtkr8|j�tdS�WYdd}~XnXdS)Nr<)rlZproc_num_handlesr�r�r�r�r�r�)r�r�r)r)r*r<�s
zProcess.num_handlescCs|j�td}tj|d�S)Nr=r)r�r�rZpctxsw)r�r=r)r)r*�num_ctx_switches�szProcess.num_ctx_switches)N)r)-r&r'r(r��	__slots__r�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r@rAr�r�r�r�rrrrrr�rlr	rr
r�rrr<rr)r)r)r*r��sR
	
		
	r�)rrr�r�)rar�)r�)�r�r�r�r�rm�sys�collectionsr�rrrl�ImportErrorr�rs�lower�
startswithZgetwindowsversionr��RuntimeErrorrrr	r
rrr
rrZ_compatrrrrr�_exceptionsrrrrrrrrr�version_inforZ__extra__all__r"r��	frozensetZEPERMZEACCESZERROR_ACCESS_DENIEDr�ZERROR_INVALID_NAMEZERROR_SERVICE_DOES_NOT_EXISTr�r#�IntEnumr$ZMIB_TCP_STATE_ESTABZCONN_ESTABLISHEDZMIB_TCP_STATE_SYN_SENTZ
CONN_SYN_SENTZMIB_TCP_STATE_SYN_RCVDZ
CONN_SYN_RECVZMIB_TCP_STATE_FIN_WAIT1ZCONN_FIN_WAIT1ZMIB_TCP_STATE_FIN_WAIT2ZCONN_FIN_WAIT2ZMIB_TCP_STATE_TIME_WAITZCONN_TIME_WAITZMIB_TCP_STATE_CLOSEDZ
CONN_CLOSEZMIB_TCP_STATE_CLOSE_WAITZCONN_CLOSE_WAITZMIB_TCP_STATE_LAST_ACKZ
CONN_LAST_ACKZMIB_TCP_STATE_LISTENZCONN_LISTENZMIB_TCP_STATE_CLOSINGZCONN_CLOSINGZMIB_TCP_STATE_DELETE_TCBZPSUTIL_CONN_NONEZ	CONN_NONEr�r%�globalsr��__members__r�r�rRrXr]�_fieldsr`rbrjrdrfrpruryrzZdisk_io_countersr~r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r r!�objectr�Zpidsr�r�r�r�r)r)r)r*�<module>s 









	
*__pycache__/_exceptions.cpython-36.pyc000064400000006323150466730530013737 0ustar003

��JZ��@sTGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd	�d	e�Zd
S)c@s&eZdZdZddd�Zdd�ZeZdS)	�ErrorzQBase exception class. All other psutil exceptions inherit
    from this one.
    �cCstj||�||_dS)N)�	Exception�__init__�msg)�selfr�r�#/usr/lib64/python3.6/_exceptions.pyrszError.__init__cCsd|jj|jf}|j�S)Nzpsutil.%s %s)�	__class__�__name__r�strip)r�retrrr�__repr__szError.__repr__N)r)r
�
__module__�__qualname__�__doc__rr
�__str__rrrrrs
rc@seZdZdZddd�ZdS)�
NoSuchProcesszXException raised when a process with a certain PID doesn't
    or no longer exists.
    NcCsXtj||�||_||_||_|dkrT|r@d|jt|j�f}n
d|j}d||_dS)Nz(pid=%s, name=%s)z(pid=%s)zprocess no longer exists )rr�pid�namer�repr)rrrr�detailsrrrrs
zNoSuchProcess.__init__)NN)r
rrrrrrrrrsrc@seZdZdZddd�ZdS)�
ZombieProcessa/Exception raised when querying a zombie process. This is
    raised on OSX, BSD and Solaris only, and not always: depending
    on the query the OS may be able to succeed anyway.
    On Linux all zombie processes are querable (hence this is never
    raised). Windows doesn't have zombie processes.
    NcCs~tj||�||_||_||_||_|dkrzd|g}|rN|jdt|j��|rb|jd|j�ddj|�}d||_dS)Nzpid=%szname=%szppid=%sz(%s)z, z'process still exists but it's a zombie )	rrr�ppidrr�appendr�join)rrrrr�argsrrrrr0s
zZombieProcess.__init__)NNN)r
rrrrrrrrr(src@seZdZdZddd�ZdS)�AccessDeniedz@Exception raised when permission to perform an action is denied.NcCsjtj||�||_||_||_|dkrf|dk	rJ|dk	rJd|t|�f|_n|dk	r`d|j|_nd|_dS)Nz(pid=%s, name=%s)z(pid=%s)r)rrrrrr)rrrrrrrrCszAccessDenied.__init__)NNN)r
rrrrrrrrr@src@seZdZdZddd�ZdS)�TimeoutExpiredzWRaised on Process.wait(timeout) if timeout expires and process
    is still alive.
    NcCsntj|d|�||_||_||_|dk	rN|dk	rN|jd|t|�f7_n|dk	rj|jd|j7_dS)Nztimeout after %s secondsz (pid=%s, name=%s)z	 (pid=%s))rr�secondsrrrr)rrrrrrrrVszTimeoutExpired.__init__)NN)r
rrrrrrrrrQsrN)rrrrrrrrrr�<module>s__pycache__/_psosx.cpython-36.opt-1.pyc000064400000034165150466730530013676 0ustar003

��JZ=C�@s�dZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddl	mZddl	mZ
dd	l	mZdd
l
mZddl
mZddl
mZdd
l
mZddl
mZddl
mZddl
mZddl
mZddlmZddlmZddlmZgZejd�ZejZe
j e
j!e
j"e
j#e
j$e
j%e
j&e
j'e
j(e
j)e
j*e
j+e
j,e
j-e
j.e
j/e
j0e
j1e
j2e
j3e
j4e
j5e
j6e
j7iZ8e
j9e
j:e
j;e
j<e
j=e
j>e
j?e
j@e
jAe
jBiZCeDdddddddddddd�ZEeDddddddddd �ZFed!d"d#d$d%g�ZGed&d'd(d)d*d+d,d-d.g�ZHed/d0d1d2d3g�ZIed4eIjJda�ZKed6d7�ZLed8d9d:jMeLjJ��ZNd;d<�ZOd=d>�ZPd?d@�ZQdAdB�ZRdCdD�ZSdEdF�ZTdGdH�ZUdIdJ�ZVejWZWe
jXZXdbdLdM�ZYdNdO�ZZe
j[Z[ej\Z\dcdQdR�Z]dSdT�Z^dUdV�Z_dWdX�Z`dYdZ�ZaejbZbd[d\�Zcejdd]d^��ZeGd_d`�d`ef�ZgdS)dzOSX platform implementation.�N)�AF_INET)�
namedtuple�)�_common)�_psposix)�_psutil_osx)�
_psutil_posix)�AF_INET6)�	conn_tmap)�
isfile_strict)�memoize_when_activated)�parse_environ_block)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�SC_PAGE_SIZE��������	�
)�ppid�ruid�euid�suid�rgid�egid�sgid�ttynr�ctime�status�name)�cpuutime�cpustime�rss�vms�pfaults�pageins�
numthreads�volctxsw�	scputimes�user�nice�system�idle�svmem�totalZ	available�percent�used�free�active�inactive�wired�pmemr+r,r-r.�pfullmem�uss�
pmmap_groupedz7path rss private swapped dirtied ref_count shadow_depth�	pmmap_extzaddr perms � c	CsNtj�\}}}}}||}|||}t|||dd�}t||||||||�S)z&System virtual memory as a namedtuple.r)�_round)�cextZvirtual_memrr6)r7r;r<r=r:Zavailr9r8�rF�/usr/lib64/python3.6/_psosx.py�virtual_memoryxsrHcCs4tj�\}}}}}t||dd�}tj||||||�S)z=Swap system memory as a (total, used, free, sin, sout) tuple.r)rD)rEZswap_memrrZsswap)r7r9r:ZsinZsoutr8rFrFrG�swap_memory�srIcCstj�\}}}}t||||�S)z(Return system CPU times as a namedtuple.)rE�	cpu_timesr1)r2r3r4r5rFrFrGrJ�srJcCs>g}x4tj�D](}|\}}}}t||||�}|j|�qW|S)z(Return system CPU times as a named tuple)rE�
per_cpu_timesr1�append)�retZcpu_tr2r3r4r5�itemrFrFrGrK�srKcCstj�S)z0Return the number of logical CPUs in the system.)rE�cpu_count_logicalrFrFrFrGrO�srOcCstj�S)z1Return the number of physical CPUs in the system.)rEZcpu_count_physrFrFrFrG�cpu_count_physical�srPcCs"tj�\}}}}}tj||||�S)N)rE�	cpu_statsrZ	scpustats)Zctx_switchesZ
interruptsZsoft_interruptsZsyscallsZtrapsrFrFrGrQ�srQcCstj�\}}}tj|||�gS)z�Return CPU frequency.
    On OSX per-cpu frequency is not supported.
    Also, the returned frequency never changes, see:
    https://arstechnica.com/civis/viewtopic.php?f=19&t=465002
    )rE�cpu_freqrZscpufreq)ZcurrZmin_Zmax_rFrFrGrR�srRFc	Csrg}tj�}x`|D]X}|\}}}}|dkr.d}|sPtjj|�stjj|�rPqtj||||�}|j|�qW|S)z8Return mounted disk partitions as a list of namedtuples.Znone�)	rE�disk_partitions�os�path�isabs�existsrZ	sdiskpartrL)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZopts�ntuplerFrFrGrT�s
rTcCsbytj�\}}}Wntk
r&dSX|dk}|r<tj}n|dkrLtj}n|d}tj|||�S)z Return battery information.
    Nr�<���)rE�sensors_battery�NotImplementedErrorrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)r8ZminsleftZ
power_pluggedZsecsleftrFrFrGr_�sr_�inetc
Csrg}xht�D]^}yt|�j|�}Wntk
r8wYqX|rx*|D]"}t|�|g}|jtj|��qDWqW|S)z System-wide network connections.)�pids�Process�connectionsr�listrLrZsconn)�kindrM�pidZcons�crFrFrG�net_connections�s
ricCsjt�j�}i}xV|D]N}tj|�}tj|�}tj|�\}}ttd�rNtj|�}tj	||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)
�net_io_counters�keys�
cext_posixZ
net_if_mtuZnet_if_flagsZnet_if_duplex_speed�hasattrrrjZ	snicstats)�namesrMr(ZmtuZisupZduplexZspeedrFrFrG�net_if_statss





rpcCstj�S)z:The system boot time expressed in seconds since the epoch.)rE�	boot_timerFrFrFrGrqsrqc	Cs`g}tj�}xN|D]F}|\}}}}}|dkr.q|s4qtj||p@d|pFd||�}|j|�qW|S)z:Return currently connected users as a list of namedtuples.�~N)rE�usersrZsuserrL)	rZ�rawlistrNr2ZttyZhostnameZtstamprg�ntrFrFrGrss
rscCs`tj�}d|kr\ytd�j�|jd�Wn0tk
r>Yntk
rZ|jd�YnX|S)Nr)rErbrc�create_timerLrr)ZlsrFrFrGrb0srbcstj���fdd��}|S)z`Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    csty�|f|�|�Stk
rn}zB|jtjkr<t|j|j��|jtjtjfkr\t|j|j���WYdd}~XnXdS)N)	�OSError�errno�ESRCHrrg�_nameZEPERMZEACCESr)�self�args�kwargs�err)�funrFrG�wrapperGsz wrap_exceptions.<locals>.wrapper)�	functools�wraps)rr�rF)rrG�wrap_exceptionsCs
r�ccs�y
dVWn�ttfk
r�}zrt|t�s6|jtjkr�y|j�}Wntk
rZ|�Yq�X|tjkrzt	|j
|j|j��q�t
|j
|j��n�WYdd}~XnXdS)z�There are some poor C APIs which incorrectly raise ESRCH when
    the process is still alive or it's a zombie, or even RuntimeError
    (those who don't set errno). This is here in order to solve:
    https://github.com/giampaolo/psutil/issues/1044
    N)rw�RuntimeError�
isinstancerxryr'rr�
STATUS_ZOMBIErrgrz�_ppidr)�procr~r'rFrFrG�catch_zombieTs


r�c@sneZdZdZdddgZdd�Zedd��Zed	d
��Zdd�Z	d
d�Z
edd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zedd��Zedd��Zedd ��Zed!d"��Zed#d$��Zed%d&��Zed'd(��Zed)d*��Zed+d,��Zed-d.��ZedAd0d1��Zed2d3��ZedBd5d6��Zed7d8��Zed9d:��Z ed;d<��Z!ed=d>��Z"ed?d@��Z#d4S)Crcz1Wrapper class around underlying C implementation.rgrzr�cCs||_d|_d|_dS)N)rgrzr�)r{rgrFrFrG�__init__sszProcess.__init__cCstj|j�}|S)N)rEZproc_kinfo_oneshotrg)r{rMrFrFrG�_get_kinfo_procxszProcess._get_kinfo_procc	Cs$t|��tj|j�}WdQRX|S)N)r�rEZproc_pidtaskinfo_oneshotrg)r{rMrFrFrG�_get_pidtaskinfos
zProcess._get_pidtaskinfocCs|jj�|jj�dS)N)r�Zcache_activater�)r{rFrFrG�
oneshot_enter�s
zProcess.oneshot_entercCs|jj�|jj�dS)N)r�Zcache_deactivater�)r{rFrFrG�oneshot_exit�s
zProcess.oneshot_exitcCs(|j�td}|dk	r|Stj|j�S)Nr()r��kinfo_proc_maprEZ	proc_namerg)r{r(rFrFrGr(�szProcess.namec	Cs t|��tj|j�SQRXdS)N)r�rEZproc_exerg)r{rFrFrG�exe�s
zProcess.exec	Cs t|��tj|j�SQRXdS)N)r�rEZproc_cmdlinerg)r{rFrFrG�cmdline�s
zProcess.cmdlinec
Cs$t|��ttj|j��SQRXdS)N)r�r
rEZproc_environrg)r{rFrFrG�environ�s
zProcess.environcCs|j�td|_|jS)Nr)r�r�r�)r{rFrFrGr�szProcess.ppidc	Cs t|��tj|j�SQRXdS)N)r�rEZproc_cwdrg)r{rFrFrG�cwd�s
zProcess.cwdcCs.|j�}tj|td|td|td�S)Nrr r!)r�r�puidsr�)r{�rawtuplerFrFrG�uids�s


zProcess.uidscCs.|j�}tj|td|td|td�S)Nr"r#r$)r�rr�r�)r{r�rFrFrG�gids�s


zProcess.gidscCs:|j�td}tj�}y||Stk
r4dSXdS)Nr%)r�r�rZget_terminal_map�KeyError)r{Ztty_nrZtmaprFrFrG�terminal�szProcess.terminalcCs6|j�}t|td|td|td|td�S)Nr+r,r-r.)r�r>�pidtaskinfo_map)r{r�rFrFrG�memory_info�s


zProcess.memory_infocCs"|j�}tj|j�}t||f�S)N)r�rEZproc_memory_ussrgr?)r{Z	basic_memr@rFrFrG�memory_full_info�szProcess.memory_full_infocCs(|j�}tj|td|tddd�S)Nr)r*g)r�rZ	pcputimesr�)r{r�rFrFrGrJ�s


zProcess.cpu_timescCs|j�tdS)Nr&)r�r�)r{rFrFrGrv�szProcess.create_timecCs|j�td}tj|d�S)Nr0r)r�r�rZpctxsw)r{ZvolrFrFrG�num_ctx_switches�szProcess.num_ctx_switchescCs|j�tdS)Nr/)r�r�)r{rFrFrG�num_threads�szProcess.num_threadscCsf|jdkrgSg}t|��tj|j�}WdQRXx.|D]&\}}t|�r8tj||�}|j|�q8W|S)Nr)rgr�rEZproc_open_filesrrZ	popenfilerL)r{�filesrtrV�fdr\rFrFrG�
open_files�s

zProcess.open_filesracCs�|tkr(td|djdd�tD��f��t|\}}t|��tj|j||�}WdQRXg}xz|D]r}|\}}}	}
}}t|}t|�}t	|	�}	|t
tfkr�|
r�tj
|
�}
|r�tj
|�}tj|||	|
||�}
|j|
�qbW|S)Nz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSrF)�repr)�.0�xrFrFrG�
<listcomp>sz'Process.connections.<locals>.<listcomp>)r
�
ValueError�joinr�rEZproc_connectionsrg�TCP_STATUSESrrrr	rZaddrZpconnrL)r{rfZfamilies�typesrtrMrNr�Zfam�typeZladdrZraddrr'rurFrFrGrd�s(



zProcess.connectionsc	Cs.|jdkrdSt|��tj|j�SQRXdS)Nr)rgr�rEZproc_num_fds)r{rFrFrG�num_fdss

zProcess.num_fdsNcCstj|j||j�S)N)rZwait_pidrgrz)r{ZtimeoutrFrFrG�waitszProcess.waitc	Cs t|��tj|j�SQRXdS)N)r�rm�getpriorityrg)r{rFrFrG�nice_gets
zProcess.nice_getc
Cs"t|��tj|j|�SQRXdS)N)r�rm�setpriorityrg)r{�valuerFrFrG�nice_set#s
zProcess.nice_setcCs|j�td}tj|d�S)Nr'�?)r�r��
PROC_STATUSES�get)r{�coderFrFrGr'(szProcess.statuscCsTt|��tj|j�}WdQRXg}x*|D]"\}}}tj|||�}|j|�q*W|S)N)r�rEZproc_threadsrgrZpthreadrL)r{rtrZZ	thread_id�utimeZstimer\rFrFrG�threads.s
zProcess.threadsc	Cs t|��tj|j�SQRXdS)N)r�rEZproc_memory_mapsrg)r{rFrFrG�memory_maps8s
zProcess.memory_maps)ra)N)$�__name__�
__module__�__qualname__�__doc__�	__slots__r�rr�r�r�r�r�r(r�r�r�rr�r�r�r�r�r�rJrvr�r�r�rdr�r�r�r�r'r�r�rFrFrFrGrcnsB
	
	

rc)r@)F)ra)hr��
contextlibrxr�rUZsocketr�collectionsrrSrrrrErrmr	r
rrr
rrr�_exceptionsrrrZ__extra__all__�sysconfZPAGESIZEZAF_LINKZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZTCPS_SYN_RECEIVEDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGZPSUTIL_CONN_NONEZ	CONN_NONEr�ZSIDLZSTATUS_IDLEZSRUNZSTATUS_RUNNINGZSSLEEPZSTATUS_SLEEPINGZSSTOPZSTATUS_STOPPEDZSZOMBr�r��dictr�r�r1r6r>�_fieldsr?rAr�rBrHrIrJrKrOrPrQrRZ
disk_usageZdisk_io_countersrTr_rkZnet_if_addrsrirprqrsrbZ
pid_existsr��contextmanagerr��objectrcrFrFrFrG�<module>s�





__pycache__/_psaix.cpython-36.pyc000064400000036141150466730530012703 0ustar003

��JZ�K�@s�dZddlZddlZddlZddlZddlZddlZddlmZddl	m
Z
ddlmZddlm
Z
ddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZdgZ e!ed�Z"ej#d�Z$ej%Z%ej&ej'ej(ej)ej*ej+ej,ej+ej-ej.iZ/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ej<ej=ej>ej?ej@ejAejBejCejDejEejFejGiZHeIddddddddd�ZJed d!d"g�ZKeKZLed#d$d%d&d'g�ZMed(d)d*d+d,d-g�ZNed.d/d!d0d1g�ZOed2d3d4jPeOjQ��ZRd5d6�ZSd7d8�ZTd9d:�ZUd;d<�ZVd=d>�ZWd?d@�ZXdAdB�ZYdCdD�ZZej[Z[e
j\Z\dXdFdG�Z]ej^Z^ej_Z_dZdHdI�Z`dJdK�ZadLdM�ZbdNdO�ZcdPdQ�ZddRdS�ZedTdU�ZfGdVdW�dWeg�ZhdS)[zAIX platform implementation.�N)�
namedtuple)�AF_INET�)�_common)�_psposix)�_psutil_aix)�
_psutil_posix)�AF_INET6)�memoize_when_activated)�NIC_DUPLEX_FULL)�NIC_DUPLEX_HALF)�NIC_DUPLEX_UNKNOWN)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�PY3)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�PROCFS_PATH�proc_threads�SC_PAGE_SIZE������)�ppid�rss�vms�create_time�nice�num_threads�status�ttynr�pmemrr �	scputimes�user�systemZidleZiowait�svmem�totalZ	available�percent�used�free�
pmmap_grouped�pathZanon�locked�	pmmap_extzaddr perms � cCstjdjS)z+Return updated psutil.PROCFS_PATH constant.Zpsutil)�sys�modulesr�r6r6�/usr/lib64/python3.6/_psaix.py�get_procfs_pathlsr8cCs4tj�\}}}}}t|||dd�}t|||||�S)Nr)�_round)�cextZvirtual_memrr*)r+Zavailr.ZpinnedZinuser,r6r6r7�virtual_memoryvsr;cCs:tj�\}}}}||}t||dd�}tj||||||�S)z=Swap system memory as a (total, used, free, sin, sout) tuple.r)r9)r:Zswap_memrrZsswap)r+r.ZsinZsoutr-r,r6r6r7�swap_memory|sr<cCstj�}tdd�t|�D��S)z-Return system-wide CPU times as a named tuplecSsg|]}t|��qSr6)�sum)�.0�xr6r6r7�
<listcomp>�szcpu_times.<locals>.<listcomp>)r:�
per_cpu_timesr'�zip)�retr6r6r7�	cpu_times�srDcCstj�}dd�|D�S)z5Return system per-CPU times as a list of named tuplescSsg|]}t|��qSr6)r')r>r?r6r6r7r@�sz!per_cpu_times.<locals>.<listcomp>)r:rA)rCr6r6r7rA�srAcCs$y
tjd�Stk
rdSXdS)z0Return the number of logical CPUs in the system.�SC_NPROCESSORS_ONLNN)�os�sysconf�
ValueErrorr6r6r6r7�cpu_count_logical�s
rIcCsrd}tj|dtjtjd�}|j�\}}tr@dd�||fD�\}}|jdkrZtd||f��|j�j�}t	|�ppdS)Nzlsdev -Cc processorT)�shell�stdout�stderrcSsg|]}|jtjj��qSr6)�decoder4rK�encoding)r>r?r6r6r7r@�sz&cpu_count_physical.<locals>.<listcomp>rz%r command error
%s)
�
subprocess�Popen�PIPE�communicater�
returncode�RuntimeError�strip�
splitlines�len)�cmd�prKrLZ
processorsr6r6r7�cpu_count_physical�s

rZcCs tj�\}}}}tj||||�S)z*Return various CPU stats as a named tuple.)r:�	cpu_statsrZ	scpustats)Zctx_switchesZ
interruptsZsoft_interruptsZsyscallsr6r6r7r[�sr[Fc	Cs`g}tj�}xN|D]F}|\}}}}|dkr.d}|s>t|�js>qtj||||�}|j|�qW|S)zReturn system disk partitions.Znone�)r:�disk_partitions�
disk_usager+rZ	sdiskpart�append)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZopts�ntupler6r6r7r]�s

r]c	Cstj}||kr.td|djdd�|D��f��tj|\}}tj|�}t�}x�|D]�}|\}}	}
}}}
}|	|krrqR|
|kr|qRt|
}
|	tt	fkr�|r�tj
|�}|r�tj
|�}t|	�}	t|
�}
|dkr�tj
||	|
|||
|�}ntj||	|
|||
�}|j|�qRWt|�S)z�Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    z+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr6)�repr)r>r?r6r6r7r@�sz#net_connections.<locals>.<listcomp>r���)rZ	conn_tmaprH�joinr:�net_connections�set�TCP_STATUSESrr	ZaddrrrZsconnZpconn�add�list)�kind�_pidZcmapZfamilies�types�rawlistrC�item�fdZfamZtype_ZladdrZraddrr$�pid�ntr6r6r7rg�s4



rgcCs�ttd�}tdd�t�D��}i}x�|D]�}tj|�\}}d}d}tjdd|gtjtjd�}|j	�\}	}
t
r�d	d�|	|
fD�\}	}
|jdkr�tj
d
|	�}|dk	r�t|jd��}|jd
�}|j|t�}tj||||�||<q(W|S)z)Get NIC stats (isup, duplex, speed, mtu).)ZFullZHalfcSsg|]}|d�qS)rr6)r>r?r6r6r7r@�sz net_if_stats.<locals>.<listcomp>r\rz/usr/bin/entstatz-d)rKrLcSsg|]}|jtjj��qSr6)rMr4rKrN)r>r?r6r6r7r@
sz"Running: (\d+) Mbps.*?(\w+) DuplexNrr)rrrh�net_if_addrsr:�net_if_statsrOrPrQrRrrS�re�search�int�group�getr
rZ	snicstats)Z
duplex_map�namesrC�nameZisupZmtuZduplexZspeedrYrKrLZ	re_resultr6r6r7ru�s,


rucCstj�S)z:The system boot time expressed in seconds since the epoch.)r:�	boot_timer6r6r6r7r}sr}cCs`g}tj�}d}xJ|D]B}|\}}}}}}	|s0q||kr<d}tj|||||	�}
|j|
�qW|S)z:Return currently connected users as a list of namedtuples.�:0.0�:0�	localhost)r~r)r:�usersrZsuserr_)raror�rpr(ZttyZhostnameZtstampZuser_processrrrsr6r6r7r�$s
r�cCsdd�tjt��D�S)z7Returns a list of PIDs currently running on the system.cSsg|]}|j�rt|��qSr6)�isdigitrx)r>r?r6r6r7r@>szpids.<locals>.<listcomp>)rF�listdirr8r6r6r6r7�pids<sr�cCstjjtjjt�t|�d��S)z&Check for the existence of a unix pid.Zpsinfo)rFr0�existsrfr8�str)rrr6r6r7�
pid_existsAsr�cs�fdd�}|S)z�Call callable into a try/except clause and translate ENOENT,
    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
    cs�y�|f|�|�Stk
r�}z�tdks:tdks:tdkr<�|jtjtjfkrzt|j�sht|j|j	��nt|j|j	|j
��|jtjtjfkr�t|j|j	���WYdd}~XnXdS)N)
�EnvironmentErrorrrr�errno�ENOENTZESRCHr�rr�_name�_ppidZEPERMZEACCES)�self�args�kwargs�err)�funr6r7�wrapperKs
z wrap_exceptions.<locals>.wrapperr6)r�r�r6)r�r7�wrap_exceptionsFsr�c@sheZdZdZddddgZdd�Zdd	�Zd
d�Zedd
��Z	edd��Z
edd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zer�edd��Zed@dd ��Zed!d"��Zed#d$��Zed%d&��Zed'd(��Zed)d*��Zed+d,��Zed-d.��Zed/d0��Zed1d2��ZeZed3d4��Zd5d6�Z ed7d8��Z!ed9d:��Z"edAd<d=��Z#ed>d?��Z$d;S)B�Processz1Wrapper class around underlying C implementation.rrr�r��_procfs_pathcCs||_d|_d|_t�|_dS)N)rrr�r�r8r�)r�rrr6r6r7�__init__fszProcess.__init__cCs"|jj�|jj�|jj�dS)N)�_proc_name_and_argsZcache_activate�_proc_basic_info�
_proc_cred)r�r6r6r7�
oneshot_enterls

zProcess.oneshot_entercCs"|jj�|jj�|jj�dS)N)r�Zcache_deactivater�r�)r�r6r6r7�oneshot_exitqs

zProcess.oneshot_exitcCstj|j|j�S)N)r:Zproc_name_and_argsrrr�)r�r6r6r7r�vszProcess._proc_name_and_argscCstj|j|j�S)N)r:Zproc_basic_inforrr�)r�r6r6r7r�zszProcess._proc_basic_infocCstj|j|j�S)N)r:Z	proc_credrrr�)r�r6r6r7r�~szProcess._proc_credcCs |jdkrdS|j�djd�S)NrZswapper�)rrr��rstrip)r�r6r6r7r|�s
zProcess.namecCs�|j�d}tjj|krttjj|�s>tjjtjj|j�|��}tjj|�rhtjj|�rhtj	|tj
�rh|Stjj|�}xLtjdj
d�D]8}tjjtjj||��}tjj|�r�tj	|tj
�r�|Sq�WdS)Nr�PATH�:r\)�cmdlinerFr0�sep�isabs�abspathrf�cwd�isfile�access�X_OK�basename�environ�split)r��exer0Zpossible_exer6r6r7r��szProcess.execCs|j�djd�S)Nrr3)r�r�)r�r6r6r7r��szProcess.cmdlinecCs|j�tdS)Nr!)r��
proc_info_map)r�r6r6r7r!�szProcess.create_timecCs|j�tdS)Nr#)r�r�)r�r6r6r7r#�szProcess.num_threadscCsZtj|j�}g}x*|D]"\}}}tj|||�}|j|�qW|sVtjd|j|jf�|S)Nz%s/%s)	r:rrrrZpthreadr_rF�statr�)r�roraZ	thread_id�utimeZstimercr6r6r7�threads�szProcess.threads�inetcCs,t||jd�}|s(tjd|j|jf�|S)N)rmz%s/%s)rgrrrFr�r�)r�rlrCr6r6r7�connections�szProcess.connectionscCstj|j�S)N)�
cext_posix�getpriorityrr)r�r6r6r7�nice_get�szProcess.nice_getcCstj|j|�S)N)r��setpriorityrr)r��valuer6r6r7�nice_set�szProcess.nice_setcCs|j�td|_|jS)Nr)r�r�r�)r�r6r6r7r�szProcess.ppidcCs"|j�\}}}}}}tj|||�S)N)r�r�puids)r��real�	effective�saved�_r6r6r7�uids�szProcess.uidscCs"|j�\}}}}}}tj|||�S)N)r�rr�)r�r�r�r�r�r6r6r7�gids�szProcess.gidscCstj|j|j�}tj|�S)N)r:Zproc_cpu_timesrrr�rZ	pcputimes)r�rDr6r6r7rD�szProcess.cpu_timescCsP|j�td}|d@d?|d@B}x&tjd�D]}tj|�j|kr0|Sq0WdS)Nr%l��i��z	/dev/**/*)r�r��globrFr��st_rdev)r�ZttydevZdevr6r6r7�terminal�szProcess.terminalcCsr|j}ytjd||jf�}|jd�Stk
rl}z,|jtjkrZtjd||jf�dS�WYdd}~XnXdS)Nz	%s/%s/cwd�/z%s/%s)	r�rF�readlinkrrr��OSErrorr�r�r�)r�Zprocfs_path�resultr�r6r6r7r��s
zProcess.cwdcCs2|j�}|tdd}|tdd}t||�S)Nrir )r�r�r&)r�rCrr r6r6r7�memory_info�szProcess.memory_infocCs|j�td}tj|d�S)Nr$�?)r�r��
PROC_STATUSESrz)r��coder6r6r7r$szProcess.statuscCs�tjddt|j�gtjtjd�}|j�\}}trFdd�||fD�\}}d|j�kr`t|j|j	��t
jd|�}g}xR|D]J\}}|j�}|j
d�r�|d	d�}|j�d
kr�qv|jtj|t|���qvW|S)Nz/usr/bin/procfilesz-n)rKrLcSsg|]}|jtjj��qSr6)rMr4rKrN)r>r?r6r6r7r@sz&Process.open_files.<locals>.<listcomp>zno such processz(\d+): S_IFREG.*\s*.*name:(.*)
z//rzcannot be retrieved)rOrPr�rrrQrRr�lowerrr�rv�findallrU�
startswithr_rZ	popenfilerx)r�rYrKrLZ	procfilesrarqr0r6r6r7�
open_filess$
zProcess.open_filescCs(|jdkrdSttjd|j|jf��S)Nrz%s/%s/fd)rrrWrFr�r�)r�r6r6r7�num_fds$s
zProcess.num_fdscCstjtj|j��S)N)rZpctxswr:Zproc_num_ctx_switchesrr)r�r6r6r7�num_ctx_switches*szProcess.num_ctx_switchesNcCstj|j||j�S)N)rZwait_pidrrr�)r�Ztimeoutr6r6r7�wait/szProcess.waitc
CsXytj|j�\}}}}Wn.tk
rFt|j�s@t|j|j���YnXtj||||�S)N)	r:Zproc_io_countersrrr�r�rr�rZpio)r�ZrcZwc�rb�wbr6r6r7�io_counters3s
zProcess.io_counters)r�)N)%�__name__�
__module__�__qualname__�__doc__�	__slots__r�r�r�r
r�r�r�r�r|r�r�r!r#�HAS_THREADSr�r�r�r�rr�r�rDr�r�r�Zmemory_full_infor$r�r�r�r�r�r6r6r6r7r�asDr�)Fre)re)ir�r�r�rFrvrOr4�collectionsrZsocketrr\rrrr:rr�r	r
rrr
rrrZ_compatr�_exceptionsrrrZ__extra__all__�hasattrr�rGZ	PAGE_SIZEZAF_LINKZSIDLZSTATUS_IDLEZSZOMBZ
STATUS_ZOMBIEZSACTIVEZSTATUS_RUNNINGZSSWAPZSSTOPZSTATUS_STOPPEDr�ZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZ
TCPS_SYN_RCVDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGZPSUTIL_CONN_NONEZ	CONN_NONEri�dictr�r&Zpfullmemr'r*r/rf�_fieldsr2r8r;r<rDrArIrZr[Zdisk_io_countersr^r]rtZnet_io_countersrgrur}r�r�r�r��objectr�r6r6r6r7�<module>s�

	

	

!$__pycache__/_pssunos.cpython-36.opt-1.pyc000064400000042532150466730530014231 0ustar003

��JZ2d�@s
dZddlZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddl	mZddl	mZ
dd	l	mZdd
l
mZddl
mZddl
mZdd
l
mZddl
mZddl
mZddlmZddlmZddlmZddlmZddlmZdddgZejd�Ze
j Z ej!d^kZ"dZ#dZ$ej%e
j&ej'e
j(ej)e
j*ej+e
j,ej-e
j.ej/e
j(ej0e
j1iZ2ej3e
j4ej5e
j6ej7e
j8ej9e
j:ej;e
j<ej=e
j>ej?e
j@ejAe
jBejCe
jDejEe
jFejGe
jHejIe
jJejKe#ejLe$iZMeNddddddd d!d"�ZOed#d$d%d&d'g�ZPed(d$d%d)d*g�ZQed+d,d-d.d/d0g�ZRed1d2d3g�ZSeSZTed4d5d2d6d7g�ZUed8d9d:jVeUjW��ZXd;d<�ZYd=d>�ZZd?d@�Z[dAdB�Z\dCdD�Z]dEdF�Z^dGdH�Z_dIdJ�Z`ejaZaejbZbd_dLdM�ZcejdZde
jeZedadNdO�ZfdPdQ�ZgdRdS�ZhdTdU�ZidVdW�ZjdXdY�ZkdZd[�ZlGd\d]�d]em�ZndS)bz'Sun OS Solaris platform implementation.�N)�
namedtuple)�AF_INET�)�_common)�_psposix)�
_psutil_posix)�
_psutil_sunos)�AF_INET6)�
isfile_strict)�memoize_when_activated)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�b)�PY3)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�	CONN_IDLE�
CONN_BOUND�PROCFS_PATH�SC_PAGE_SIZE�� ZIDLEZBOUND�����)�ppid�rss�vms�create_time�nice�num_threads�status�ttynr�	scputimes�user�systemZidleZiowait�	pcputimes�
children_user�children_system�svmem�totalZ	available�percent�used�free�pmemr r!�
pmmap_grouped�pathZ	anonymous�locked�	pmmap_extzaddr perms � cCstjdjS)z+Return updated psutil.PROCFS_PATH constant.Zpsutil)�sys�modulesr�r:r:� /usr/lib64/python3.6/_pssunos.py�get_procfs_pathqsr<cCsFtjd�t}tjd�t}}||}t||dd�}t|||||�S)zReport virtual memory metrics.�
SC_PHYS_PAGES�SC_AVPHYS_PAGESr)�_round)�os�sysconf�	PAGE_SIZErr-)r.r1Zavailr0r/r:r:r;�virtual_memory{s
rCc
Cstj�\}}tjddtjdddgtjd�}|j�\}}trL|j	t
jj�}|j
dkrdtd|j
��|j�jd	�d
d�}|s�td��d}}xL|D]D}|j�}|dd�\}	}
|tt|	�d�7}|tt|
�d�7}q�W||}t||d
d�}tj|||||t|t�S)zReport swap memory metrics.z/usr/bin/envzPATH=/usr/sbin:/sbin:%s�PATHZswapz-l)�stdoutrz'swap -l' failed (retcode=%s)�
rNzno swap device(s) configuredri)r?���)�cextZswap_mem�
subprocess�Popenr@�environ�PIPE�communicater�decoder8rE�encoding�
returncode�RuntimeError�strip�split�intrrZsswaprB)
ZsinZsout�prE�stderr�linesr.r1�line�t�fr0r/r:r:r;�swap_memory�s,


r[cCstj�}tdd�t|�D��S)z-Return system-wide CPU times as a named tuplecSsg|]}t|��qSr:)�sum)�.0�xr:r:r;�
<listcomp>�szcpu_times.<locals>.<listcomp>)rH�
per_cpu_timesr'�zip)�retr:r:r;�	cpu_times�srccCstj�}dd�|D�S)z5Return system per-CPU times as a list of named tuplescSsg|]}t|��qSr:)r')r]r^r:r:r;r_�sz!per_cpu_times.<locals>.<listcomp>)rHr`)rbr:r:r;r`�sr`cCs$y
tjd�Stk
rdSXdS)z0Return the number of logical CPUs in the system.�SC_NPROCESSORS_ONLNN)r@rA�
ValueErrorr:r:r:r;�cpu_count_logical�s
rfcCstj�S)z1Return the number of physical CPUs in the system.)rHZcpu_count_physr:r:r:r;�cpu_count_physical�srgcCs$tj�\}}}}d}tj||||�S)z*Return various CPU stats as a named tuple.r)rH�	cpu_statsrZ	scpustats)Zctx_switchesZ
interruptsZsyscallsZtrapsZsoft_interruptsr:r:r;rh�s
rhFc	Cs`g}tj�}xN|D]F}|\}}}}|dkr.d}|s>t|�js>qtj||||�}|j|�qW|S)zReturn system disk partitions.Znone�)rH�disk_partitions�
disk_usager.rZ	sdiskpart�append)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZoptsZntupler:r:r;rj�s

rjc	Cstjj�}|dkr|jdd�||krFtd|djdd�|D��f��tj|\}}tj|�}t�}x�|D]�}|\}}	}
}}}
}|	|kr�qj|
|kr�qj|	t	t
fkr�|r�tj|�}|r�tj|�}t|
}
t
|	�}	t|
�}
|d	kr�tj||	|
|||
|�}ntj||	|
|||
�}|j|�qjWt|�S)
z�Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    Only INET sockets are returned (UNIX are not).
    r�unixrz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr:)�repr)r]r^r:r:r;r_�sz#net_connections.<locals>.<listcomp>���rr)rZ	conn_tmap�copy�popre�joinrH�net_connections�setrr	�addr�TCP_STATUSESrr
Zsconn�pconn�add�list)�kind�_pidZcmapZfamilies�types�rawlistrb�item�fdZfamZtype_ZladdrZraddrr%�pid�ntr:r:r;rv�s8




rvcCsVtj�}xH|j�D]<\}}|\}}}}ttd�r:tj|�}tj||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)rH�net_if_stats�items�hasattrrr�Z	snicstats)rb�namer�ZisupZduplexZspeedZmtur:r:r;r�s

r�cCstj�S)z:The system boot time expressed in seconds since the epoch.)rH�	boot_timer:r:r:r;r�)sr�cCs`g}tj�}d}xJ|D]B}|\}}}}}}	|s0q||kr<d}tj|||||	�}
|j|
�qW|S)z:Return currently connected users as a list of namedtuples.�:0.0�:0�	localhost)r�r�)rH�usersrZsuserrl)rnr�r�r�r(�ttyZhostnameZtstampZuser_processr�r�r:r:r;r�.s
r�cCsdd�tjtt���D�S)z7Returns a list of PIDs currently running on the system.cSsg|]}|j�rt|��qSr:)�isdigitrT)r]r^r:r:r;r_Hszpids.<locals>.<listcomp>)r@�listdirrr<r:r:r:r;�pidsFsr�cCs
tj|�S)z&Check for the existence of a unix pid.)r�
pid_exists)r�r:r:r;r�Ksr�cs�fdd�}|S)z�Call callable into a try/except clause and translate ENOENT,
    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
    cs�y�|f|�|�Stk
r�}z�|jdkrHdt�krFt|j|j��n�|jtjtjfkr�t|j�stt	|j|j��nt
|j|j|j��|jtjtj
fkr�t|j|j���WYdd}~XnXdS)Nr)�EnvironmentErrorr�r�r�_name�errno�ENOENT�ESRCHr�rr�_ppidZEPERMZEACCES)�self�args�kwargs�err)�funr:r;�wrapperUs


z wrap_exceptions.<locals>.wrapperr:)r�r�r:)r�r;�wrap_exceptionsPsr�c@s�eZdZdZddddgZdd�Zdd	�Zd
d�Zedd
��Z	edd��Z
edd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zedd��Zedd��Zed d!��Zed"d#��Zed$d%��Zed&d'��Zed(d)��Zed*d+��Zed,d-��Zed.d/��Zed0d1��ZeZed2d3��Zed4d5��Zed6d7��Z d8d9�Z!edId;d<��Z"e#d=d>�Z$e#d=d?�Z%ed@dA��Z&edBdC��Z'edDdE��Z(edJdGdH��Z)dFS)K�Processz1Wrapper class around underlying C implementation.r�r�r��_procfs_pathcCs||_d|_d|_t�|_dS)N)r�r�r�r<r�)r�r�r:r:r;�__init__qszProcess.__init__cCs"|jj�|jj�|jj�dS)N)�_proc_name_and_argsZcache_activate�_proc_basic_info�
_proc_cred)r�r:r:r;�
oneshot_enterws

zProcess.oneshot_entercCs"|jj�|jj�|jj�dS)N)r�Zcache_deactivater�r�)r�r:r:r;�oneshot_exit|s

zProcess.oneshot_exitcCstj|j|j�S)N)rHZproc_name_and_argsr�r�)r�r:r:r;r��szProcess._proc_name_and_argscCstj|j|j�}|S)N)rHZproc_basic_infor�r�)r�rbr:r:r;r��szProcess._proc_basic_infocCstj|j|j�S)N)rHZ	proc_credr�r�)r�r:r:r;r��szProcess._proc_credcCs|j�dS)Nr)r�)r�r:r:r;r��szProcess.namecCs8ytjd|j|jf�Stk
r*YnX|j�dS)Nz%s/%s/path/a.outri)r@�readlinkr�r��OSError�cmdline)r�r:r:r;�exe�szProcess.execCs|j�djd�S)Nrr7)r�rS)r�r:r:r;r��szProcess.cmdlinecCstj|j|j�S)N)rHZproc_environr�r�)r�r:r:r;rK�szProcess.environcCs|j�tdS)Nr")r��
proc_info_map)r�r:r:r;r"�szProcess.create_timecCs|j�tdS)Nr$)r�r�)r�r:r:r;r$�szProcess.num_threadscCsbytj|j�Stk
r\}z4|jtjtjdfkrJt|j�rJt|j|j	���WYdd}~XnXdS)N�0)
�
cext_posix�getpriorityr�r�r�r�r�r�rr�)r�r�r:r:r;�nice_get�s
zProcess.nice_getcCs&|jdkrt|j|j��tj|j|�S)Nrr)rr)r�rr�r��setpriority)r��valuer:r:r;�nice_set�s
zProcess.nice_setcCs|j�td|_|jS)Nr)r�r�r�)r�r:r:r;r�szProcess.ppidcCs"|j�\}}}}}}tj|||�S)N)r�r�puids)r��real�	effective�saved�_r:r:r;�uids�szProcess.uidscCs"|j�\}}}}}}tj|||�S)N)r�rr�)r�r�r�r�r�r:r:r;�gids�szProcess.gidscCs\ytj|j|j�}Wn<tk
rP}z |jtjkr>tr>d}n�WYdd}~XnXtj	|�S)N�)r�r�r�r�)
rHZproc_cpu_timesr�r�r�r��	EOVERFLOW�	IS_64_BITrr*)r��timesr�r:r:r;rc�szProcess.cpu_timescCstj|j|j�S)N)rHZproc_cpu_numr�r�)r�r:r:r;�cpu_num�szProcess.cpu_numcCs�|j}d}t|j�td�}|tjkr�xZd
D]R}ytjd||j|f�St	k
r~}z|j
t
jkrld}w.�WYdd}~Xq.Xq.W|r�tjd	||jf�dS)NFr&rrr�z
%s/%d/path/%dTz%s/%s)rrrr�)
r�r�r�r�rHZPRNODEVr@r�r�r�r�r��stat)r��procfs_path�
hit_enoentr�r^r�r:r:r;�terminal�s 

zProcess.terminalcCsh|j}ytjd||jf�Stk
rb}z,|jtjkrPtjd||jf�dS�WYdd}~XnXdS)Nz%s/%s/path/cwdz%s/%s)r�r@r�r�r�r�r�r�)r�r�r�r:r:r;�cwdszProcess.cwdcCs2|j�}|tdd}|tdd}t||�S)Nr ir!)r�r�r2)r�rbr r!r:r:r;�memory_infoszProcess.memory_infocCs|j�td}tj|d�S)Nr%�?)r�r��
PROC_STATUSES�get)r��coder:r:r;r%$szProcess.statusc
Cs�|j}g}tjd||jf�}d}x�|D]�}t|�}ytj|j||�\}}WnJtk
r�}z.|jtj	krrt
rrw(|jtjkr�d}w(�WYdd}~Xq(Xtj
|||�}	|j|	�q(W|r�tjd||jf�|S)Nz	%s/%d/lwpFTz%s/%s)r�r@r�r�rTrHZquery_process_threadr�r�r�r�r�rZpthreadrlr�)
r�r�rbZtidsr��tid�utimeZstimer�r�r:r:r;�threads*s*
zProcess.threadsc	Cs�g}d}|j}d||jf}x�tjd||jf�D]�}tjj||�}tjj|�r2ytj|�}Wn6tk
r�}z|j	t	j
kr�d}w2�WYdd}~Xq2Xt|�r2|jt
j|t|���q2W|r�tjd||jf�|S)NFz
%s/%d/pathz%s/%d/fdTz%s/%s)r�r�r@r�r4ru�islinkr�r�r�r�r
rlrZ	popenfilerTr�)	r�rnr�r�Zpathdirr�r4�filer�r:r:r;�
open_filesLs&zProcess.open_filesccs,d|}tj|dtjtjd�}|j�\}}trDdd�||fD�\}}|jdkr�d|j�krht|j|j	��d|j�kr�t
|j|j	��td	||f��|jd
�dd�}x�t
|�D]v\}}|j�}|jd
�r�|jdd�d}	||dj�}
|
dkr�tj}
n|
dk�r
tj}
nd}
dtj|
|	dtjfVq�WdS)z<Get UNIX sockets used by process by parsing 'pfiles' output.z	pfiles %sT)�shellrErVcSsg|]}|jtjj��qSr:)rNr8rErO)r]r^r:r:r;r_nsz-Process._get_unix_sockets.<locals>.<listcomp>rzpermission deniedzno such processz%r command error
%srFrNzsockname: AF_UNIXr7�SOCK_STREAM�
SOCK_DGRAMrrirrrr)rIrJrLrMrrP�lowerrr�r�rrQrS�	enumerate�lstrip�
startswithrR�socketr�r�ZAF_UNIXr�	CONN_NONE)r�r��cmdrUrErVrW�irXr4�typer:r:r;�_get_unix_socketses2



zProcess._get_unix_sockets�inetcCsPt||jd�}|s(tjd|j|jf�|dkrL|jdd�|j|j�D��|S)N)r~z%s/%srmrpcSsg|]}tj|��qSr:)rrz)r]Zconnr:r:r;r_�sz'Process.connections.<locals>.<listcomp>)rmrp)rvr�r@r�r��extendr�)r�r}rbr:r:r;�connections�s
zProcess.connectionsZmmapzpath rss anon lockedzaddr perms path rss anon lockedc$Cs.dd�}|j}g}ytj|j|�}Wn:tk
r^}z|jtjkrLtrLgS�WYdd}~XnXd}x�|D]�}|\}}	}
}}}
}|||	�}|jd�s�yt	j
d||j|f�}WnFtk
r�}z*|jtjkr�d||j|f}d}n�WYdd}~XnX|j||
|||
|f�qjW|�r*t	j
d||jf�|S)NcSs0dt|�dd�jd�t|�dd�jd�fS)Nz%s-%sr�L)�hexrR)�start�endr:r:r;�toaddr�sz#Process.memory_maps.<locals>.toaddrF�[z
%s/%s/path/%sTz%s/%s)r�rHZproc_memory_mapsr�r�r�r�r�r�r@r�r�rlr�)r�r�r�rnr�r�r�r�rxZaddrsizeZpermr�r Zanonr5r:r:r;�memory_maps�s4


zProcess.memory_mapscCsttjd|j|jf��S)Nz%s/%s/fd)�lenr@r�r�r�)r�r:r:r;�num_fds�szProcess.num_fdscCstjtj|j|j��S)N)rZpctxswrHZproc_num_ctx_switchesr�r�)r�r:r:r;�num_ctx_switches�szProcess.num_ctx_switchesNcCstj|j||j�S)N)rZwait_pidr�r�)r�Ztimeoutr:r:r;�wait�szProcess.wait)r�)N)*�__name__�
__module__�__qualname__�__doc__�	__slots__r�r�r�rr�r�r�r�r�r�r�rKr"r$r�r�rr�r�rcr�r�r�r�Zmemory_full_infor%r�r�r�r�rZnt_mmap_groupedZnt_mmap_extr�r�r�r�r:r:r:r;r�lsL

" 

0r�l)Frr)rr)or�r�r@r�rIr8�collectionsrrrirrrr�rrHr	r
rrr
rZ_compatrr�_exceptionsrrrZ__extra__all__rArBZAF_LINK�maxsizer�rrZSSLEEPZSTATUS_SLEEPINGZSRUNZSTATUS_RUNNINGZSZOMBZ
STATUS_ZOMBIEZSSTOPZSTATUS_STOPPEDZSIDLZSTATUS_IDLEZSONPROCZSWAITZSTATUS_WAITINGr�ZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZ
TCPS_SYN_RCVDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGZPSUTIL_CONN_NONEr�Z	TCPS_IDLEZ
TCPS_BOUNDry�dictr�r'r*r-r2Zpfullmemr3ru�_fieldsr6r<rCr[rcr`rfrgrhZdisk_io_countersrkrjZnet_io_countersZnet_if_addrsrvr�r�r�r�r�r��objectr�r:r:r:r;�<module>s�



	
&	


$__pycache__/_psbsd.cpython-36.opt-1.pyc000064400000045207150466730530013634 0ustar003

��JZ$v�@sldZddlZddlZddlZddlZddljjZddl	m
Z
ddlmZddl
mZddl
mZddl
mZdd	l
mZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"ddl m#Z#gZ$e�rhej%ej&ej'ej(ej)ej*ej+ej,ej-ej.ej/ej0ej1ej2iZ3n�e�ste�r�ej%ej&ej)ej*ej+ej,ej4ej.ej-ej.ej'ej5ej6ej(iZ3nBe�r�ej%ej&ej7ej(ej8ej.ej+ej,ej-ej.ej4ej9ej:ej;iZ3ej<ej=ej>ej?ej@ejAejBejCejDejEejFejGejHejIejJejKejLejMejNejOejPejQejRejSiZTe�rjejUd�ZVn
ejUd�ZVejWZWeXddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1�ZYe
d2d3d4d5d6d7d8d9d:d;d<d=g�ZZe
d>d?d@dAdBdCg�Z[e
dDdEdFdGdHdIg�Z\e\Z]e
dJd?dAdKdLg�Z^e
dMdN�Z_e
dOdP�Z`e�rFe
dQdRdSdTdUdVdWdXg�Zane
dQdRdSdTdUg�ZadYdZ�Zbd[d\�Zcd]d^�Zdeeed_��r�d`d_�Zfndad_�Zfdbef_gdcdd�Zhe�s�e�r�dedf�Zindgdf�Zidhdi�Zjd�djdk�ZkejlZlejmZmejnZnejoZodldm�Zpdndo�Zqe�rdpdq�Zrdrds�Zsdtdu�Ztedvdw��Zudxdy�Zve�s2e�r<dzd{�ZwnejwZwd|d}�Zxejyd~d��ZzGd�d��d�e{�Z|dS)�z5FreeBSD, OpenBSD and NetBSD platforms implementation.�N)�
namedtuple)�AF_INET�)�_common)�_psposix)�_psutil_bsd)�
_psutil_posix)�AF_INET6)�	conn_tmap)�FREEBSD)�memoize)�memoize_when_activated)�NETBSD)�OPENBSD)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�which)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�SC_PAGESIZE�SC_PAGE_SIZE��������	�
���
�����������)�ppid�status�real_uid�
effective_uid�	saved_uid�real_gid�
effective_gid�	saved_gid�ttynr�create_time�ctx_switches_vol�ctx_switches_unvol�
read_io_count�write_io_count�	user_time�sys_time�ch_user_time�ch_sys_time�rss�vms�memtext�memdata�memstack�cpunum�name�svmem�totalZ	available�percent�used�free�active�inactive�buffers�cached�shared�wired�	scputimes�user�nice�system�idle�irq�pmemrBrC�text�data�stack�	pcputimes�
children_user�children_system�
pmmap_groupedz*path rss, private, ref_count, shadow_count�	pmmap_extz6addr, perms path rss, private, ref_count, shadow_count�sdiskioZ
read_countZwrite_countZ
read_bytesZwrite_bytesZ	read_timeZ
write_timeZ	busy_timecCs�tj�}|\}}}}}}}}tr�tdd��R}	xJ|	D]B}
|
jd�rVt|
j�d�d}q2|
jd�r2t|
j�d�d}q2WWdQRX|||}|||}t|||dd�}
t|||
||||||||�S)	z&System virtual memory as a namedtuple.z
/proc/meminfo�rbsBuffers:ris
MemShared:N)�_round)	�cextZvirtual_memr�open�
startswith�int�splitrrI)ZmemrJrMrNrOrSrQrPrR�f�lineZavailrLrK�rm�/usr/lib64/python3.6/_psbsd.py�virtual_memory�s


"rocCs4tj�\}}}}}t||dd�}tj||||||�S)z@System swap memory as (total, used, free, sin, sout) namedtuple.r)re)rfZswap_memrrZsswap)rJrLrMZsinZsoutrKrmrmrn�swap_memory�srpcCs"tj�\}}}}}t|||||�S)z+Return system per-CPU times as a namedtuple)rf�	cpu_timesrT)rUrVrWrXrYrmrmrnrq�srq�
per_cpu_timescCsBg}x8tj�D],}|\}}}}}t|||||�}|j|�qW|S)z'Return system CPU times as a namedtuple)rfrrrT�append)�retZcpu_trUrVrWrXrY�itemrmrmrnrr�scCs.t�dkrt�gStjr td��dt_t�gS)z'Return system CPU times as a namedtuplerz&supported only starting from FreeBSD 8T)�cpu_count_logicalrqrr�
__called__�NotImplementedErrorrmrmrmrnrr�s
FcCstj�S)z0Return the number of logical CPUs in the system.)rfrvrmrmrmrnrv�srvcCst�dkrdSdS)Nr)rvrmrmrmrn�cpu_count_physical�sryc
Csxd}tj�}|dk	rb|jd�}|dkrb|d|d�}tj|�}zt|jd��pRd}Wd|j�X|stt�dkrtdS|S)z1Return the number of physical CPUs in the system.Nz	</groups>rr zgroup/children/group/cpu���)	rfZcpu_count_phys�rfind�ETZ
fromstring�len�findall�clearrv)rt�s�index�rootrmrmrnry�s



c	Cs�trtj�\}}}}}nttrrtj�\}}}}}}}tdd��.}x&|D]}|jd�rDt|j�d�}qDWWdQRXntr�tj�\}}}}}}}t	j
||||�S)z*Return various CPU stats as a named tuple.z
/proc/statrdsintrrN)rrf�	cpu_statsrrgrhrirjrrZ	scpustats)	ZctxswZintrsZ
soft_intrsZsyscallsZtrapsZfaultsZforksrkrlrmrmrnr�s

 r�c	CsDg}tj�}x2|D]*}|\}}}}tj||||�}|j|�qW|S)z�Return mounted disk partitions as a list of namedtuples.
    'all' argument is ignored, see:
    https://github.com/giampaolo/psutil/issues/906
    )rf�disk_partitionsrZ	sdiskpartrs)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZopts�ntuplermrmrnr�<s
r�cCsjt�j�}i}xV|D]N}tj|�}tj|�}tj|�\}}ttd�rNtj|�}tj	||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)
�net_io_counters�keys�
cext_posixZ
net_if_mtuZnet_if_flagsZnet_if_duplex_speed�hasattrrr�Z	snicstats)�namesrtrHZmtuZisupZduplexZspeedrmrmrn�net_if_statsWs





r�cCs�trzg}xlt�D]b}yt|�j|�}Wnttfk
r@wYqXx.|D]&}t|�}|j|�|jtj	|��qHWqW|S|tj
kr�td|djdd�t
D��f��t
|\}}t
�}tr�tjd�}ntj�}x�|D]�}|\}	}
}}}
}}|
|ko�||kr�yt|}Wn tk
�r&ttj}YnX|
ttfk�rV|�rFtj|�}|
�rVtj|
�}
t|
�}
t|�}tj	|	|
|||
||�}|j|�q�Wt|�S)z System-wide network connections.z+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSrm)�repr)�.0�xrmrmrn�
<listcomp>wsz#net_connections.<locals>.<listcomp>rrz)r�pids�Process�connectionsrr�listrsrZsconnr
�
ValueError�join�setrrf�net_connections�TCP_STATUSES�KeyError�PSUTIL_CONN_NONErr	�addrrr�add)�kindrt�pidZconsZconn�families�types�rawlistru�fd�fam�type�laddr�raddrr1�ntrmrmrnr�esJ





r�cCsbytj�\}}}Wntk
r&dSX|dk}|r<tj}n|dkrLtj}n|d}tj|||�S)zReturn battery info.Nr�<rz)rf�sensors_batteryrxrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)rKZminsleftZ
power_pluggedZsecsleftrmrmrnr��sr�cCstj�S)z:The system boot time expressed in seconds since the epoch.)rf�	boot_timermrmrmrnr��sr�c	Csbg}tj�}xP|D]H}|\}}}}}|dkr0d}|dkr:qtj||pFd|||�}|j|�qW|S)z:Return currently connected users as a list of namedtuples.rN�~rz)rf�usersrZsuserrs)	r�r�rurUZttyZhostnameZtstampr�r�rmrmrnr��s
r�cCs@ytd�j�Wn&tk
r$dStk
r6dSXdSdS)NrFT)r�rHrrrmrmrmrn�
_pid_0_exists�sr�cCs*tj�}tr&d|kr&t�r&|jdd�|S)z7Returns a list of PIDs currently running on the system.r)rfr�rr��insert)rtrmrmrnr��sr�cCs tj|�}|s|t�kSdSdS)zReturn True if pid exists.TN)r�
pid_existsr�)r��existsrmrmrnr��s

r�cstj���fdd��}|S)z`Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    cs�y�|f|�|�Stk
r�}z�|jdkrHdt�krFt|j|j��n�|jtjkr�t|j�snt|j|j��nt	|j|j|j
��|jtjtjfkr�t|j|j���WYdd}~XnXdS)Nr)
�OSErrorr�r�r�_name�errno�ESRCHr�rr�_ppid�EPERM�EACCES)�self�args�kwargs�err)�funrmrn�wrapper�s


z wrap_exceptions.<locals>.wrapper)�	functools�wraps)r�r�rm)r�rn�wrap_exceptions�sr�ccs�y
dVWn�tk
r�}zf|jtjtjfkrZt|j�sHt|j|j��nt|j|j|j	��|jtj
tjfkrzt|j|j���WYdd}~XnXdS)z8Same as above, for routines relying on reading /proc fs.N)
�EnvironmentErrorr��ENOENTr�r�r�rr�rr�r�r�r)Zinstr�rmrmrn�wrap_exceptions_procfs
s

r�c@s�eZdZdZdddgZdd�Zedd��Zd	d
�Zdd�Z	e
d
d��Ze
dd��Ze
dd��Z
e
dd��Ze
dd��Ze
dd��Ze
dd��Ze
dd��Zer�e
dd��Ze
dd ��ZeZe
d!d"��Ze
d#d$��Ze
d%d&��Ze
d'd(��Ze
dJd*d+��Ze
dKd-d.��Ze
d/d0��Ze
d1d2��Ze
d3d4��Ze
d5d6��Z e
d7d8��Z!e"d9d:�Z#e"d9d;�Z$d<d=�Z%e&e'd>��rxe
d?d@��Z(ne%Z(e&e'dA��r�e
dBdC��Z)ne%Z)e�r�e
dDdE��Z*e
dFdG��Z+e
dHdI��Z,d,S)Lr�z1Wrapper class around underlying C implementation.r�r�r�cCs||_d|_d|_dS)N)r�r�r�)r�r�rmrmrn�__init__"szProcess.__init__cCstj|j�}|S)z;Retrieves multiple process info in one shot as a raw tuple.)rfZproc_oneshot_infor�)r�rtrmrmrn�oneshot'szProcess.oneshotcCs|jj�dS)N)r�Zcache_activate)r�rmrmrn�
oneshot_enter.szProcess.oneshot_entercCs|jj�dS)N)r�Zcache_deactivate)r�rmrmrn�oneshot_exit1szProcess.oneshot_exitcCs(|j�td}|dk	r|Stj|j�S)NrH)r��kinfo_proc_maprfZ	proc_namer�)r�rHrmrmrnrH4szProcess.namec
Csdtrtj|j�StrD|jdkr"dSt|��tjd|j�SQRXn|j�}|r\t	|d�SdSdS)Nr�z/proc/%s/exe)
rrfZproc_exer�rr��os�readlink�cmdliner)r�r�rmrmrn�exe9s

zProcess.execCs�tr|jdkrgStr�ytj|j�Stk
r�}zB|jtjkrnt|j�sZt	|j|j
��qpt|j|j
|j��n�WYdd}~Xq�Xntj|j�SdS)Nr)
rr�rrfZproc_cmdliner�r��EINVALr�rr�rr�)r�r�rmrmrnr�Os
zProcess.cmdlinecCs:|j�td}tj�}y||Stk
r4dSXdS)Nr8)r�r�rZget_terminal_mapr�)r�Ztty_nrZtmaprmrmrn�terminaleszProcess.terminalcCs|j�td|_|jS)Nr0)r�r�r�)r�rmrmrnr0nszProcess.ppidcCs.|j�}tj|td|td|td�S)Nr2r3r4)r�rZpuidsr�)r��rawtuplermrmrn�uidsss


zProcess.uidscCs.|j�}tj|td|td|td�S)Nr5r6r7)r�rZpgidsr�)r�r�rmrmrn�gids{s


zProcess.gidscCs8|j�}tj|td|td|td|td�S)Nr>r?r@rA)r�rr^r�)r�r�rmrmrnrq�s


zProcess.cpu_timescCs|j�tdS)NrG)r�r�)r�rmrmrn�cpu_num�szProcess.cpu_numcCs@|j�}t|td|td|td|td|td�S)NrBrCrDrErF)r�rZr�)r�r�rmrmrn�memory_info�s



zProcess.memory_infocCs|j�tdS)Nr9)r�r�)r�rmrmrnr9�szProcess.create_timecCs&ttd�rtj|j�St|j��SdS)N�proc_num_threads)r�rfr�r�r}�threads)r�rmrmrn�num_threads�s
zProcess.num_threadscCs$|j�}tj|td|td�S)Nr:r;)r�rZpctxswr�)r�r�rmrmrn�num_ctx_switches�s
zProcess.num_ctx_switchescCsLtj|j�}g}x*|D]"\}}}tj|||�}|j|�qWtrH|j�|S)N)rfZproc_threadsr�rZpthreadrsrrH)r�r�r�Z	thread_id�utimeZstimer�rmrmrnr��szProcess.threads�inetcCs�|tkr(td|djdd�tD��f��t�rt|\}}t�}tj|j�}x�|D]�}|\}}}	}
}}}
||krR|	|krRyt|}Wnt	k
r�ttj
}YnX|ttfkr�|
r�t
j|
�}
|r�t
j|�}t|�}t|	�}	t
j|||	|
||�}|j|�qRW|j�t|�St|\}}tj|j||�}g}x�|D]z}|\}}}	}
}}|ttfk�rv|
�rft
j|
�}
|�rvt
j|�}t|�}t|	�}	t|}t
j|||	|
||�}|j|��q4Wt�r�|j�|S)Nz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSrm)r�)r�r�rmrmrnr��sz'Process.connections.<locals>.<listcomp>)r
r�r�rr�rfr�r�r�r�r�rr	rr�rrZpconnr�rHr�Zproc_connectionsrsr)r�r�r�r�rtr�rur�r�r�r�r�r1r�r�rmrmrnr��sV





zProcess.connectionsNcCstj|j||j�S)N)rZwait_pidr�r�)r�Ztimeoutrmrmrn�wait�szProcess.waitcCstj|j�S)N)r��getpriorityr�)r�rmrmrn�nice_get�szProcess.nice_getcCstj|j|�S)N)r��setpriorityr�)r��valuermrmrn�nice_set�szProcess.nice_setcCs|j�td}tj|d�S)Nr1�?)r�r��
PROC_STATUSES�get)r��codermrmrnr1szProcess.statuscCs(|j�}tj|td|tddd�S)Nr<r=rrzrz)r�rZpior�)r�r�rmrmrn�io_counterss

zProcess.io_countersc
Csftr|jdkrdStr8t|��tjd|j�SQRXn*ttd�rRtj|j�pPdSt	t
r\dnd��dS)z)Return process current working directory.rNz/proc/%s/cwd�proc_open_filesz&supported only starting from FreeBSD 8r�)rr�rr�r�r�r�rfZproc_cwdrxr)r�rmrmrn�cwds

zProcess.cwdZmmapz*path rss, private, ref_count, shadow_countz6addr, perms path rss, private, ref_count, shadow_countcCst�dS)N)rx)r�rmrmrn�_not_implemented)szProcess._not_implementedr�cCstj|j�}dd�|D�S)z8Return files opened by process as a list of namedtuples.cSsg|]\}}tj||��qSrm)rZ	popenfile)r��pathr�rmrmrnr�3sz&Process.open_files.<locals>.<listcomp>)rfr�r�)r�r�rmrmrn�
open_files/szProcess.open_files�proc_num_fdscCstj|j�}tr|j�|S)z=Return the number of file descriptors opened by this process.)rfr�r�rrH)r�rtrmrmrn�num_fds:szProcess.num_fdscCstj|j�S)N)rfZproc_cpu_affinity_getr�)r�rmrmrn�cpu_affinity_getJszProcess.cpu_affinity_getcCs�tttt����}x$|D]}||krtd||f��qWytj|j|�Wn\tk
r�}z@|j	t	j
t	jfkr�x$|D]}||krttd||f��qtW�WYdd}~XnXdS)Nz#invalid CPU #%i (choose between %s))�tuple�ranger}rrr�rfZproc_cpu_affinity_setr�r�r�r�ZEDEADLK)r�ZcpusZallcpusZcpur�rmrmrn�cpu_affinity_setNs

zProcess.cpu_affinity_setcCstj|j�S)N)rfZproc_memory_mapsr�)r�rmrmrn�memory_mapsgszProcess.memory_maps)r�)N)-�__name__�
__module__�__qualname__�__doc__�	__slots__r�r
r�r�r�r�rHr�r�r�r0r�r�rqrr�r�Zmemory_full_infor9r�r�r�r�r�r�r�r1r�r�rZnt_mmap_groupedZnt_mmap_extr�r�rfr�r�r�r�r�rmrmrmrnr�s\
		
6	
r�)F)}r��
contextlibr�r�r�Zxml.etree.ElementTreeZetreeZElementTreer|�collectionsrZsocketrr�rrrrfrr�r	r
rrr
rrrrrZ_compatr�_exceptionsrrrZ__extra__all__ZSIDLZSTATUS_IDLEZSRUNZSTATUS_RUNNINGZSSLEEPZSTATUS_SLEEPINGZSSTOPZSTATUS_STOPPEDZSZOMBZ
STATUS_ZOMBIEZSWAITZSTATUS_WAITINGZSLOCKZ
STATUS_LOCKEDr�ZSDEADZ
STATUS_WAKINGZSONPROCZSACTIVEZSDYINGZSTATUS_DEADZ
SSUSPENDEDZSTATUS_SUSPENDEDZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZTCPS_SYN_RECEIVEDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGr�Z	CONN_NONEr��sysconfZPAGESIZEZAF_LINK�dictr�rIrTrZZpfullmemr^rarbrcrorprqr�rrrwrvryr�r�Z
disk_usageZdisk_io_countersr�Znet_if_addrsr�r�r�r�r�r�r�r�r��contextmanagerr��objectr�rmrmrmrn�<module>s




	
#
6


__pycache__/_pssunos.cpython-36.pyc000064400000042612150466730530013271 0ustar003

��JZ2d�@s
dZddlZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddl	mZddl	mZ
dd	l	mZdd
l
mZddl
mZddl
mZdd
l
mZddl
mZddl
mZddlmZddlmZddlmZddlmZddlmZdddgZejd�Ze
j Z ej!d^kZ"dZ#dZ$ej%e
j&ej'e
j(ej)e
j*ej+e
j,ej-e
j.ej/e
j(ej0e
j1iZ2ej3e
j4ej5e
j6ej7e
j8ej9e
j:ej;e
j<ej=e
j>ej?e
j@ejAe
jBejCe
jDejEe
jFejGe
jHejIe
jJejKe#ejLe$iZMeNddddddd d!d"�ZOed#d$d%d&d'g�ZPed(d$d%d)d*g�ZQed+d,d-d.d/d0g�ZRed1d2d3g�ZSeSZTed4d5d2d6d7g�ZUed8d9d:jVeUjW��ZXd;d<�ZYd=d>�ZZd?d@�Z[dAdB�Z\dCdD�Z]dEdF�Z^dGdH�Z_dIdJ�Z`ejaZaejbZbd_dLdM�ZcejdZde
jeZedadNdO�ZfdPdQ�ZgdRdS�ZhdTdU�ZidVdW�ZjdXdY�ZkdZd[�ZlGd\d]�d]em�ZndS)bz'Sun OS Solaris platform implementation.�N)�
namedtuple)�AF_INET�)�_common)�_psposix)�
_psutil_posix)�
_psutil_sunos)�AF_INET6)�
isfile_strict)�memoize_when_activated)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�b)�PY3)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�	CONN_IDLE�
CONN_BOUND�PROCFS_PATH�SC_PAGE_SIZE�� ZIDLEZBOUND�����)�ppid�rss�vms�create_time�nice�num_threads�status�ttynr�	scputimes�user�systemZidleZiowait�	pcputimes�
children_user�children_system�svmem�totalZ	available�percent�used�free�pmemr r!�
pmmap_grouped�pathZ	anonymous�locked�	pmmap_extzaddr perms � cCstjdjS)z+Return updated psutil.PROCFS_PATH constant.Zpsutil)�sys�modulesr�r:r:� /usr/lib64/python3.6/_pssunos.py�get_procfs_pathqsr<cCsFtjd�t}tjd�t}}||}t||dd�}t|||||�S)zReport virtual memory metrics.�
SC_PHYS_PAGES�SC_AVPHYS_PAGESr)�_round)�os�sysconf�	PAGE_SIZErr-)r.r1Zavailr0r/r:r:r;�virtual_memory{s
rCc
Cstj�\}}tjddtjdddgtjd�}|j�\}}trL|j	t
jj�}|j
dkrdtd|j
��|j�jd	�d
d�}|s�td��d}}xL|D]D}|j�}|dd�\}	}
|tt|	�d�7}|tt|
�d�7}q�W||}t||d
d�}tj|||||t|t�S)zReport swap memory metrics.z/usr/bin/envzPATH=/usr/sbin:/sbin:%s�PATHZswapz-l)�stdoutrz'swap -l' failed (retcode=%s)�
rNzno swap device(s) configuredri)r?���)�cextZswap_mem�
subprocess�Popenr@�environ�PIPE�communicater�decoder8rE�encoding�
returncode�RuntimeError�strip�split�intrrZsswaprB)
ZsinZsout�prE�stderr�linesr.r1�line�t�fr0r/r:r:r;�swap_memory�s,


r[cCstj�}tdd�t|�D��S)z-Return system-wide CPU times as a named tuplecSsg|]}t|��qSr:)�sum)�.0�xr:r:r;�
<listcomp>�szcpu_times.<locals>.<listcomp>)rH�
per_cpu_timesr'�zip)�retr:r:r;�	cpu_times�srccCstj�}dd�|D�S)z5Return system per-CPU times as a list of named tuplescSsg|]}t|��qSr:)r')r]r^r:r:r;r_�sz!per_cpu_times.<locals>.<listcomp>)rHr`)rbr:r:r;r`�sr`cCs$y
tjd�Stk
rdSXdS)z0Return the number of logical CPUs in the system.�SC_NPROCESSORS_ONLNN)r@rA�
ValueErrorr:r:r:r;�cpu_count_logical�s
rfcCstj�S)z1Return the number of physical CPUs in the system.)rHZcpu_count_physr:r:r:r;�cpu_count_physical�srgcCs$tj�\}}}}d}tj||||�S)z*Return various CPU stats as a named tuple.r)rH�	cpu_statsrZ	scpustats)Zctx_switchesZ
interruptsZsyscallsZtrapsZsoft_interruptsr:r:r;rh�s
rhFc	Cs`g}tj�}xN|D]F}|\}}}}|dkr.d}|s>t|�js>qtj||||�}|j|�qW|S)zReturn system disk partitions.Znone�)rH�disk_partitions�
disk_usager.rZ	sdiskpart�append)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZoptsZntupler:r:r;rj�s

rjc	Cstjj�}|dkr|jdd�||krFtd|djdd�|D��f��tj|\}}tj|�}t�}x�|D]�}|\}}	}
}}}
}|	|kr�qj|
|kr�qj|	t	t
fkr�|r�tj|�}|r�tj|�}t|
}
t
|	�}	t|
�}
|d	kr�tj||	|
|||
|�}ntj||	|
|||
�}|j|�qjWt|�S)
z�Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    Only INET sockets are returned (UNIX are not).
    r�unixrz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr:)�repr)r]r^r:r:r;r_�sz#net_connections.<locals>.<listcomp>���rr)rZ	conn_tmap�copy�popre�joinrH�net_connections�setrr	�addr�TCP_STATUSESrr
Zsconn�pconn�add�list)�kind�_pidZcmapZfamilies�types�rawlistrb�item�fdZfamZtype_ZladdrZraddrr%�pid�ntr:r:r;rv�s8




rvcCsVtj�}xH|j�D]<\}}|\}}}}ttd�r:tj|�}tj||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)rH�net_if_stats�items�hasattrrr�Z	snicstats)rb�namer�ZisupZduplexZspeedZmtur:r:r;r�s

r�cCstj�S)z:The system boot time expressed in seconds since the epoch.)rH�	boot_timer:r:r:r;r�)sr�cCs`g}tj�}d}xJ|D]B}|\}}}}}}	|s0q||kr<d}tj|||||	�}
|j|
�qW|S)z:Return currently connected users as a list of namedtuples.�:0.0�:0�	localhost)r�r�)rH�usersrZsuserrl)rnr�r�r�r(�ttyZhostnameZtstampZuser_processr�r�r:r:r;r�.s
r�cCsdd�tjtt���D�S)z7Returns a list of PIDs currently running on the system.cSsg|]}|j�rt|��qSr:)�isdigitrT)r]r^r:r:r;r_Hszpids.<locals>.<listcomp>)r@�listdirrr<r:r:r:r;�pidsFsr�cCs
tj|�S)z&Check for the existence of a unix pid.)r�
pid_exists)r�r:r:r;r�Ksr�cs�fdd�}|S)z�Call callable into a try/except clause and translate ENOENT,
    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
    cs�y�|f|�|�Stk
r�}z�|jdkrHdt�krFt|j|j��n�|jtjtjfkr�t|j�stt	|j|j��nt
|j|j|j��|jtjtj
fkr�t|j|j���WYdd}~XnXdS)Nr)�EnvironmentErrorr�r�r�_name�errno�ENOENT�ESRCHr�rr�_ppidZEPERMZEACCES)�self�args�kwargs�err)�funr:r;�wrapperUs


z wrap_exceptions.<locals>.wrapperr:)r�r�r:)r�r;�wrap_exceptionsPsr�c@s�eZdZdZddddgZdd�Zdd	�Zd
d�Zedd
��Z	edd��Z
edd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zedd��Zedd��Zed d!��Zed"d#��Zed$d%��Zed&d'��Zed(d)��Zed*d+��Zed,d-��Zed.d/��Zed0d1��ZeZed2d3��Zed4d5��Zed6d7��Z d8d9�Z!edId;d<��Z"e#d=d>�Z$e#d=d?�Z%ed@dA��Z&edBdC��Z'edDdE��Z(edJdGdH��Z)dFS)K�Processz1Wrapper class around underlying C implementation.r�r�r��_procfs_pathcCs||_d|_d|_t�|_dS)N)r�r�r�r<r�)r�r�r:r:r;�__init__qszProcess.__init__cCs"|jj�|jj�|jj�dS)N)�_proc_name_and_argsZcache_activate�_proc_basic_info�
_proc_cred)r�r:r:r;�
oneshot_enterws

zProcess.oneshot_entercCs"|jj�|jj�|jj�dS)N)r�Zcache_deactivater�r�)r�r:r:r;�oneshot_exit|s

zProcess.oneshot_exitcCstj|j|j�S)N)rHZproc_name_and_argsr�r�)r�r:r:r;r��szProcess._proc_name_and_argscCs(tj|j|j�}t|�tt�ks$t�|S)N)rHZproc_basic_infor�r��len�
proc_info_map�AssertionError)r�rbr:r:r;r��szProcess._proc_basic_infocCstj|j|j�S)N)rHZ	proc_credr�r�)r�r:r:r;r��szProcess._proc_credcCs|j�dS)Nr)r�)r�r:r:r;r��szProcess.namecCs8ytjd|j|jf�Stk
r*YnX|j�dS)Nz%s/%s/path/a.outri)r@�readlinkr�r��OSError�cmdline)r�r:r:r;�exe�szProcess.execCs|j�djd�S)Nrr7)r�rS)r�r:r:r;r��szProcess.cmdlinecCstj|j|j�S)N)rHZproc_environr�r�)r�r:r:r;rK�szProcess.environcCs|j�tdS)Nr")r�r�)r�r:r:r;r"�szProcess.create_timecCs|j�tdS)Nr$)r�r�)r�r:r:r;r$�szProcess.num_threadscCsbytj|j�Stk
r\}z4|jtjtjdfkrJt|j�rJt|j|j	���WYdd}~XnXdS)N�0)
�
cext_posix�getpriorityr�r�r�r�r�r�rr�)r�r�r:r:r;�nice_get�s
zProcess.nice_getcCs&|jdkrt|j|j��tj|j|�S)Nrr)rr)r�rr�r��setpriority)r��valuer:r:r;�nice_set�s
zProcess.nice_setcCs|j�td|_|jS)Nr)r�r�r�)r�r:r:r;r�szProcess.ppidcCs"|j�\}}}}}}tj|||�S)N)r�r�puids)r��real�	effective�saved�_r:r:r;�uids�szProcess.uidscCs"|j�\}}}}}}tj|||�S)N)r�rr�)r�r�r�r�r�r:r:r;�gids�szProcess.gidscCs\ytj|j|j�}Wn<tk
rP}z |jtjkr>tr>d}n�WYdd}~XnXtj	|�S)N�)r�r�r�r�)
rHZproc_cpu_timesr�r�r�r��	EOVERFLOW�	IS_64_BITrr*)r��timesr�r:r:r;rc�szProcess.cpu_timescCstj|j|j�S)N)rHZproc_cpu_numr�r�)r�r:r:r;�cpu_num�szProcess.cpu_numcCs�|j}d}t|j�td�}|tjkr�xZd
D]R}ytjd||j|f�St	k
r~}z|j
t
jkrld}w.�WYdd}~Xq.Xq.W|r�tjd	||jf�dS)NFr&rrr�z
%s/%d/path/%dTz%s/%s)rrrr�)
r�r�r�r�rHZPRNODEVr@r�r�r�r�r��stat)r��procfs_path�
hit_enoentr�r^r�r:r:r;�terminal�s 

zProcess.terminalcCsh|j}ytjd||jf�Stk
rb}z,|jtjkrPtjd||jf�dS�WYdd}~XnXdS)Nz%s/%s/path/cwdz%s/%s)r�r@r�r�r�r�r�r�)r�r�r�r:r:r;�cwdszProcess.cwdcCs2|j�}|tdd}|tdd}t||�S)Nr ir!)r�r�r2)r�rbr r!r:r:r;�memory_infoszProcess.memory_infocCs|j�td}tj|d�S)Nr%�?)r�r��
PROC_STATUSES�get)r��coder:r:r;r%$szProcess.statusc
Cs�|j}g}tjd||jf�}d}x�|D]�}t|�}ytj|j||�\}}WnJtk
r�}z.|jtj	krrt
rrw(|jtjkr�d}w(�WYdd}~Xq(Xtj
|||�}	|j|	�q(W|r�tjd||jf�|S)Nz	%s/%d/lwpFTz%s/%s)r�r@r�r�rTrHZquery_process_threadr�r�r�r�r�rZpthreadrlr�)
r�r�rbZtidsr��tid�utimeZstimer�r�r:r:r;�threads*s*
zProcess.threadsc	Cs�g}d}|j}d||jf}x�tjd||jf�D]�}tjj||�}tjj|�r2ytj|�}Wn6tk
r�}z|j	t	j
kr�d}w2�WYdd}~Xq2Xt|�r2|jt
j|t|���q2W|r�tjd||jf�|S)NFz
%s/%d/pathz%s/%d/fdTz%s/%s)r�r�r@r�r4ru�islinkr�r�r�r�r
rlrZ	popenfilerTr�)	r�rnr�r�Zpathdirr�r4�filer�r:r:r;�
open_filesLs&zProcess.open_filesccs,d|}tj|dtjtjd�}|j�\}}trDdd�||fD�\}}|jdkr�d|j�krht|j|j	��d|j�kr�t
|j|j	��td	||f��|jd
�dd�}x�t
|�D]v\}}|j�}|jd
�r�|jdd�d}	||dj�}
|
dkr�tj}
n|
dk�r
tj}
nd}
dtj|
|	dtjfVq�WdS)z<Get UNIX sockets used by process by parsing 'pfiles' output.z	pfiles %sT)�shellrErVcSsg|]}|jtjj��qSr:)rNr8rErO)r]r^r:r:r;r_nsz-Process._get_unix_sockets.<locals>.<listcomp>rzpermission deniedzno such processz%r command error
%srFrNzsockname: AF_UNIXr7�SOCK_STREAM�
SOCK_DGRAMrrirrrr)rIrJrLrMrrP�lowerrr�r�rrQrS�	enumerate�lstrip�
startswithrR�socketr�r�ZAF_UNIXr�	CONN_NONE)r�r��cmdrUrErVrW�irXr4�typer:r:r;�_get_unix_socketses2



zProcess._get_unix_sockets�inetcCsPt||jd�}|s(tjd|j|jf�|dkrL|jdd�|j|j�D��|S)N)r~z%s/%srmrpcSsg|]}tj|��qSr:)rrz)r]Zconnr:r:r;r_�sz'Process.connections.<locals>.<listcomp>)rmrp)rvr�r@r�r��extendr�)r�r}rbr:r:r;�connections�s
zProcess.connectionsZmmapzpath rss anon lockedzaddr perms path rss anon lockedc$Cs.dd�}|j}g}ytj|j|�}Wn:tk
r^}z|jtjkrLtrLgS�WYdd}~XnXd}x�|D]�}|\}}	}
}}}
}|||	�}|jd�s�yt	j
d||j|f�}WnFtk
r�}z*|jtjkr�d||j|f}d}n�WYdd}~XnX|j||
|||
|f�qjW|�r*t	j
d||jf�|S)NcSs0dt|�dd�jd�t|�dd�jd�fS)Nz%s-%sr�L)�hexrR)�start�endr:r:r;�toaddr�sz#Process.memory_maps.<locals>.toaddrF�[z
%s/%s/path/%sTz%s/%s)r�rHZproc_memory_mapsr�r�r�r�r�r�r@r�r�rlr�)r�r�r�rnr�r�r�r�rxZaddrsizeZpermr�r Zanonr5r:r:r;�memory_maps�s4


zProcess.memory_mapscCsttjd|j|jf��S)Nz%s/%s/fd)r�r@r�r�r�)r�r:r:r;�num_fds�szProcess.num_fdscCstjtj|j|j��S)N)rZpctxswrHZproc_num_ctx_switchesr�r�)r�r:r:r;�num_ctx_switches�szProcess.num_ctx_switchesNcCstj|j||j�S)N)rZwait_pidr�r�)r�Ztimeoutr:r:r;�wait�szProcess.wait)r�)N)*�__name__�
__module__�__qualname__�__doc__�	__slots__r�r�r�rr�r�r�r�r�r�r�rKr"r$r�r�rr�r�rcr�r�r�r�Zmemory_full_infor%r�r�r�r�rZnt_mmap_groupedZnt_mmap_extr�r�r�r�r:r:r:r;r�lsL

" 

0r�l)Frr)rr)or�r�r@r�rIr8�collectionsrrrirrrr�rrHr	r
rrr
rZ_compatrr�_exceptionsrrrZ__extra__all__rArBZAF_LINK�maxsizer�rrZSSLEEPZSTATUS_SLEEPINGZSRUNZSTATUS_RUNNINGZSZOMBZ
STATUS_ZOMBIEZSSTOPZSTATUS_STOPPEDZSIDLZSTATUS_IDLEZSONPROCZSWAITZSTATUS_WAITINGr�ZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZ
TCPS_SYN_RCVDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGZPSUTIL_CONN_NONEr�Z	TCPS_IDLEZ
TCPS_BOUNDry�dictr�r'r*r-r2Zpfullmemr3ru�_fieldsr6r<rCr[rcr`rfrgrhZdisk_io_countersrkrjZnet_io_countersZnet_if_addrsrvr�r�r�r�r�r��objectr�r:r:r:r;�<module>s�



	
&	


$__pycache__/_pswindows.cpython-36.pyc000064400000062630150466730530013616 0ustar003

��JZa��(@s�dZddlZddlZddlZddlZddlZddlmZddlm	Z	yddlm
ZWnlek
r�Z
zPee
�j�jd�r�ej�ddkr�d	Zed
7Zed7Zed7Zee��n�WYddZ
[
XnXdd
l	mZddl	mZddl	mZddl	mZddl	mZddl	mZddl	mZddl	mZddl	mZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddl#m$Z$ddl#m%Z%ddl#m&Z&ddl
m'Z'ddl
m(Z(dd l
m)Z)dd!l
m*Z*dd"l
m+Z+dd#l
m,Z,ej-d�k�r�ddl.Z.ndZ.d&d'd(d)d*d+d,d-d.d/g
Z/d0Z0d1Z1e2ej3ej4ej5g�Z6e2ej7ej8g�Z9e.dk�rDd�Z:ne.j;d2d/d�i�Z<e<j:Z:ej=e	j>ej?e	j@ejAe	jBejCe	jDejEe	jFejGe	jHejIe	jJejKe	jLejMe	jNejOe	jPejQe	jRejSe0ejTe	jUi
ZVe.dk	�r�Gd3d4�d4e.j;�ZWeX�jYeWjZ�e[ddd5d$d%d6dd7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdF�Z\edGdHdIdJdKdLg�Z]edMdNdOdPdQdRg�Z^edSdTdUdVdWdXdYdZd[d\d]d^d_g�Z_ed`e_j`d��ZaedbdcdTg�Zbedddedfjcebj`��Zdedgdhdidjdkdldmg�Zeedndo�dpdq��Zfdrds�Zgdtdu�Zhdvdw�ZiejjZjdxdy�Zkdzd{�Zld|d}�Zmd~d�Znd�d��Zod�d��Zpd�d��Zqd�d��Zrd�d�d��Zsd�d��Ztd�d��Zud�d��Zvd�d��Zwdaxd�d��Zyd�d��Zzd�d&�Z{d�d'�Z|Gd�d��d�e}�Z~ejZej�Z�ej�Z�d�d��Z�Gd�d��d�e}�Z�dS)�z Windows platform implementation.�N)�
namedtuple�)�_common)�_psutil_windowszdll load failed�z3this Windows version is too old (< Windows Vista); z:psutil 3.4.2 is the latest version which supports Windows z92000, XP and 2003 server; it may be possible that psutil z)will work if compiled from sources though)�	conn_tmap)�ENCODING)�
ENCODING_ERRS)�
isfile_strict)�memoize_when_activated)�parse_environ_block)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�long)�	lru_cache)�PY3)�unicode)�xrange)�AccessDenied)�
NoSuchProcess)�TimeoutExpired)�ABOVE_NORMAL_PRIORITY_CLASS)�BELOW_NORMAL_PRIORITY_CLASS)�HIGH_PRIORITY_CLASS)�IDLE_PRIORITY_CLASS)�NORMAL_PRIORITY_CLASS)�REALTIME_PRIORITY_CLASS���win_service_iter�win_service_getrrrrrr�CONN_DELETE_TCB�AF_LINKZ
DELETE_TCBi�
AddressFamilyc@s$eZdZeZeZeZeZeZeZdS)�PriorityN)	�__name__�
__module__�__qualname__rrrrrr�r)r)�"/usr/lib64/python3.6/_pswindows.pyr%osr%�����	�
���
��������)�num_handles�ctx_switches�	user_time�kernel_time�create_time�num_threads�	io_rcount�	io_wcount�	io_rbytes�	io_wbytes�io_count_others�io_bytes_others�num_page_faults�	peak_wset�wset�peak_paged_pool�
paged_pool�peak_non_paged_pool�non_paged_pool�pagefile�
peak_pagefile�mem_private�	scputimes�user�system�idle�	interrupt�dpc�svmem�totalZ	available�percent�used�free�pmem�rss�vmsrHrIrJrKrLZpeak_nonpaged_poolZ
nonpaged_poolrOrPZprivate�pfullmem�uss�
pmmap_grouped�path�	pmmap_extzaddr perms � �pioZ
read_countZwrite_countZ
read_bytesZwrite_bytes�other_countZother_bytesi)�maxsizecCs<dj|jd�dd��}tj|�}tjj||t|�d��S)z�Convert paths using native DOS format like:
        "\Device\HarddiskVolume1\Windows\systemew\file.txt"
    into:
        "C:\Windows\systemew\file.txt"
    �\Nr)�join�split�cextZwin32_QueryDosDevice�osrc�len)�sZrawdriveZdriveletterr)r)r*�convert_dos_path�s
rpcCs(tr|St|t�r|S|jttd�SdS)zmEncode a unicode string to a byte string by using the default fs
    encoding + "replace" error handler.
    )�errorsN)r�
isinstance�str�encoderr	)ror)r)r*�
py2_strencode�s

rucCsNtj�}|\}}}}}}|}|}|}	||}
t|||dd�}t||||
|	�S)z&System virtual memory as a namedtuple.r)�_round)rl�virtual_memrrX)�memZtotphysZ	availphysZtotpagefZ
availpagefZtotvirtZfreevirtrYZavailr\r[rZr)r)r*�virtual_memory�srycCsBtj�}|d}|d}||}t||dd�}tj||||dd�S)z=Swap system memory as a (total, used, free, sin, sout) tuple.r+rr)rvr)rlrwrrZsswap)rxrYr\r[rZr)r)r*�swap_memory�srzcCsPtrt|t�r|jtdd�}tj|�\}}||}t||dd�}tj	||||�S)z'Return disk usage associated with path.�strict)rqr)rv)
rrr�bytes�decoderrl�
disk_usagerrZ
sdiskusage)rcrYr\r[rZr)r)r*r~�sr~cCstj|�}dd�|D�S)zReturn disk partitions.cSsg|]}tj|��qSr))rZ	sdiskpart)�.0�xr)r)r*�
<listcomp>sz#disk_partitions.<locals>.<listcomp>)rl�disk_partitions)�all�rawlistr)r)r*r��s
r�cCs<tj�\}}}tdd�ttj��D��}t||||j|j�S)z)Return system CPU times as a named tuple.cSsg|]}t|��qSr))�sum)r�nr)r)r*r�szcpu_times.<locals>.<listcomp>)rl�	cpu_timesrR�zip�
per_cpu_timesrVrW)rSrTrUZ
percpu_summedr)r)r*r�	sr�cCs>g}x4tj�D](\}}}}}t|||||�}|j|�qW|S)z6Return system per-CPU times as a list of named tuples.)rlr�rR�append)�retrSrTrUrVrW�itemr)r)r*r�s
r�cCstj�S)z0Return the number of logical CPUs in the system.)rl�cpu_count_logicalr)r)r)r*r�sr�cCstj�S)z1Return the number of physical CPUs in the system.)rlZcpu_count_physr)r)r)r*�cpu_count_physical"sr�cCs$tj�\}}}}d}tj||||�S)zReturn CPU statistics.r)rl�	cpu_statsrZ	scpustats)r=Z
interruptsZdpcsZsyscallsZsoft_interruptsr)r)r*r�'s
r�cCs(tj�\}}d}tjt|�|t|��gS)zMReturn CPU frequency.
    On Windows per-cpu frequency is not supported.
    g)rl�cpu_freqrZscpufreq�float)ZcurrZmax_Zmin_r)r)r*r�/sr�c	Cs�|tkr(td|djdd�tD��f��t|\}}tj|||�}t�}x�|D]�}|\}}}	}
}}}
|
rrtj|
�}
|r�tj|�}t|}t	|�}t
|	�}	|dkr�tj|||	|
|||
�}ntj|||	|
||�}|j
|�qNWt|�S)z�Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    z+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr))�repr)rr�r)r)r*r�Csz#net_connections.<locals>.<listcomp>r���)r�
ValueErrorrjrl�net_connections�setr�addr�TCP_STATUSESr
rZsconnZpconn�add�list)�kind�_pidZfamilies�typesr�r�r��fdZfam�typeZladdrZraddr�status�pid�ntr)r)r*r�=s(


r�cCs|i}tj�}xj|j�D]^\}}ts@t|t�s8tt|���t|�}|\}}}}t	t
d�r`t
j|�}t
j||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)
rl�net_if_stats�itemsrrrr�AssertionErrorr�ru�hasattrrr�Z	snicstats)r�Zrawdict�namer�ZisupZduplexZspeedZmtur)r)r*r�Xs

r�cCstj�}tdd�|j�D��S)zsReturn network I/O statistics for every network interface
    installed on the system as a dict of raw tuples.
    cSsg|]\}}t|�|f�qSr))ru)r�k�vr)r)r*r�lsz#net_io_counters.<locals>.<listcomp>)rl�net_io_counters�dictr�)r�r)r)r*r�gsr�cCs<g}x2tj�D]&}t|�}t|d�|d<|j|�qW|S)z,Return the addresses associated to each NIC.r)rl�net_if_addrsr�rur�)r�r�r)r)r*r�osr�cCsdtj�\}}}}|dk}t|d@�}t|d@�}|r8dS|s@|rHtj}n|dkrVtj}tj|||�S)zReturn battery information.r�r.Nr�)rl�sensors_battery�boolrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)Z
acline_status�flagsrZZsecsleftZ
power_pluggedZ
no_batteryZchargingr)r)r*r�~sr�cCs,ttj��}t|t�dkr tS|a|SdS)z:The system boot time expressed in seconds since the epoch.rN)r�rl�	boot_time�abs�_last_btime)r�r)r)r*r��s
r�cCsLg}tj�}x:|D]2}|\}}}t|�}tj|d||d�}|j|�qW|S)z:Return currently connected users as a list of namedtuples.N)rl�usersrurZsuserr�)�retlistr�r�rSZhostnameZtstampr�r)r)r*r��s

r�ccs.x(tj�D]\}}tt|�t|��Vq
WdS)z*Yields a list of WindowsService instances.N)rlZwinservice_enumerate�WindowsServiceru)r��display_namer)r)r*r �scCst|d�}|j�d|_|S)zBOpen a Windows service and return it as a WindowsService instance.Nr�)r��
_query_config�
_display_name)r�Zservicer)r)r*r!�s
c@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
ejdd��Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$S)%r�z(Represents an installed Windows service.cCs||_||_dS)N)�_namer�)�selfr�r�r)r)r*�__init__�szWindowsService.__init__cCs d|j|jf}d|jj|fS)Nz(name=%r, display_name=%r)z%s%s)r�r��	__class__r&)r�Zdetailsr)r)r*�__str__�szWindowsService.__str__cCsd|j�t|�fS)Nz
<%s at %s>)r��id)r�r)r)r*�__repr__�szWindowsService.__repr__cCst|t�stS|j|jkS)N)rrr��NotImplementedr�)r��otherr)r)r*�__eq__�s
zWindowsService.__eq__cCs
||kS)Nr))r�r�r)r)r*�__ne__�szWindowsService.__ne__c
CsH|j��tj|j�\}}}}WdQRXtt|�t|�t|�t|�d�S)N)r��binpath�username�
start_type)�_wrap_exceptionsrlZwinservice_query_configr�r�ru)r�r�r�r�r�r)r)r*r��s
zWindowsService._query_configcCs<|j��tj|j�\}}WdQRX|dkr0d}t||d�S)Nr)r�r�)r�rlZwinservice_query_statusr�r�)r�r�r�r)r)r*�
_query_status�s

zWindowsService._query_statusccs�y
dVWnrtk
r|}zV|jtkr>td|jd|jd��n.|jtksR|jtkrjtd|jd|jd��n�WYdd}~XnXdS)z{Ctx manager which translates bare OSError and WindowsError
        exceptions into NoSuchProcess and AccessDenied.
        Nz2service %r is not querable (not enough privileges))r�r��msgzservice %r does not exist))ZWindowsError�errno�ACCESS_DENIED_ERRSETrr��NO_SUCH_SERVICE_ERRSETZwinerrorr)r��errr)r)r*r��s



zWindowsService._wrap_exceptionscCs|jS)z�The service name. This string is how a service is referenced
        and can be passed to win_service_get() to get a new
        WindowsService instance.
        )r�)r�r)r)r*r�szWindowsService.namecCs|jS)z_The service display name. The value is cached when this class
        is instantiated.
        )r�)r�r)r)r*r�szWindowsService.display_namecCs|j�dS)zwThe fully qualified path to the service binary/exe file as
        a string, including command line arguments.
        r�)r�)r�r)r)r*r�szWindowsService.binpathcCs|j�dS)z,The name of the user that owns this service.r�)r�)r�r)r)r*r�szWindowsService.usernamecCs|j�dS)zRA string which can either be "automatic", "manual" or
        "disabled".
        r�)r�)r�r)r)r*r�szWindowsService.start_typecCs|j�dS)zzThe process PID, if any, else None. This can be passed
        to Process class to control the service's process.
        r�)r�)r�r)r)r*r�'szWindowsService.pidcCs|j�dS)zService status as a string.r�)r�)r�r)r)r*r�-szWindowsService.statuscCsttj|j���S)zService long description.)rurlZwinservice_query_descrr�)r�r)r)r*�description1szWindowsService.descriptioncCs>|j�}|j|j��|j�|d<|j�|d<|j�|d<|S)zUUtility method retrieving all the information above as a
        dictionary.
        r�r�r�)r��updater�r�r�r�)r��dr)r)r*�as_dict7szWindowsService.as_dictN)r&r'r(�__doc__r�r�r�r�r�r�r��
contextlib�contextmanagerr�r�r�r�r�r�r�r�r�r�r)r)r)r*r��s$r�cstj���fdd��}|S)zqDecorator which translates bare OSError and WindowsError
    exceptions into NoSuchProcess and AccessDenied.
    csly�|f|�|�Stk
rf}z:|jtkr:t|j|j��|jtjkrTt|j|j���WYdd}~XnXdS)N)�OSErrorr�r�rr�r��ESRCHr)r��args�kwargsr�)�funr)r*�wrapperxs
z wrap_exceptions.<locals>.wrapper)�	functools�wraps)r�r�r))r�r*�wrap_exceptionsts
r�c@s�eZdZdZdddgZdd�Zdd�Zd	d
�Zedd��Z	e
d
d��Ze
dd��Ze
dd��Z
e
dd��Zdd�Zdd�Ze
dd��Ze
dd��Zdd�Ze
dd ��Ze
d!d"��Ze
dPd$d%��Ze
d&d'��Ze
d(d)��Ze
d*d+��Ze
d,d-��Ze
d.d/��Ze
d0d1��Ze
d2d3��Ze
d4d5��Ze
d6d7��Ze
dQd9d:��Z e
d;d<��Z!e
d=d>��Z"e#e$d?��rve
d@dA��Z%e
dBdC��Z&e
dDdE��Z'e
dFdG��Z(e
dHdI��Z)e
dJdK��Z*e
dLdM��Z+e
dNdO��Z,d#S)R�Processz1Wrapper class around underlying C implementation.r�r��_ppidcCs||_d|_d|_dS)N)r�r�r�)r�r�r)r)r*r��szProcess.__init__cCs|jj�dS)N)�oneshot_infoZcache_activate)r�r)r)r*�
oneshot_enter�szProcess.oneshot_entercCs|jj�dS)N)r�Zcache_deactivate)r�r)r)r*�oneshot_exit�szProcess.oneshot_exitcCs$tj|j�}t|�tt�ks t�|S)zOReturn multiple information about this process as a
        raw tuple.
        )rlZ	proc_infor�rn�	pinfo_mapr�)r�r�r)r)r*r��szProcess.oneshot_infocCsV|jdkrdS|jdkrdSyttjj|j���Stk
rPttj|j��SXdS)zbReturn process name, which on Windows is always the final
        part of the executable.
        rzSystem Idle ProcessrZSystemN)	r�rurmrc�basename�exerrlZ	proc_name)r�r)r)r*r��s

zProcess.namecCs,|jdkrt|j|j��tttj|j���S)Nrr)rr)r�rr�rurprlZproc_exe)r�r)r)r*r��s
zProcess.execCs&tj|j�}tr|Sdd�|D�SdS)NcSsg|]}t|��qSr))ru)rror)r)r*r��sz#Process.cmdline.<locals>.<listcomp>)rlZproc_cmdliner�r)r�r�r)r)r*�cmdline�szProcess.cmdlinecCs8tj|j�}|r,tr,t|t�s,tt|���tt	|��S)N)
rlZproc_environr�rrrrr�r�rru)r�Zustrr)r)r*�environ�s
zProcess.environcCs4yt�|jStk
r.t|j|j��YnXdS)N)�ppid_mapr��KeyErrorrr�)r�r)r)r*�ppid�szProcess.ppidcCs�ytj|j�Stk
r�}z�|jtkr�|j�}|td|td|td|td|td|td|td|td|td	|td
f
S�WYdd}~XnXdS)NrHrIrJrKrLrMrNrOrPrQ)rlZproc_memory_infor�r�r�r�r�r�)r�r��infor)r)r*�_get_raw_meminfo�s 









zProcess._get_raw_meminfocCs(|j�}|d}|d}t||f|�S)Nr+r-)r�r])r��tr^r_r)r)r*�memory_info�szProcess.memory_infocCs"|j�}tj|j�}t||f�S)N)r�rlZproc_memory_ussr�r`)r�Z	basic_memrar)r)r*�memory_full_info�szProcess.memory_full_infoccs�ytj|j�}WnVtk
rf}z:|jtkr:t|j|j��|jtjkrTt	|j|j���WYdd}~XnXXxT|D]L\}}}}t
|�}ts�t|t
�s�tt|���t|�}t|�}||||fVqnWdS)N)rlZproc_memory_mapsr�r�r�r�rr�r�rrprrrrr�r�ru�hex)r��rawr�r�Zpermrcr^r)r)r*�memory_maps�s
zProcess.memory_mapscCstj|j�S)N)rlZ	proc_killr�)r�r)r)r*�killszProcess.killcCstj|j|�dS)N)rmr�r�)r�Zsigr)r)r*�send_signalszProcess.send_signalNcCsr|dkrtj}nt|d�}xPtj|j|�}|tkrDt||j|j��t|j�rj|dkrZqnt||j|j��|SdS)Ni�)	rlZINFINITE�intZ	proc_waitr��WAIT_TIMEOUTrr��
pid_exists)r�ZtimeoutZcext_timeoutr�r)r)r*�waits
zProcess.waitcCs2|jdkrdStj|j�\}}t|�dt|�S)NrrzNT AUTHORITY\SYSTEMri)rr)r�rlZ
proc_usernameru)r�ZdomainrSr)r)r*r�(s
zProcess.usernamecCs`|jdkrt�Sytj|j�Stk
rZ}z"|jtkrH|j�tdS�WYdd}~XnXdS)Nrrr@)rr)	r�r�rlZproc_create_timer�r�r�r�r�)r�r�r)r)r*r@/s

zProcess.create_timecCs|j�tdS)NrA)r�r�)r�r)r)r*rA;szProcess.num_threadscCs@tj|j�}g}x*|D]"\}}}tj|||�}|j|�qW|S)N)rlZproc_threadsr�rZpthreadr�)r�r�r�Z	thread_id�utimeZstime�ntupler)r)r*�threads?szProcess.threadscCsvytj|j�\}}WnPtk
rd}z4|jtkrR|j�}|td}|td}n�WYdd}~XnXtj	||dd�S)Nr>r?g)
rlZproc_cpu_timesr�r�r�r�r�r�rZ	pcputimes)r�rSrTr�r�r)r)r*r�Hs
zProcess.cpu_timescCstj|j�S)N)rlZproc_suspendr�)r�r)r)r*�suspendVszProcess.suspendcCstj|j�S)N)rlZproc_resumer�)r�r)r)r*�resumeZszProcess.resumecCs4|jdkrt|j|j��tj|j�}ttjj|��S)Nrr)rr)	r�rr�rlZproc_cwdrurmrc�normpath)r�rcr)r)r*�cwd^s
zProcess.cwdcCsh|jdkrgSt�}tj|j�}x>|D]6}t|�}t|�r&tsFt|�}tj	|d�}|j
|�q&Wt|�S)Nrrr)rrr�)r�r�rlZproc_open_filesrpr
rrurZ	popenfiler�r�)r�r�Zraw_file_namesZ_filer�r)r)r*�
open_filesgs

zProcess.open_files�inetcCst||jd�S)N)r�)r�r�)r�r�r)r)r*�connectionszszProcess.connectionscCs tj|j�}tdk	rt|�}|S)N)rlZproc_priority_getr��enumr%)r��valuer)r)r*�nice_get~szProcess.nice_getcCstj|j|�S)N)rlZproc_priority_setr�)r�rr)r)r*�nice_set�szProcess.nice_set�proc_io_priority_getcCstj|j�S)N)rlr	r�)r�r)r)r*�
ionice_get�szProcess.ionice_getcCs.|rtd��|dkr td|��tj|j|�S)Nz<set_proc_ionice() on Windows takes only 1 argument (2 given)r+rrz9value must be 2 (normal), 1 (low) or 0 (very low); got %r)r+rr)�	TypeErrorr�rlZproc_io_priority_setr�)r�r�_r)r)r*�
ionice_set�szProcess.ionice_setcCs�ytj|j�}Wnxtk
r�}z\|jtkrv|j�}|td|td|td|td|td|tdf}n�WYdd}~XnXt|�S)NrBrCrDrErFrG)	rlZproc_io_countersr�r�r�r�r�r�rf)r�r�r�r�r)r)r*�io_counters�s





zProcess.io_counterscCs tj|j�}|rtjStjSdS)N)rlZproc_is_suspendedr�rZSTATUS_STOPPEDZSTATUS_RUNNING)r�Z	suspendedr)r)r*r��szProcess.statuscCsdd�}tj|j�}||�S)Ncs�fdd�td�D�S)Ncsg|]}d|>�@r|�qS)rr))r�i)r�r)r*r��szBProcess.cpu_affinity_get.<locals>.from_bitmask.<locals>.<listcomp>�@)r)r�r))r�r*�from_bitmask�sz.Process.cpu_affinity_get.<locals>.from_bitmask)rlZproc_cpu_affinity_getr�)r�r�bitmaskr)r)r*�cpu_affinity_get�szProcess.cpu_affinity_getcCsrdd�}tttt����}x<|D]4}||kr t|ttf�sHtd|��q td|��q W||�}t	j
|j|�dS)NcSs2|std|��d}x|D]}|d|O}qW|S)Nzinvalid argument %rrr+)r�)�l�out�br)r)r*�
to_bitmask�s
z,Process.cpu_affinity_set.<locals>.to_bitmaskz&invalid CPU %r; an integer is requiredzinvalid CPU %r)r��rangernr�rrr�rrr�rlZproc_cpu_affinity_setr�)r�rrZallcpusZcpurr)r)r*�cpu_affinity_set�s
zProcess.cpu_affinity_setcCsPytj|j�Stk
rJ}z"|jtkr8|j�tdS�WYdd}~XnXdS)Nr<)rlZproc_num_handlesr�r�r�r�r�r�)r�r�r)r)r*r<�s
zProcess.num_handlescCs|j�td}tj|d�S)Nr=r)r�r�rZpctxsw)r�r=r)r)r*�num_ctx_switches�szProcess.num_ctx_switches)N)r)-r&r'r(r��	__slots__r�r�r�rr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r@rAr�r�r�r�rrrrrr�rlr
r
rr�rrr<rr)r)r)r*r��sR
	
		
	r�)rrr�r�)rar�)r�)�r�r�r�r�rm�sys�collectionsr�rrrl�ImportErrorr�rs�lower�
startswithZgetwindowsversionr��RuntimeErrorrrr	r
rrr
rrZ_compatrrrrr�_exceptionsrrrrrrrrr�version_inforZ__extra__all__r"r��	frozensetZEPERMZEACCESZERROR_ACCESS_DENIEDr�ZERROR_INVALID_NAMEZERROR_SERVICE_DOES_NOT_EXISTr�r#�IntEnumr$ZMIB_TCP_STATE_ESTABZCONN_ESTABLISHEDZMIB_TCP_STATE_SYN_SENTZ
CONN_SYN_SENTZMIB_TCP_STATE_SYN_RCVDZ
CONN_SYN_RECVZMIB_TCP_STATE_FIN_WAIT1ZCONN_FIN_WAIT1ZMIB_TCP_STATE_FIN_WAIT2ZCONN_FIN_WAIT2ZMIB_TCP_STATE_TIME_WAITZCONN_TIME_WAITZMIB_TCP_STATE_CLOSEDZ
CONN_CLOSEZMIB_TCP_STATE_CLOSE_WAITZCONN_CLOSE_WAITZMIB_TCP_STATE_LAST_ACKZ
CONN_LAST_ACKZMIB_TCP_STATE_LISTENZCONN_LISTENZMIB_TCP_STATE_CLOSINGZCONN_CLOSINGZMIB_TCP_STATE_DELETE_TCBZPSUTIL_CONN_NONEZ	CONN_NONEr�r%�globalsr��__members__r�r�rRrXr]�_fieldsr`rbrjrdrfrpruryrzZdisk_io_countersr~r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r r!�objectr�Zpidsr�r�r�r�r)r)r)r*�<module>s 









	
*__pycache__/_pslinux.cpython-36.pyc000064400000131707150466730540013266 0ustar003

��JZb$�@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddl$m%Z%ddl$m&Z&ddl$m'Z'ddl$m(Z(ddl)m*Z*ddl)m+Z+ddl)m,Z,ej-d�k�r�ddl.Z.ndZ.d d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/gZ/d0Z0ej1j2d1ej3��Z4e5ed2�Z6e7�Z8e6�r2x(e9e�D]Z:e:j;d3��re/j<e:��qWej=d4�Z>ej=d5�Z?da@e(�rTd�nd6ZAejBd7kZCd8ZDe.dk�rxe
jEZFne.jGd9d:eHe
jE�i�ZIeIjFZFe.dk�r�dZJdZKd;ZLdZMn Gd<d=�d=e.jG�ZNeO�jPeNjQ�ejRejSejTejUejVejWejXejXejYejZd>�
Z[ej\ej]ej^ej_ej`ejaejbejcejdejeejfd?�Zged@dAdBdCdDdEdFdGdHdIdJg
�ZhedKdLdMdNdOdPdQdRdSdTg	�ZiedUdVdWdXdYdZg�Zjed[d\�Zked]ekjld��ZmedadVdbdcd_dddedfdgdhdid`g�Znedjdkdljoenjl��ZpedmdLdMdNdOdndog�Zqdpdq�Zrdrds�Zse(�rdtdu�Ztndvdu�Ztdwdx�Zudydz�Zvd{d|�Zwd}d~�Zxedd���Zye8d�fd�d��Zzyeyd��Wn0e{k
�r�e
j|�ed�d��d�d�d��a}YnXd�d��Z~d�d��Zd�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�ej1j2d���s�ej1j2d���r�d�d��Z�ej�Z�Gd�d��d�e{�Z�Gd�d��d��Z�e��Z�d�d�d��Z�d�d��Z�d�d��Z�ej�Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�Gd�d��d�e7�Z�dS)�zLinux platform implementation.�)�divisionN)�defaultdict)�
namedtuple�)�_common)�_psposix)�
_psutil_linux)�
_psutil_posix)�ENCODING)�
ENCODING_ERRS)�
isfile_strict)�memoize)�memoize_when_activated)�NIC_DUPLEX_FULL)�NIC_DUPLEX_HALF)�NIC_DUPLEX_UNKNOWN)�parse_environ_block)�path_exists_strict)�
supports_ipv6)�
usage_percent)�b)�
basestring)�long)�PY3)�AccessDenied)�
NoSuchProcess)�
ZombieProcess���PROCFS_PATH�IOPRIO_CLASS_NONE�IOPRIO_CLASS_RT�IOPRIO_CLASS_BE�IOPRIO_CLASS_IDLE�CONN_ESTABLISHED�
CONN_SYN_SENT�
CONN_SYN_RECV�CONN_FIN_WAIT1�CONN_FIN_WAIT2�CONN_TIME_WAIT�
CONN_CLOSE�CONN_CLOSE_WAIT�
CONN_LAST_ACK�CONN_LISTEN�CONN_CLOSINGz/sys/class/power_supplyz/proc/%s/smaps�
linux_prlimitZRLIM�
SC_CLK_TCK�SC_PAGE_SIZEi �littlei�
AddressFamily�AF_LINK�c@seZdZdZdZdZdZdS)�
IOPriorityrrr5rN)�__name__�
__module__�__qualname__r r!r"r#�r:r:� /usr/lib64/python3.6/_pslinux.pyr6jsr6)
�R�S�D�T�t�Z�X�x�K�W)Z01Z02Z03Z04Z05Z06Z07Z08Z09Z0AZ0B�svmem�total�	available�percent�used�free�active�inactive�buffers�cached�shared�sdiskioZ
read_countZwrite_countZ
read_bytesZwrite_bytesZ	read_timeZ
write_timeZread_merged_countZwrite_merged_count�	busy_time�	popenfile�path�fdZposition�mode�flags�pmemz"rss vms shared text lib data dirty�pfullmem�uss�pss�swap�
pmmap_grouped�rss�sizeZshared_cleanZshared_dirtyZ
private_cleanZ
private_dirtyZ
referencedZ	anonymous�	pmmap_extzaddr perms � �pioZ
read_charsZwrite_charscKst|df|�S)N�rb)�open)�fname�kwargsr:r:r;�open_binary�srgcKs*tr|jdt�|jdt�t|df|�S)z�On Python 3 opens a file in text mode by using fs encoding and
    a proper en/decoding errors handler.
    On Python 2 this is just an alias for open(name, 'rt').
    �encoding�errors�rt)r�
setdefaultr
rrd)rerfr:r:r;�	open_text�srlcCs|jttd�S)N)rhri)�decoder
r)�sr:r:r;rm�srmcCs|S)Nr:)rnr:r:r;rm�scCstjdjS)z+Return updated psutil.PROCFS_PATH constant.Zpsutil)�sys�modulesrr:r:r:r;�get_procfs_path�srqcCsNt|t�st|��tj|�}|jd�d}|jd�rJt|�rJ|dd�}|S)zWrapper around os.readlink().�rz
 (deleted)N�
i����)�
isinstancer�AssertionError�os�readlink�split�endswithr)rTr:r:r;rw�s
rwcCsXtjdtjdtjdi}||tjtjBtjB@}|tj@rH|jddd�}|jdd�}|S)zZConvert file's open() flags into a readable string.
    Used by Process.open_files().
    �r�wzw+�arzr+)rv�O_RDONLY�O_WRONLY�O_RDWR�O_APPEND�replace)rWZ	modes_maprVr:r:r;�file_flags_to_mode�s
r�cCsDy&td|d��}t|j��SQRXWnttfk
r>tSXdS)zKReturn the sector size of a partition.
    Used by disk_io_counters().
    z"/sys/block/%s/queue/hw_sector_sizerjN)rd�int�read�IOError�
ValueError�SECTOR_SIZE_FALLBACK)�	partition�fr:r:r;�get_sector_size�s
r�cCs�td|��}|j�j�dd�}WdQRXdddddd	d
g}t|�}|dkrX|jd�|d
krj|jd�|dkr||jd�td|�adS)z�Set a namedtuple of variable fields depending on the CPU times
    available on this Linux kernel version which may be:
    (user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
     [guest_nice]]])
    Used by cpu_times() function.
    z%s/statrN�user�nice�systemZidleZiowaitZirqZsoftirq�Zsteal�	ZguestrsZ
guest_nice�	scputimes)rg�readlinerx�len�appendrr�)�procfs_pathr��values�fieldsZvlenr:r:r;�set_scputimes_ntuples	


r�TcCsTy,|rt|�nt|��}|j�j�SQRXWn"tk
rN|tk	rH|S�YnXdS)z�Return file content.
    fallback: the value returned in case the file does not exist or
              cannot be read
    binary: whether to open the file in binary or text mode.
    N)rgrlr��stripr��_DEFAULT)re�fallback�binaryr�r:r:r;�cat sr�z/procr�zuser system idlegcCs|d}||jdd�}y|d}|d}|d}Wntk
rH|SXytdt��}Wntk
rp|SXd}|�:x2|D]*}|j�}|jd�r�|t|j�d	�7}q�WWd
QRX|t	9}|}||}	||}
|
t
|
d|�8}
|	|
7}	|	|t
|d|�7}	t|	�S)
a�Fallback for kernels < 3.14 where /proc/meminfo does not provide
    "MemAvailable:" column, see:
    https://blog.famzah.net/2014/09/24/
    This code reimplements the algorithm outlined here:
    https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
        commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

    XXX: on recent kernels this calculation differs by ~1.5% than
    "MemAvailable:" as it's calculated slightly differently, see:
    https://gitlab.com/procps-ng/procps/issues/42
    https://github.com/famzah/linux-memavailable-procfs/issues/2
    It is still way more realistic than doing (free + cached) though.
    sMemFree:sCached:rs
Active(file):sInactive(file):s
SReclaimable:z%s/zoneinfoslowrNr5g@)�get�KeyErrorrgrqr�r��
startswithr�rx�PAGESIZE�min)�memsrKr�Zlru_active_fileZlru_inactive_fileZslab_reclaimabler�Z
watermark_low�line�availZ	pagecacher:r:r;�calculate_avail_vmem=s4

"r�cNCs�g}i}tdt���4}x,|D]$}|j�}t|d�d||d<qWWdQRX|d}|d}y|d}Wn"tk
r�d}|jd	�YnXy|d
}Wn"tk
r�d}|jd�YnX||jdd�7}y|d
}	WnHtk
�r$y|d}	Wn$tk
�rd}	|jd�YnXYnXy|d}
Wn$tk
�rVd}
|jd�YnXy|d}WnXtk
�r�y|d|d|d}Wn$tk
�r�d}|jd�YnXYnX||||}|dk�r�||}y|d}
Wntk
�r
t|�}
YnX|
dk�r$d}
|jd�|
|k�r2|}
t||
|dd�}|�rzddj	|�t
|�dk�rfdndf}tj|t
�t||
||||
||||	�
S)a�Report virtual memory stats.
    This implementation matches "free" and "vmstat -s" cmdline
    utility values and procps-ng-3.3.12 source was used as a reference
    (2016-09-18):
    https://gitlab.com/procps-ng/procps/blob/
        24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c
    For reference, procps-ng-3.3.10 is the version available on Ubuntu
    16.04.

    Note about "available" memory: up until psutil 4.3 it was
    calculated as "avail = (free + buffers + cached)". Now
    "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as
    it's more accurate.
    That matches "available" column in newer versions of "free".
    z
%s/meminforirNs	MemTotal:sMemFree:sBuffers:rNsCached:rOs
SReclaimable:sShmem:s
MemShared:rPsActive:rLs	Inactive:sInact_dirty:sInact_clean:sInact_laundry:rMs
MemAvailable:rH)�_roundz6%s memory stats couldn't be determined and %s set to 0z, ZwasZwere)rgrqrxr�r�r�r�r�r�joinr��warnings�warn�RuntimeWarningrF)Zmissing_fieldsr�r�r�r�rGrKrNrOrPrLrMrJr�rI�msgr:r:r;�virtual_memoryrsz
&
	


r�c%Cs�i}tdt���4}x,|D]$}|j�}t|d�d||d<qWWdQRXy|d}|d}Wn:tk
r�tj�\}}}}}}}||9}||9}YnX||}t||dd�}	ytd	t��}WnDtk
�r}
z&d
t	|
�}t
j|t�d}}
WYdd}
~
Xn�X|��d}}
x�|D]j}|j
d��rJt|jd�d�d
d}n&|j
d��rpt|jd�d�d
d}
|dk	�r|
dk	�rP�qWd}t
j|t�d}}
WdQRXtj||||	||
�S)zReturn swap memory metrics.z
%s/meminforirNs
SwapTotal:s	SwapFree:)r�z	%s/vmstatzP'sin' and 'sout' swap memory stats couldn't be determined and were set to 0 (%s)spswpin� rspswpoutzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)rgrqrxr�r��cextZ
linux_sysinforr��strr�r�r�r�rZsswap)r�r�r�r�rGrK�_Zunit_multiplierrJrI�errr�ZsinZsoutr:r:r;�swap_memory�sD
&

r�cCs^t�}t|�td|��}|j�j�}WdQRX|dttj�d�}dd�|D�}t|�S)z�Return a named tuple representing the following system-wide
    CPU times:
    (user, nice, system, idle, iowait, irq, softirq [steal, [guest,
     [guest_nice]]])
    Last 3 fields may not be available on all Linux kernel versions.
    z%s/statNrcSsg|]}t|�t�qSr:)�float�CLOCK_TICKS)�.0rCr:r:r;�
<listcomp>-szcpu_times.<locals>.<listcomp>)rqr�rgr�rxr�r��_fields)r�r�r�r�r:r:r;�	cpu_times!sr�cCs�t�}t|�g}td|��d}|j�xT|D]L}|jd�r.|j�}|dttj�d�}dd�|D�}t|�}|j	|�q.W|SQRXdS)zfReturn a list of namedtuple representing the CPU times
    for every CPU available on the system.
    z%s/statscpurcSsg|]}t|�t�qSr:)r�r�)r�rCr:r:r;r�?sz!per_cpu_times.<locals>.<listcomp>N)
rqr�rgr�r�rxr�r�r�r�)r��cpusr�r�r�r��entryr:r:r;�
per_cpu_times1s

r�cCs�y
tjd�Stk
r�d}tdt���*}x"|D]}|j�jd�r4|d7}q4WWdQRX|dkr�tjd�}t	dt���4}x,|D]$}|j
d	�d}|j|�r�|d7}q�WWdQRX|dkr�dS|SXdS)
z0Return the number of logical CPUs in the system.�SC_NPROCESSORS_ONLNrz
%s/cpuinfos	processorrNzcpu\dz%s/statra)rv�sysconfr�rgrq�lowerr��re�compilerlrx�match)Znumr�r��searchr:r:r;�cpu_count_logicalEs$




r�cCs�i}i}tdt���z}xr|D]j}|j�j�}|sXd|krRd|krR|d||d<i}q|jd�sl|jd�r|jdd�\}}t|�||<qWWdQRXt|j��p�dS)z2Return the number of physical cores in the system.z
%s/cpuinfosphysical ids	cpu coress	:rN)	rgrqr�r�r�rxr��sumr�)�mappingZcurrent_infor�r��key�valuer:r:r;�cpu_count_physicalbs


r�cCs�tdt����}d}d}d}xx|D]p}|jd�rBt|j�d�}n6|jd�r^t|j�d�}n|jd�rxt|j�d�}|dk	r"|dk	r"|dk	r"Pq"WWdQRXd}tj||||�S)z*Return various CPU stats as a named tuple.z%s/statNsctxtrsintrssoftirqr)rgrqr�r�rxrZ	scpustats)r�Zctx_switchesZ
interruptsZsoft_interruptsr�Zsyscallsr:r:r;�	cpu_stats{s"



r�z/sys/devices/system/cpu/cpufreqz$/sys/devices/system/cpu/cpu0/cpufreqcCs�g}tjd�}|r$|jdd�d�ntjd�}|jdd�d�tjj}x�|D]�}t||d�dd	�}|dkr�t||d
�dd	�}|dkr�td��t|�d}tt||d
���d}tt||d���d}|jt	j
|||��qLW|S)z�Return frequency metrics for all CPUs.
        Contrarily to other OSes, Linux updates these values in
        real-time.
        z'/sys/devices/system/cpu/cpufreq/policy*cSsttjj|�dd��S)N�)r�rvrT�basename)rCr:r:r;�<lambda>�szcpu_freq.<locals>.<lambda>)r�z)/sys/devices/system/cpu/cpu[0-9]*/cpufreqcSsttjd|�jd��S)Nz[0-9]+r)r�r�r��group)rCr:r:r;r��sZscaling_cur_freqN)r�Zcpuinfo_cur_freqz!can't find current frequency filei�Zscaling_max_freqZscaling_min_freq)�glob�sortrvrTr�r��NotImplementedErrorr�r�rZscpufreq)�ret�lsZpjoinrTZcurrZmax_Zmin_r:r:r;�cpu_freq�s&


r�c@seZdZdS)�_Ipv6UnsupportedErrorN)r7r8r9r:r:r:r;r��sr�c@sZeZdZdZdd�Zdd�Zdd�Zedd	��Zeddd��Z	edd
d��Z
ddd�Zd
S)�ConnectionsawA wrapper on top of /proc/net/* files, retrieving per-process
    and system-wide open connections (TCP, UDP, UNIX) similarly to
    "netstat -an".

    Note: in case of UNIX sockets we're only able to determine the
    local endpoint/path, not the one it's connected to.
    According to [1] it would be possible but not easily.

    [1] http://serverfault.com/a/417946
    cCs�dtjtjf}dtjtjf}dtjtjf}dtjtjf}dtjdf}|||||f||f|f|f||f|f|f|f||||f||f||fd�|_d|_dS)N�tcp�tcp6�udp�udp6�unix)�allr��tcp4r�r��udp4r�r��inetZinet4Zinet6)�socket�AF_INET�SOCK_STREAM�AF_INET6Z
SOCK_DGRAMZAF_UNIX�tmap�_procfs_path)�selfr�r�r�r�r�r:r:r;�__init__�s"
zConnections.__init__cCs�tt�}x�tjd|j|f�D]�}ytd|j||f�}WnJtk
r�}z.|jtjtj	fkrbwn|jtj
krrwn�WYdd}~XqX|jd�r|dd�dd�}||j|t
|�f�qW|S)Nz%s/%s/fdz%s/%s/fd/%szsocket:[r�r���)r�listrv�listdirr�rw�OSError�errno�ENOENT�ESRCH�EINVALr�r�r�)r��pid�inodesrU�inoder�r:r:r;�get_proc_inodes�s
zConnections.get_proc_inodescCsli}xbt�D]X}y|j|j|��Wqtk
rb}z"|jtjtjtjtjfkrR�WYdd}~XqXqW|S)N)	�pids�updater�r�r�r�r��EPERM�EACCES)r�r�r�r�r:r:r;�get_all_inodes�szConnections.get_all_inodesc
Cs�|jd�\}}t|d�}|s fStr.|jd�}|tjkrntrZtj|tj	|�ddd��}q�tj|tj	|��}nxtj	|�}yJtr�tjtj
tjd	tj
d|����}n tjtj
tjd
tj
d|����}Wn"tk
r�t�s�t�n�YnXtj||�S)a�Accept an "ip:port" address as displayed in /proc/net/*
        and convert it into a human readable form, like:

        "0500000A:0016" -> ("10.0.0.5", 22)
        "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)

        The IP address portion is a little or big endian four-byte
        hexadecimal number; that is, the least significant byte is listed
        first, so we need to reverse the order of the bytes to convert it
        to an IP address.
        The port is represented as a two-byte hexadecimal number.

        Reference:
        http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
        �:��asciiNr�>4I�<4Ir�)r�)r�)rxr�r�encoder�r��
LITTLE_ENDIANZ	inet_ntop�base64Z	b16decoder��struct�pack�unpackr�rr�r�addr)r�familyZipZportr:r:r;�decode_address
s0



zConnections.decode_addressNccsF|jd�rtjj|�rdSt|td���}|j��xt|d�D]�\}}y(|j�dd�\
}}	}
}}}}}}}Wn&t	k
r�t
d|||f��YnX||kr�||d\}
}nd	\}
}|dk	r�||
kr�qBqB|tjkr�t
|}ntj}ytj|	|�}	tj|
|�}
Wntk
�rwBYnX||||	|
||
fVqBWWdQRXdS)
z.Parse /proc/net/tcp* and /proc/net/udp* files.�6N)�	bufferingrrsz,error while parsing %s; malformed line %s %rrr�)Nr�)ryrvrT�existsrl�BIGFILE_BUFFERINGr��	enumeraterxr��RuntimeErrorr�r��TCP_STATUSESr�	CONN_NONEr�rr�)�filer�type_r��
filter_pidr��linenor�r��laddr�raddr�statusr�r�rUr:r:r;�process_inetDs2(

zConnections.process_inetccst|td���}|j�x�|D]�}|j�}y|dd�\}}}}}}}	Wn.tk
rtd|kr`wtd||f��YnX|	|kr�||	}
ndg}
xd|
D]\\}}|dk	r�||kr�q�q�t|�dkr�|d}
nd	}
t|�}d	}tj	}||||
|||fVq�WqWWdQRXdS)
zParse /proc/net/unix files.)rr�raz)error while parsing %s; malformed line %rNrr��r�)Nr�r�)
rlr	r�rxr�rr�r�rr
)rrr�rr�r��tokensr�rr�Zpairsr�rUrTrrr:r:r;�process_unixls2


zConnections.process_unixc
Cs"||jkr,td|djdd�|jD��f��t�|_|dk	rP|j|�}|sXgSn|j�}t�}x�|j|D]�\}}}|tj	tj
fkr�|jd|j|f||||d�}n|jd|j|f|||d�}xT|D]L\}	}}}
}}}
|r�t
j|	|||
||�}nt
j|	|||
|||
�}|j|�q�WqjWt|�S)Nz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr:)�repr)r�rCr:r:r;r��sz(Connections.retrieve.<locals>.<listcomp>z	%s/net/%s)r)r�r�r�rqr�r�r��setr�r�r�rrrZpconnZsconn�addr�)r��kindr�r�r�r�rrr�rUrrrZ	bound_pidZconnr:r:r;�retrieve�s4

zConnections.retrieve)N)N)N)r7r8r9�__doc__r�r�r��staticmethodrrrrr:r:r:r;r��s
7'%r�r�cCs
tj|�S)z$Return system-wide open connections.)�_connectionsr)rr:r:r;�net_connections�sr"cCs�tdt���}|j�}WdQRXi}x�|dd�D]�}|jd�}|dksVtt|���|d|�j�}||dd�j�j�}tt	|�\}}}	}
}}}
}}}}}}}}}|||||	||
|f||<q4W|S)zsReturn network I/O statistics for every network interface
    installed on the system as a dict of raw tuples.
    z
%s/net/devNr5r�rr)
rlrq�	readlines�rfindrurr�rx�mapr�)r��lines�retdictr�Zcolon�namer�Z
bytes_recvZpackets_recvZerrinZdropinZfifoinZframeinZcompressedinZmulticastinZ
bytes_sentZpackets_sentZerroutZdropoutZfifooutZ
collisionsoutZ
carrieroutZ
compressedoutr:r:r;�net_io_counters�s
*r)cCsptjttjttjti}t�j�}i}xF|D]>}t	j
|�}t	j|�}tj|�\}}t
j|||||�||<q*W|S)z)Get NIC stats (isup, duplex, speed, mtu).)r�ZDUPLEX_FULLrZDUPLEX_HALFrZDUPLEX_UNKNOWNrr)�keys�
cext_posixZ
net_if_mtuZnet_if_flagsZnet_if_duplex_speedrZ	snicstats)Z
duplex_map�namesr�r(ZmtuZisupZduplexZspeedr:r:r;�net_if_stats�s




r-cCs`dd�}i}|�}tdt���}|j�}WdQRX�x$|D�]}|j�}t|�}|dkr�|d}t|d�}	tt|dd	��\
}
}}}
}}}}}}n�|d	kr�|d}tt|dd	��\}	}
}}}
}}}}}}nN|d
k�r|d}tt|dd��\}	}}
}d}}}
}}ntd|��||kr<t|�}||9}||9}|	|
|||||
||f	||<q<W|S)
zcReturn disk I/O statistics for every disk installed on the
    system as a dict of raw tuples.
    cSs�g}tdt���}|j�dd�}WdQRXxXt|�D]L}|j�\}}}}|dj�rd|j|�q8|sz|dj|�r8|j|�q8W|S)Nz
%s/partitionsr5rr�r�)rlrqr#�reversedrx�isdigitr�r�)�
partitionsr�r&r�r�r(r:r:r;�get_partitions�sz(disk_io_counters.<locals>.get_partitionsz%s/diskstatsN�rr5r�rrz!not sure how to interpret line %r)	rlrqr#rxr�r�r%r�r�)r1r'r0r�r&r�r�Z
fields_lenr(ZreadsZreads_mergedZrbytesZrtimeZwritesZ
writes_mergedZwbytesZwtimer�rRZssizer:r:r;�disk_io_counters�s6(*
r4Fc
Cs�t�}tdt���V}xN|D]F}|j�}|jd�sB|j|j��q|jd�d}|dkr|jd�qWWdQRXg}tj�}xT|D]L}|\}}	}}
|dkr�d}|s�|dks�||kr�q�t	j
||	||
�}|j|�q�W|S)	z8Return mounted disk partitions as a list of namedtuples.z%s/filesystemsZnodev�	rZzfsNZnoner)rrlrqr�r�rrxr��disk_partitionsrZ	sdiskpartr�)r�Zfstypesr�r�Zfstype�retlistr0r�ZdeviceZ
mountpointZopts�ntupler:r:r;r6?s*


r6c	Cs.tjt�}tjd�}|jtjd��ttdd�|D���}x�|D]�}ytt|d��d}Wn8t	t
fk
r�}ztjd|t
�w@WYdd}~XnXttjjtjj|�d	�d
d�}t|ddd
�}t|ddd
�}t|ddd
d�}|dk	r�t|�d}|dk	�rt|�d}||j||||f�q@W|S)a�Return hardware (CPU and others) temperatures as a dict
    including hardware name, label, current, max and critical
    temperatures.

    Implementation notes:
    - /sys/class/hwmon looks like the most recent interface to
      retrieve this info, and this implementation relies on it
      only (old distros will probably use something else)
    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
    - /sys/class/thermal/thermal_zone* is another one but it's more
      difficult to parse
    z/sys/class/hwmon/hwmon*/temp*_*z&/sys/class/hwmon/hwmon*/device/temp*_*cSsg|]}|jd�d�qS)r�r)rx)r�rCr:r:r;r�ssz(sensors_temperatures.<locals>.<listcomp>�_inputg@�@zignoring %rNr(F)r�Z_max)r�Z_crit�_labelr)r�r�)�collectionsrr�r��extend�sortedrr�r�r�r�r�r�r�rvrTr��dirnamer�)	r��	basenames�base�currentr��	unit_nameZhighZcritical�labelr:r:r;�sensors_temperatures`s*



rDcCs�tjt�}tjd�}|s"tjd�}ttdd�|D���}x�|D]�}ytt|d��}Wn8tt	fk
r�}zt
jd|t�w>WYdd}~XnXtt
jjt
jj|�d�d	d
�}t|ddd	d
�}||jtj||��q>Wt|�S)a�Return hardware fans info (for CPU and other peripherals) as a
    dict including hardware label and current speed.

    Implementation notes:
    - /sys/class/hwmon looks like the most recent interface to
      retrieve this info, and this implementation relies on it
      only (old distros will probably use something else)
    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
    z/sys/class/hwmon/hwmon*/fan*_*z%/sys/class/hwmon/hwmon*/device/fan*_*cSsg|]}|jd�d�qS)r�r)rx)r�rCr:r:r;r��sz sensors_fans.<locals>.<listcomp>r9zignoring %rNr(F)r�r:r)r�r�)r;rr�r�r=rr�r�r�r�r�r�r�rvrTr�r>r�rZsfan�dict)r�r?r@rAr�rBrCr:r:r;�sensors_fans�s 




rFc
s�t���fdd�}tjjtd�}tjj|�s0dS||d|d�}||d|d�}||d	|d
�}|dksv|dkrzdS|dk	r�yd||}Wq�tk
r�d}Yq�Xn tt|d
dd��}|dkr�dSd}|tjjtd�tjjtd��}|dk	�r|dk}n4t|dddd�j	�}|dk�r*d}n|dk�r8d}|�rFt
j}	n2yt||d�}	Wntk
�rvt
j}	YnXt
j
||	|�S)aReturn battery information.
    Implementation note: it appears /sys/class/power_supply/BAT0/
    directory structure may vary and provide files with the same
    meaning but under different names, see:
    https://github.com/giampaolo/psutil/issues/966
    cs:x4|D],}t|�d�}|�kr|j�r.t|�S|SqWdS)zvAttempt to read the content of multiple files which may
        not exist. If none of them exist return None.
        )r�N)r�r/r�)�pathsrTr�)�nullr:r;�	multi_cat�s

z"sensors_battery.<locals>.multi_catZBAT0Nz/energy_nowz/charge_nowz
/power_nowz/current_nowz/energy_fullz/charge_fullgY@gz	/capacityr)r�z
AC0/onlinez	AC/onlinez/statusrF)r�r�Zdischarging�charging�fullTir�r�)rJrK)�objectrvrTr��POWER_SUPPLY_PATHr�ZeroDivisionErrorr�r�r�rZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)
rI�rootZ
energy_nowZ	power_nowZenergy_fullrIZ
power_pluggedZonlinerZsecsleftr:)rHr;�sensors_battery�sT







rPc
Cs`g}tj�}xN|D]F}|\}}}}}}|s,q|dkr8d}tj||pDd|||�}	|j|	�qW|S)z:Return currently connected users as a list of namedtuples.�:0.0�:0Z	localhostN)rQrR)r��usersrZsuserr�)
r7Zrawlist�itemr�ZttyZhostnameZtstampZuser_processr��ntr:r:r;rSs
rScCsbdt�}t|��F}x2|D]*}|jd�rt|j�j�d�}|a|SqWtd|��WdQRXdS)zAReturn the system boot time expressed in seconds since the epoch.z%s/statsbtimerzline 'btime' not found in %sN)rqrgr�r�r�rx�	BOOT_TIMEr)rTr�r�r�r:r:r;�	boot_times



rWcCsdd�tjtt���D�S)z7Returns a list of PIDs currently running on the system.cSsg|]}|j�rt|��qSr:)r/r�)r�rCr:r:r;r�,szpids.<locals>.<listcomp>)rvr�rrqr:r:r:r;r�*sr�cCs�tj|�sdSybdt�|f}t|��B}x.|D]&}|jd�r.t|j�d�}||kSq.Wtd|��WdQRXWnttfk
r�|t	�kSXdS)zcCheck for the existence of a unix PID. Linux TIDs are not
    supported (always return False).
    Fz%s/%s/statussTgid:rz'Tgid' line not found in %sN)
r�
pid_existsrqrgr�r�rxr��EnvironmentErrorr�)r�rTr�r�Ztgidr:r:r;rX/s




rXc	Cs�i}t�}x�t�D]�}y(td||f��}|j�}WdQRXWn>tk
r|}z"|jtjtjtjtj	fkrl�WYdd}~XqX|j
d�}||dd�j�}t|d�}|||<qW|S)zsObtain a {pid: ppid, ...} dict for all running processes in
    one shot. Used to speed up Process.children().
    z
%s/%s/statN�)r5r)
rqr�rgr�rYr�r�r�r�r�r$rxr�)	r�r�r�r��datar��rparZdset�ppidr:r:r;�ppid_mapOs
r^cstj���fdd��}|S)zlDecorator which translates bare OSError and IOError exceptions
    into NoSuchProcess and AccessDenied.
    cs�y�|f|�|�Stk
r�}zv|jtjtjfkrBt|j|j��|jtjkr\t|j|j��|jtj	kr�t
jjd|j
|jf�r�t|j|j���WYdd}~XnXdS)Nz%s/%s)rYr�r�r�rr��_namer�rr�rvrTrr�)r��argsrfr�)�funr:r;�wrapperksz wrap_exceptions.<locals>.wrapper)�	functools�wraps)rarbr:)rar;�wrap_exceptionsgsrec@sneZdZdZddddgZdd�Zedd	��Zed
d��Zedd
��Z	dd�Z
dd�Zedd��Z
dd�Zedd��Zedd��Zedd��Zejjdej��r�edd��Zndd�Zed d!��Zed"d#��Zed`d%d&��Zed'd(��Zed)d*��Ze�r"eejd+�ejd,�ejd-�fd.d/��ZneZe�r:ed0d1��Z nd2d1�Z ed3d4��Z!eejd5�fd6d7��Z"eejd8�fd9d:��Z#ed;d<��Z$ed=d>��Z%ed?d@��Z&edAdB��Z'ejdC�fdDdE�Z(edFdG��Z)e*e+dH��r�edIdJ��Z,edKdL��Z-e.�redadMdN��Z/edOdP��Z0edQdR��Z1edbdTdU��Z2edVdW��Z3edXdY��Z4eejdZ�fd[d\��Z5eejd]�fd^d_��Z6d$S)c�ProcesszLinux process implementation.r�r_�_ppidr�cCs||_d|_d|_t�|_dS)N)r�r_rgrqr�)r�r�r:r:r;r��szProcess.__init__c
Csftd|j|jf��}|j�}WdQRX|jd�}||jd�d|�}||dd�j�}|g|S)a{Parse /proc/{pid}/stat file. Return a list of fields where
        process name is in position 0.
        Using "man proc" as a reference: where "man proc" refers to
        position N, always substract 2 (e.g starttime pos 22 in
        'man proc' == pos 20 in the list returned here).
        The return value is cached in case oneshot() ctx manager is
        in use.
        z
%s/%s/statNrZ�(rr5)rgr�r�r�r$�findrx)r�r�r[r\r(Zothersr:r:r;�_parse_stat_file�s

zProcess._parse_stat_filec	Cs(td|j|jf��
}|j�SQRXdS)z�Read /proc/{pid}/stat file and return its content.
        The return value is cached in case oneshot() ctx manager is
        in use.
        z%s/%s/statusN)rgr�r�r�)r�r�r:r:r;�_read_status_file�szProcess._read_status_filec	Cs0td|j|jftd��}|j�j�SQRXdS)Nz%s/%s/smaps)r)rgr�r�r	r�r�)r�r�r:r:r;�_read_smaps_file�s
zProcess._read_smaps_filecCs"|jj�|jj�|jj�dS)N)rjZcache_activaterkrl)r�r:r:r;�
oneshot_enter�s

zProcess.oneshot_entercCs"|jj�|jj�|jj�dS)N)rjZcache_deactivaterkrl)r�r:r:r;�oneshot_exit�s

zProcess.oneshot_exitcCs|j�d}trt|�}|S)Nr)rjrrm)r�r(r:r:r;r(�szProcess.namecCs�ytd|j|jf�Stk
r�}z�|jtjtjfkr�tjj	d|j|jf�rTdSt
|j�snt|j|j��nt
|j|j|j��|jtjtjfkr�t|j|j���WYdd}~XnXdS)Nz	%s/%s/exez%s/%sr)rwr�r�r�r�r�r�rvrT�lexistsrXrr_rrgr�r�r)r�r�r:r:r;�exe�s
zProcess.exec
Csltd|j|jf��}|j�}WdQRX|s0gS|jd�r>dnd}|j|�rX|dd�}dd�|j|�D�S)Nz
%s/%s/cmdlinerrrarcSsg|]}|�qSr:r:)r�rCr:r:r;r��sz#Process.cmdline.<locals>.<listcomp>r�)rlr�r�r�ryrx)r�r�r[�sepr:r:r;�cmdline�s
zProcess.cmdlinec	Cs0td|j|jf��}|j�}WdQRXt|�S)Nz
%s/%s/environ)rlr�r�r�r)r�r�r[r:r:r;�environ�szProcess.environcCs:t|j�d�}tj�}y||Stk
r4dSXdS)N�)r�rjrZget_terminal_mapr�)r�Ztty_nrr�r:r:r;�terminal�szProcess.terminalz/proc/%s/iocCs�d|j|jf}i}t|��:}x2|D]*}|j�}|r$|jd�\}}t|�||<q$WWdQRX|sltd|��t|d|d|d|d|d|d	�S)
Nz%s/%s/ios: z%s file was emptyssyscrssyscws
read_bytesswrite_bytessrcharswchar)r�r�rgr�rxr�rrb)r�rer�r�r�r(r�r:r:r;�io_counters�s"

zProcess.io_counterscCstd|j��dS)Nz+couldn't find /proc/%s/io (kernel too old?))r�r�)r�r:r:r;rvscCsX|j�}t|d�t}t|d�t}t|d�t}t|d�t}tj||||�S)N��
r3r2)rjr�r�rZ	pcputimes)r�r��utime�stimeZchildren_utimeZchildren_stimer:r:r;r�szProcess.cpu_timescCst|j�d�S)zWhat CPU the process is on.�%)r�rj)r�r:r:r;�cpu_numszProcess.cpu_numNcCstj|j||j�S)N)rZwait_pidr�r_)r�Ztimeoutr:r:r;�waitszProcess.waitcCs&|j�}tpt�}t|d�t|S)N�)rjrVrWr�r�)r�r�Zbtr:r:r;�create_time"s
zProcess.create_timec	Cs`td|j|jf��2}dd�|j�j�dd�D�\}}}}}}}WdQRXt|||||||�S)Nz%s/%s/statmcSsg|]}t|�t�qSr:)r�r�)r�rCr:r:r;r�<sz'Process.memory_info.<locals>.<listcomp>r)rgr�r�r�rxrX)	r�r�Zvmsr^rP�text�libr[Zdirtyr:r:r;�memory_info-s
6zProcess.memory_infosPrivate.*:\s+(\d+)sPss.*:\s+(\d+)sSwap.*:\s+(\d+)c	Csj|j�}|j�}ttt|j|���d}ttt|j|���d}ttt|j|���d}t||||f�S)Ni)r�rlr�r%r��findallrY)	r�Z_private_reZ_pss_reZ_swap_reZ	basic_memZ
smaps_datarZr[r\r:r:r;�memory_full_infoCs
zProcess.memory_full_infocCsXdd�}|j�}|sgS|jd�}g}|jd�}|g}�x|||�D�]
\}}|jdd�}y|\}	}
}}}
}Wn*tk
r�|dg\}	}
}}}
}YnX|s�d}n4tr�t|�}|j�}|jd	�r�t|�r�|dd�}|j	t|	�t|
�||d|j
dd�|j
d
d�|j
dd�|j
dd�|j
dd�|j
dd�|j
dd�|j
dd�|j
dd�f
�qDW|S)z�Return process's mapped memory regions as a list of named
            tuples. Fields are explained in 'man proc'; here is an updated
            (Apr 2012) version: http://goo.gl/fmebo
            css�i}x�|D]�}|jdd�}|djd�sB|j�|fV|j|�q
yt|d�d||d<Wq
tk
r�|djd�r�w
ntd|��Yq
Xq
W|j�|fVdS)Nrtr�:risVmFlags:z#don't know how to interpret line %r)rxry�popr�r�r�r�)r&�
current_blockr[r�r�r:r:r;�
get_blocksis
z'Process.memory_maps.<locals>.get_blocks�
rNrtrz[anon]z
 (deleted)rssRss:sSize:sPss:s
Shared_Clean:s
Shared_Dirty:sPrivate_Clean:sPrivate_Dirty:sReferenced:s
Anonymous:sSwap:i����)rlrxr�r�rrmr�ryrr�r�)r�r�r[r&r�Z
first_liner��headerZhfieldsrZperms�offsetZdevr�rTr:r:r;�memory_mapscsF











zProcess.memory_mapscCstd|j��dS)Nzn/proc/%s/smaps does not exist on kernels < 2.6.14 or if CONFIG_MMU kernel configuration option is not enabled.)r�r�)r�r:r:r;r��scCs|ytd|j|jf�Stk
rv}zF|jtjtjfkrdt|j�sRt|j|j	��nt
|j|j	|j���WYdd}~XnXdS)Nz	%s/%s/cwd)rwr�r�r�r�r�r�rXrr_rrg)r�r�r:r:r;�cwd�s
zProcess.cwdsctxt_switches:\t(\d+)cCsL|j�}|j|�}|s,td|j|jf��ntjt|d�t|d��SdS)Nz�'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'lines were not found in %s/%s/status; the kernel is probably older than 2.6.23rr)rkr�r�r�r�rZpctxswr�)r�Z	_ctxsw_rer[Zctxswr:r:r;�num_ctx_switches�s
zProcess.num_ctx_switchessThreads:\t(\d+)cCs|j�}t|j|�d�S)Nr)rkr�r�)r�Z_num_threads_rer[r:r:r;�num_threads�szProcess.num_threadsc
Cstjd|j|jf�}|j�g}d}x�|D]�}d|j|j|f}y$t|��}|j�j�}WdQRXWn6tk
r�}z|j	t	j
kr�d}w,�WYdd}~XnX||jd�dd�}|jd�}	t
|	d�t}
t
|	d	�t}tjt|�|
|�}|j|�q,W|�rtjd
|j|jf�|S)Nz
%s/%s/taskFz%s/%s/task/%s/statTrZr5r��rwz%s/%s)rvr�r�r�r�rgr�r�r�r�r�rirxr�r�rZpthreadr�r��stat)
r�Z
thread_idsr7�
hit_enoentZ	thread_idrer��str�r�ryrzr8r:r:r;�threads�s0


zProcess.threadscCstj|j�S)N)r+�getpriorityr�)r�r:r:r;�nice_get�szProcess.nice_getcCstj|j|�S)N)r+�setpriorityr�)r�r�r:r:r;�nice_set�szProcess.nice_setcCstj|j�S)N)r�Zproc_cpu_affinity_getr�)r�r:r:r;�cpu_affinity_get�szProcess.cpu_affinity_getsCpus_allowed_list:\t(\d+)-(\d+)cCsV|j�}|j|�}|r@ttt|dd�t|dd�d��Stttt����SdS)Nrr)rkr�r��ranger�r�r�)r�Z_rer[r�r:r:r;�_get_eligible_cpus�s

*zProcess._get_eligible_cpuscCs�ytj|j|�Wn�ttfk
r�}zvt|t�s>|jtjkr�|j�}t	t
tt����}x<|D]4}||krztd||f��||kr^td||f��q^W�WYdd}~XnXdS)Nz(invalid CPU number %r; choose between %sz0CPU number %r is not eligible; choose between %s)
r�Zproc_cpu_affinity_setr�r�r�rtr�r�r��tupler�r�r�)r�r�r�Z
eligible_cpusZall_cpusZcpur:r:r;�cpu_affinity_sets 
zProcess.cpu_affinity_set�proc_ioprio_getcCs,tj|j�\}}tdk	r t|�}tj||�S)N)r�r�r��enumr6rZpionice)r��ioclassr�r:r:r;�
ionice_getszProcess.ionice_getcCs�|dk	rNtr.t|ttf�r.d|}t|��d|ko@dknsNtd��|tdfkrx|rnd|}t|��t}d}nH|tkr�|r�d|}t|��d}n&|tt	fkr�|dkr�d}ntd|��t
j|j||�S)	Nz)value argument is not an integer (gor %r)rrz0value argument range expected is between 0 and 7z3can't specify value with IOPRIO_CLASS_NONE (got %r)z3can't specify value with IOPRIO_CLASS_IDLE (got %r)rzinvalid ioclass argument %r)
rrtr�r�	TypeErrorr�r r#r!r"r�Zproc_ioprio_setr�)r�r�r�r�r:r:r;�
ionice_set%s2zProcess.ionice_setcCs�|jdkrtd��yP|dkr*tj|j|�St|�dkrFtdt|���|\}}tj|j|||�WnNtk
r�}z2|jtjkr�t	|j�r�t
|j|j|j��n�WYdd}~XnXdS)Nrz)can't use prlimit() against PID 0 processr5z4second argument must be a (soft, hard) tuple, got %s)
r�r�r�r/r�rr�r�ZENOSYSrXrr_rg)r�ZresourceZlimitsZsoftZhardr�r:r:r;�rlimitGs
zProcess.rlimitcCs$|j�d}tr|j�}tj|d�S)Nr�?)rjrrm�
PROC_STATUSESr�)r�Zletterr:r:r;rbszProcess.statusc
Cs�g}tjd|j|jf�}d}�xH|D�]>}d|j|j|f}yt|�}WnNtk
r�}z2|jtjtjfkrvd}w&n|jtj	kr�w&n�WYdd}~Xq&X|j
d�o�t|�r&d|j|j|f}yBt|��0}t
|j�j�d�}	t
|j�j�dd�}
WdQRXWn:tk
�r:}z|jtjk�r(d}n�WYdd}~Xq&Xt|
�}t|t
|�t
|	�||
�}|j|�q&W|�r�tjd	|j|jf�|S)
Nz%s/%s/fdFz%s/%s/fd/%sT�/z%s/%s/fdinfo/%srr�z%s/%s)rvr�r�r�rwr�r�r�r�r�r�rrgr�r�rxr�r�rSr�r�)
r�r7�filesr�rUrrTr�r��posrWrVr8r:r:r;�
open_filesjs@
$zProcess.open_filesr�cCs(tj||j�}tjd|j|jf�|S)Nz%s/%s)r!rr�rvr�r�)r�rr�r:r:r;�connections�szProcess.connectionscCsttjd|j|jf��S)Nz%s/%s/fd)r�rvr�r�r�)r�r:r:r;�num_fds�szProcess.num_fdscCst|j�d�S)Nr5)r�rj)r�r:r:r;r]�szProcess.ppidsUid:\t(\d+)\t(\d+)\t(\d+)cCs6|j�}|j|�d\}}}tjt|�t|�t|��S)Nr)rkr�rZpuidsr�)r�Z_uids_rer[�real�	effective�savedr:r:r;�uids�szProcess.uidssGid:\t(\d+)\t(\d+)\t(\d+)cCs6|j�}|j|�d\}}}tjt|�t|�t|��S)Nr)rkr�rZpgidsr�)r�Z_gids_rer[r�r�r�r:r:r;�gids�szProcess.gids)N)N)r�)7r7r8r9r�	__slots__r�rrjrkrlrmrnrer(rprrrsrurvrTr�getpidrvr�r|r}rr��	HAS_SMAPSr�r�r�r�r�r�r�r�r�r�r�r�r��hasattrr�r�r��HAS_PRLIMITr�rr�r�r�r]r�r�r:r:r:r;rf�st			B
		!2rf)rrr�)rZr[r\)r�)F)�rZ
__future__rr�r;r�rcr�rvr�r�rro�	tracebackr�rrrrrrr�r	r+r
rrr
rrrrrrrrZ_compatrrrr�_exceptionsrrr�version_infor�Z__extra__all__rMrTrr�r�r�r�rLr��dirr(r�r�r�r�r�rVr	�	byteorderr�r�Z	AF_PACKETr4�IntEnumr�r3r r!r"r#r6�globalsr��__members__ZSTATUS_RUNNINGZSTATUS_SLEEPINGZSTATUS_DISK_SLEEPZSTATUS_STOPPEDZSTATUS_TRACING_STOPZ
STATUS_ZOMBIEZSTATUS_DEADZSTATUS_WAKE_KILLZ
STATUS_WAKINGr�r$r%r&r'r(r)r*r+r,r-r.rrFrQrSrXr�rYr]r�r`rbrgrlrmrqrwr�r�r�r��	Exception�	print_excr�r�r�r�r�r�r�r�r�r�Znet_if_addrsr�r�r!r"r)r-Z
disk_usager4r6rDrFrPrSrWr�rXr^rerfr:r:r:r;�<module>sH















5u:*q
%H
!1 T __pycache__/_pslinux.cpython-36.opt-1.pyc000064400000131564150466730540014226 0ustar003

��JZb$�@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddl$m%Z%ddl$m&Z&ddl$m'Z'ddl$m(Z(ddl)m*Z*ddl)m+Z+ddl)m,Z,ej-d�k�r�ddl.Z.ndZ.d d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/gZ/d0Z0ej1j2d1ej3��Z4e5ed2�Z6e7�Z8e6�r2x(e9e�D]Z:e:j;d3��re/j<e:��qWej=d4�Z>ej=d5�Z?da@e(�rTd�nd6ZAejBd7kZCd8ZDe.dk�rxe
jEZFne.jGd9d:eHe
jE�i�ZIeIjFZFe.dk�r�dZJdZKd;ZLdZMn Gd<d=�d=e.jG�ZNeO�jPeNjQ�ejRejSejTejUejVejWejXejXejYejZd>�
Z[ej\ej]ej^ej_ej`ejaejbejcejdejeejfd?�Zged@dAdBdCdDdEdFdGdHdIdJg
�ZhedKdLdMdNdOdPdQdRdSdTg	�ZiedUdVdWdXdYdZg�Zjed[d\�Zked]ekjld��ZmedadVdbdcd_dddedfdgdhdid`g�Znedjdkdljoenjl��ZpedmdLdMdNdOdndog�Zqdpdq�Zrdrds�Zse(�rdtdu�Ztndvdu�Ztdwdx�Zudydz�Zvd{d|�Zwd}d~�Zxedd���Zye8d�fd�d��Zzyeyd��Wn0e{k
�r�e
j|�ed�d��d�d�d��a}YnXd�d��Z~d�d��Zd�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�ej1j2d���s�ej1j2d���r�d�d��Z�ej�Z�Gd�d��d�e{�Z�Gd�d��d��Z�e��Z�d�d�d��Z�d�d��Z�d�d��Z�ej�Z�d�d��Z�d�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�d�d��Z�Gd�d��d�e7�Z�dS)�zLinux platform implementation.�)�divisionN)�defaultdict)�
namedtuple�)�_common)�_psposix)�
_psutil_linux)�
_psutil_posix)�ENCODING)�
ENCODING_ERRS)�
isfile_strict)�memoize)�memoize_when_activated)�NIC_DUPLEX_FULL)�NIC_DUPLEX_HALF)�NIC_DUPLEX_UNKNOWN)�parse_environ_block)�path_exists_strict)�
supports_ipv6)�
usage_percent)�b)�
basestring)�long)�PY3)�AccessDenied)�
NoSuchProcess)�
ZombieProcess���PROCFS_PATH�IOPRIO_CLASS_NONE�IOPRIO_CLASS_RT�IOPRIO_CLASS_BE�IOPRIO_CLASS_IDLE�CONN_ESTABLISHED�
CONN_SYN_SENT�
CONN_SYN_RECV�CONN_FIN_WAIT1�CONN_FIN_WAIT2�CONN_TIME_WAIT�
CONN_CLOSE�CONN_CLOSE_WAIT�
CONN_LAST_ACK�CONN_LISTEN�CONN_CLOSINGz/sys/class/power_supplyz/proc/%s/smaps�
linux_prlimitZRLIM�
SC_CLK_TCK�SC_PAGE_SIZEi �littlei�
AddressFamily�AF_LINK�c@seZdZdZdZdZdZdS)�
IOPriorityrrr5rN)�__name__�
__module__�__qualname__r r!r"r#�r:r:� /usr/lib64/python3.6/_pslinux.pyr6jsr6)
�R�S�D�T�t�Z�X�x�K�W)Z01Z02Z03Z04Z05Z06Z07Z08Z09Z0AZ0B�svmem�total�	available�percent�used�free�active�inactive�buffers�cached�shared�sdiskioZ
read_countZwrite_countZ
read_bytesZwrite_bytesZ	read_timeZ
write_timeZread_merged_countZwrite_merged_count�	busy_time�	popenfile�path�fdZposition�mode�flags�pmemz"rss vms shared text lib data dirty�pfullmem�uss�pss�swap�
pmmap_grouped�rss�sizeZshared_cleanZshared_dirtyZ
private_cleanZ
private_dirtyZ
referencedZ	anonymous�	pmmap_extzaddr perms � �pioZ
read_charsZwrite_charscKst|df|�S)N�rb)�open)�fname�kwargsr:r:r;�open_binary�srgcKs*tr|jdt�|jdt�t|df|�S)z�On Python 3 opens a file in text mode by using fs encoding and
    a proper en/decoding errors handler.
    On Python 2 this is just an alias for open(name, 'rt').
    �encoding�errors�rt)r�
setdefaultr
rrd)rerfr:r:r;�	open_text�srlcCs|jttd�S)N)rhri)�decoder
r)�sr:r:r;rm�srmcCs|S)Nr:)rnr:r:r;rm�scCstjdjS)z+Return updated psutil.PROCFS_PATH constant.Zpsutil)�sys�modulesrr:r:r:r;�get_procfs_path�srqcCs<tj|�}|jd�d}|jd�r8t|�r8|dd�}|S)zWrapper around os.readlink().�rz
 (deleted)N�
i����)�os�readlink�split�endswithr)rTr:r:r;ru�s

rucCsXtjdtjdtjdi}||tjtjBtjB@}|tj@rH|jddd�}|jdd�}|S)zZConvert file's open() flags into a readable string.
    Used by Process.open_files().
    �r�wzw+�arzr+)rt�O_RDONLY�O_WRONLY�O_RDWR�O_APPEND�replace)rWZ	modes_maprVr:r:r;�file_flags_to_mode�s
r�cCsDy&td|d��}t|j��SQRXWnttfk
r>tSXdS)zKReturn the sector size of a partition.
    Used by disk_io_counters().
    z"/sys/block/%s/queue/hw_sector_sizerjN)rd�int�read�IOError�
ValueError�SECTOR_SIZE_FALLBACK)�	partition�fr:r:r;�get_sector_size�s
r�cCs�td|��}|j�j�dd�}WdQRXdddddd	d
g}t|�}|dkrX|jd�|d
krj|jd�|dkr||jd�td|�adS)z�Set a namedtuple of variable fields depending on the CPU times
    available on this Linux kernel version which may be:
    (user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
     [guest_nice]]])
    Used by cpu_times() function.
    z%s/statrN�user�nice�systemZidleZiowaitZirqZsoftirq�Zsteal�	ZguestrsZ
guest_nice�	scputimes)rg�readlinerv�len�appendrr�)�procfs_pathr��values�fieldsZvlenr:r:r;�set_scputimes_ntuples	


r�TcCsTy,|rt|�nt|��}|j�j�SQRXWn"tk
rN|tk	rH|S�YnXdS)z�Return file content.
    fallback: the value returned in case the file does not exist or
              cannot be read
    binary: whether to open the file in binary or text mode.
    N)rgrlr��stripr��_DEFAULT)re�fallback�binaryr�r:r:r;�cat sr�z/procr�zuser system idlegcCs|d}||jdd�}y|d}|d}|d}Wntk
rH|SXytdt��}Wntk
rp|SXd}|�:x2|D]*}|j�}|jd�r�|t|j�d	�7}q�WWd
QRX|t	9}|}||}	||}
|
t
|
d|�8}
|	|
7}	|	|t
|d|�7}	t|	�S)
a�Fallback for kernels < 3.14 where /proc/meminfo does not provide
    "MemAvailable:" column, see:
    https://blog.famzah.net/2014/09/24/
    This code reimplements the algorithm outlined here:
    https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
        commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

    XXX: on recent kernels this calculation differs by ~1.5% than
    "MemAvailable:" as it's calculated slightly differently, see:
    https://gitlab.com/procps-ng/procps/issues/42
    https://github.com/famzah/linux-memavailable-procfs/issues/2
    It is still way more realistic than doing (free + cached) though.
    sMemFree:sCached:rs
Active(file):sInactive(file):s
SReclaimable:z%s/zoneinfoslowrNr5g@)�get�KeyErrorrgrqr�r��
startswithr�rv�PAGESIZE�min)�memsrKr�Zlru_active_fileZlru_inactive_fileZslab_reclaimabler�Z
watermark_low�line�availZ	pagecacher:r:r;�calculate_avail_vmem=s4

"r�cNCs�g}i}tdt���4}x,|D]$}|j�}t|d�d||d<qWWdQRX|d}|d}y|d}Wn"tk
r�d}|jd	�YnXy|d
}Wn"tk
r�d}|jd�YnX||jdd�7}y|d
}	WnHtk
�r$y|d}	Wn$tk
�rd}	|jd�YnXYnXy|d}
Wn$tk
�rVd}
|jd�YnXy|d}WnXtk
�r�y|d|d|d}Wn$tk
�r�d}|jd�YnXYnX||||}|dk�r�||}y|d}
Wntk
�r
t|�}
YnX|
dk�r$d}
|jd�|
|k�r2|}
t||
|dd�}|�rzddj	|�t
|�dk�rfdndf}tj|t
�t||
||||
||||	�
S)a�Report virtual memory stats.
    This implementation matches "free" and "vmstat -s" cmdline
    utility values and procps-ng-3.3.12 source was used as a reference
    (2016-09-18):
    https://gitlab.com/procps-ng/procps/blob/
        24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c
    For reference, procps-ng-3.3.10 is the version available on Ubuntu
    16.04.

    Note about "available" memory: up until psutil 4.3 it was
    calculated as "avail = (free + buffers + cached)". Now
    "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as
    it's more accurate.
    That matches "available" column in newer versions of "free".
    z
%s/meminforirNs	MemTotal:sMemFree:sBuffers:rNsCached:rOs
SReclaimable:sShmem:s
MemShared:rPsActive:rLs	Inactive:sInact_dirty:sInact_clean:sInact_laundry:rMs
MemAvailable:rH)�_roundz6%s memory stats couldn't be determined and %s set to 0z, ZwasZwere)rgrqrvr�r�r�r�r�r�joinr��warnings�warn�RuntimeWarningrF)Zmissing_fieldsr�r�r�r�rGrKrNrOrPrLrMrJr�rI�msgr:r:r;�virtual_memoryrsz
&
	


r�c%Cs�i}tdt���4}x,|D]$}|j�}t|d�d||d<qWWdQRXy|d}|d}Wn:tk
r�tj�\}}}}}}}||9}||9}YnX||}t||dd�}	ytd	t��}WnDtk
�r}
z&d
t	|
�}t
j|t�d}}
WYdd}
~
Xn�X|��d}}
x�|D]j}|j
d��rJt|jd�d�d
d}n&|j
d��rpt|jd�d�d
d}
|dk	�r|
dk	�rP�qWd}t
j|t�d}}
WdQRXtj||||	||
�S)zReturn swap memory metrics.z
%s/meminforirNs
SwapTotal:s	SwapFree:)r�z	%s/vmstatzP'sin' and 'sout' swap memory stats couldn't be determined and were set to 0 (%s)spswpin� rspswpoutzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)rgrqrvr�r��cextZ
linux_sysinforr��strr�r�r�r�rZsswap)r�r�r�r�rGrK�_Zunit_multiplierrJrI�errr�ZsinZsoutr:r:r;�swap_memory�sD
&

r�cCs^t�}t|�td|��}|j�j�}WdQRX|dttj�d�}dd�|D�}t|�S)z�Return a named tuple representing the following system-wide
    CPU times:
    (user, nice, system, idle, iowait, irq, softirq [steal, [guest,
     [guest_nice]]])
    Last 3 fields may not be available on all Linux kernel versions.
    z%s/statNrcSsg|]}t|�t�qSr:)�float�CLOCK_TICKS)�.0rCr:r:r;�
<listcomp>-szcpu_times.<locals>.<listcomp>)rqr�rgr�rvr�r��_fields)r�r�r�r�r:r:r;�	cpu_times!sr�cCs�t�}t|�g}td|��d}|j�xT|D]L}|jd�r.|j�}|dttj�d�}dd�|D�}t|�}|j	|�q.W|SQRXdS)zfReturn a list of namedtuple representing the CPU times
    for every CPU available on the system.
    z%s/statscpurcSsg|]}t|�t�qSr:)r�r�)r�rCr:r:r;r�?sz!per_cpu_times.<locals>.<listcomp>N)
rqr�rgr�r�rvr�r�r�r�)r��cpusr�r�r�r��entryr:r:r;�
per_cpu_times1s

r�cCs�y
tjd�Stk
r�d}tdt���*}x"|D]}|j�jd�r4|d7}q4WWdQRX|dkr�tjd�}t	dt���4}x,|D]$}|j
d	�d}|j|�r�|d7}q�WWdQRX|dkr�dS|SXdS)
z0Return the number of logical CPUs in the system.�SC_NPROCESSORS_ONLNrz
%s/cpuinfos	processorrNzcpu\dz%s/statra)rt�sysconfr�rgrq�lowerr��re�compilerlrv�match)Znumr�r��searchr:r:r;�cpu_count_logicalEs$




r�cCs�i}i}tdt���z}xr|D]j}|j�j�}|sXd|krRd|krR|d||d<i}q|jd�sl|jd�r|jdd�\}}t|�||<qWWdQRXt|j��p�dS)z2Return the number of physical cores in the system.z
%s/cpuinfosphysical ids	cpu coress	:rN)	rgrqr�r�r�rvr��sumr�)�mappingZcurrent_infor�r��key�valuer:r:r;�cpu_count_physicalbs


r�cCs�tdt����}d}d}d}xx|D]p}|jd�rBt|j�d�}n6|jd�r^t|j�d�}n|jd�rxt|j�d�}|dk	r"|dk	r"|dk	r"Pq"WWdQRXd}tj||||�S)z*Return various CPU stats as a named tuple.z%s/statNsctxtrsintrssoftirqr)rgrqr�r�rvrZ	scpustats)r�Zctx_switchesZ
interruptsZsoft_interruptsr�Zsyscallsr:r:r;�	cpu_stats{s"



r�z/sys/devices/system/cpu/cpufreqz$/sys/devices/system/cpu/cpu0/cpufreqcCs�g}tjd�}|r$|jdd�d�ntjd�}|jdd�d�tjj}x�|D]�}t||d�dd	�}|dkr�t||d
�dd	�}|dkr�td��t|�d}tt||d
���d}tt||d���d}|jt	j
|||��qLW|S)z�Return frequency metrics for all CPUs.
        Contrarily to other OSes, Linux updates these values in
        real-time.
        z'/sys/devices/system/cpu/cpufreq/policy*cSsttjj|�dd��S)N�)r�rtrT�basename)rCr:r:r;�<lambda>�szcpu_freq.<locals>.<lambda>)r�z)/sys/devices/system/cpu/cpu[0-9]*/cpufreqcSsttjd|�jd��S)Nz[0-9]+r)r�r�r��group)rCr:r:r;r��sZscaling_cur_freqN)r�Zcpuinfo_cur_freqz!can't find current frequency filei�Zscaling_max_freqZscaling_min_freq)�glob�sortrtrTr�r��NotImplementedErrorr�r�rZscpufreq)�ret�lsZpjoinrTZcurrZmax_Zmin_r:r:r;�cpu_freq�s&


r�c@seZdZdS)�_Ipv6UnsupportedErrorN)r7r8r9r:r:r:r;r��sr�c@sZeZdZdZdd�Zdd�Zdd�Zedd	��Zeddd��Z	edd
d��Z
ddd�Zd
S)�ConnectionsawA wrapper on top of /proc/net/* files, retrieving per-process
    and system-wide open connections (TCP, UDP, UNIX) similarly to
    "netstat -an".

    Note: in case of UNIX sockets we're only able to determine the
    local endpoint/path, not the one it's connected to.
    According to [1] it would be possible but not easily.

    [1] http://serverfault.com/a/417946
    cCs�dtjtjf}dtjtjf}dtjtjf}dtjtjf}dtjdf}|||||f||f|f|f||f|f|f|f||||f||f||fd�|_d|_dS)N�tcp�tcp6�udp�udp6�unix)�allr��tcp4r�r��udp4r�r��inetZinet4Zinet6)�socket�AF_INET�SOCK_STREAM�AF_INET6Z
SOCK_DGRAMZAF_UNIX�tmap�_procfs_path)�selfr�r�r�r�r�r:r:r;�__init__�s"
zConnections.__init__cCs�tt�}x�tjd|j|f�D]�}ytd|j||f�}WnJtk
r�}z.|jtjtj	fkrbwn|jtj
krrwn�WYdd}~XqX|jd�r|dd�dd�}||j|t
|�f�qW|S)Nz%s/%s/fdz%s/%s/fd/%szsocket:[r�r���)r�listrt�listdirr�ru�OSError�errno�ENOENT�ESRCH�EINVALr�r�r�)r��pid�inodesrU�inoder�r:r:r;�get_proc_inodes�s
zConnections.get_proc_inodescCsli}xbt�D]X}y|j|j|��Wqtk
rb}z"|jtjtjtjtjfkrR�WYdd}~XqXqW|S)N)	�pids�updater�r�r�r�r��EPERM�EACCES)r�r�r�r�r:r:r;�get_all_inodes�szConnections.get_all_inodesc
Cs�|jd�\}}t|d�}|s fStr.|jd�}|tjkrntrZtj|tj	|�ddd��}q�tj|tj	|��}nxtj	|�}yJtr�tjtj
tjd	tj
d|����}n tjtj
tjd
tj
d|����}Wn"tk
r�t�s�t�n�YnXtj||�S)a�Accept an "ip:port" address as displayed in /proc/net/*
        and convert it into a human readable form, like:

        "0500000A:0016" -> ("10.0.0.5", 22)
        "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)

        The IP address portion is a little or big endian four-byte
        hexadecimal number; that is, the least significant byte is listed
        first, so we need to reverse the order of the bytes to convert it
        to an IP address.
        The port is represented as a two-byte hexadecimal number.

        Reference:
        http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
        �:��asciiNr�>4I�<4Ir�)r�)r�)rvr�r�encoder�r��
LITTLE_ENDIANZ	inet_ntop�base64Z	b16decoder��struct�pack�unpackr�rr�r�addr)r�familyZipZportr:r:r;�decode_address
s0



zConnections.decode_addressNccsF|jd�rtjj|�rdSt|td���}|j��xt|d�D]�\}}y(|j�dd�\
}}	}
}}}}}}}Wn&t	k
r�t
d|||f��YnX||kr�||d\}
}nd	\}
}|dk	r�||
kr�qBqB|tjkr�t
|}ntj}ytj|	|�}	tj|
|�}
Wntk
�rwBYnX||||	|
||
fVqBWWdQRXdS)
z.Parse /proc/net/tcp* and /proc/net/udp* files.�6N)�	bufferingrrsz,error while parsing %s; malformed line %s %rrr�)Nr�)rwrtrT�existsrl�BIGFILE_BUFFERINGr��	enumeratervr��RuntimeErrorr�r��TCP_STATUSESr�	CONN_NONEr�rr�)�filer�type_r��
filter_pidr��linenor�r��laddr�raddr�statusr�r�rUr:r:r;�process_inetDs2(

zConnections.process_inetccst|td���}|j�x�|D]�}|j�}y|dd�\}}}}}}}	Wn.tk
rtd|kr`wtd||f��YnX|	|kr�||	}
ndg}
xd|
D]\\}}|dk	r�||kr�q�q�t|�dkr�|d}
nd	}
t|�}d	}tj	}||||
|||fVq�WqWWdQRXdS)
zParse /proc/net/unix files.)rr�raz)error while parsing %s; malformed line %rNrr��r�)Nr�r�)
rlrr�rvr�r	r�r�rr)rrr�rr�r��tokensr�r
r�Zpairsr�rUrTrrr:r:r;�process_unixls2


zConnections.process_unixc
Cs"||jkr,td|djdd�|jD��f��t�|_|dk	rP|j|�}|sXgSn|j�}t�}x�|j|D]�\}}}|tj	tj
fkr�|jd|j|f||||d�}n|jd|j|f|||d�}xT|D]L\}	}}}
}}}
|r�t
j|	|||
||�}nt
j|	|||
|||
�}|j|�q�WqjWt|�S)Nz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr:)�repr)r�rCr:r:r;r��sz(Connections.retrieve.<locals>.<listcomp>z	%s/net/%s)r)r�r�r�rqr�r�r��setr�r�r�rrrZpconnZsconn�addr�)r��kindr�r�r�r�rr
r�rUrrrZ	bound_pidZconnr:r:r;�retrieve�s4

zConnections.retrieve)N)N)N)r7r8r9�__doc__r�r�r��staticmethodrrrrr:r:r:r;r��s
7'%r�r�cCs
tj|�S)z$Return system-wide open connections.)�_connectionsr)rr:r:r;�net_connections�sr cCs�tdt���}|j�}WdQRXi}x�|dd�D]x}|jd�}|d|�j�}||dd�j�j�}tt|�\}}}	}
}}}
}}}}}}}}}|||||	||
|f||<q4W|S)zsReturn network I/O statistics for every network interface
    installed on the system as a dict of raw tuples.
    z
%s/net/devNr5r�r)rlrq�	readlines�rfindr�rv�mapr�)r��lines�retdictr�Zcolon�namer�Z
bytes_recvZpackets_recvZerrinZdropinZfifoinZframeinZcompressedinZmulticastinZ
bytes_sentZpackets_sentZerroutZdropoutZfifooutZ
collisionsoutZ
carrieroutZ
compressedoutr:r:r;�net_io_counters�s
*r'cCsptjttjttjti}t�j�}i}xF|D]>}t	j
|�}t	j|�}tj|�\}}t
j|||||�||<q*W|S)z)Get NIC stats (isup, duplex, speed, mtu).)r�ZDUPLEX_FULLrZDUPLEX_HALFrZDUPLEX_UNKNOWNrr'�keys�
cext_posixZ
net_if_mtuZnet_if_flagsZnet_if_duplex_speedrZ	snicstats)Z
duplex_map�namesr�r&ZmtuZisupZduplexZspeedr:r:r;�net_if_stats�s




r+cCs`dd�}i}|�}tdt���}|j�}WdQRX�x$|D�]}|j�}t|�}|dkr�|d}t|d�}	tt|dd	��\
}
}}}
}}}}}}n�|d	kr�|d}tt|dd	��\}	}
}}}
}}}}}}nN|d
k�r|d}tt|dd��\}	}}
}d}}}
}}ntd|��||kr<t|�}||9}||9}|	|
|||||
||f	||<q<W|S)
zcReturn disk I/O statistics for every disk installed on the
    system as a dict of raw tuples.
    cSs�g}tdt���}|j�dd�}WdQRXxXt|�D]L}|j�\}}}}|dj�rd|j|�q8|sz|dj|�r8|j|�q8W|S)Nz
%s/partitionsr5rr�r�)rlrqr!�reversedrv�isdigitr�r�)�
partitionsr�r$r�r�r&r:r:r;�get_partitions�sz(disk_io_counters.<locals>.get_partitionsz%s/diskstatsN�rr5r�rrz!not sure how to interpret line %r)	rlrqr!rvr�r�r#r�r�)r/r%r.r�r$r�r�Z
fields_lenr&ZreadsZreads_mergedZrbytesZrtimeZwritesZ
writes_mergedZwbytesZwtimer�rRZssizer:r:r;�disk_io_counters�s6(*
r2Fc
Cs�t�}tdt���V}xN|D]F}|j�}|jd�sB|j|j��q|jd�d}|dkr|jd�qWWdQRXg}tj�}xT|D]L}|\}}	}}
|dkr�d}|s�|dks�||kr�q�t	j
||	||
�}|j|�q�W|S)	z8Return mounted disk partitions as a list of namedtuples.z%s/filesystemsZnodev�	rZzfsNZnoner)rrlrqr�r�rrvr��disk_partitionsrZ	sdiskpartr�)r�Zfstypesr�r�Zfstype�retlistr.r�ZdeviceZ
mountpointZopts�ntupler:r:r;r4?s*


r4c	Cs.tjt�}tjd�}|jtjd��ttdd�|D���}x�|D]�}ytt|d��d}Wn8t	t
fk
r�}ztjd|t
�w@WYdd}~XnXttjjtjj|�d	�d
d�}t|ddd
�}t|ddd
�}t|ddd
d�}|dk	r�t|�d}|dk	�rt|�d}||j||||f�q@W|S)a�Return hardware (CPU and others) temperatures as a dict
    including hardware name, label, current, max and critical
    temperatures.

    Implementation notes:
    - /sys/class/hwmon looks like the most recent interface to
      retrieve this info, and this implementation relies on it
      only (old distros will probably use something else)
    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
    - /sys/class/thermal/thermal_zone* is another one but it's more
      difficult to parse
    z/sys/class/hwmon/hwmon*/temp*_*z&/sys/class/hwmon/hwmon*/device/temp*_*cSsg|]}|jd�d�qS)r�r)rv)r�rCr:r:r;r�ssz(sensors_temperatures.<locals>.<listcomp>�_inputg@�@zignoring %rNr&F)r�Z_max)r�Z_crit�_labelr)r�r�)�collectionsrr�r��extend�sortedrr�r�r�r�r�r�r�rtrTr��dirnamer�)	r��	basenames�base�currentr��	unit_nameZhighZcritical�labelr:r:r;�sensors_temperatures`s*



rBcCs�tjt�}tjd�}|s"tjd�}ttdd�|D���}x�|D]�}ytt|d��}Wn8tt	fk
r�}zt
jd|t�w>WYdd}~XnXtt
jjt
jj|�d�d	d
�}t|ddd	d
�}||jtj||��q>Wt|�S)a�Return hardware fans info (for CPU and other peripherals) as a
    dict including hardware label and current speed.

    Implementation notes:
    - /sys/class/hwmon looks like the most recent interface to
      retrieve this info, and this implementation relies on it
      only (old distros will probably use something else)
    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
    z/sys/class/hwmon/hwmon*/fan*_*z%/sys/class/hwmon/hwmon*/device/fan*_*cSsg|]}|jd�d�qS)r�r)rv)r�rCr:r:r;r��sz sensors_fans.<locals>.<listcomp>r7zignoring %rNr&F)r�r8r)r�r�)r9rr�r�r;rr�r�r�r�r�r�r�rtrTr�r<r�rZsfan�dict)r�r=r>r?r�r@rAr:r:r;�sensors_fans�s 




rDc
s�t���fdd�}tjjtd�}tjj|�s0dS||d|d�}||d|d�}||d	|d
�}|dksv|dkrzdS|dk	r�yd||}Wq�tk
r�d}Yq�Xn tt|d
dd��}|dkr�dSd}|tjjtd�tjjtd��}|dk	�r|dk}n4t|dddd�j	�}|dk�r*d}n|dk�r8d}|�rFt
j}	n2yt||d�}	Wntk
�rvt
j}	YnXt
j
||	|�S)aReturn battery information.
    Implementation note: it appears /sys/class/power_supply/BAT0/
    directory structure may vary and provide files with the same
    meaning but under different names, see:
    https://github.com/giampaolo/psutil/issues/966
    cs:x4|D],}t|�d�}|�kr|j�r.t|�S|SqWdS)zvAttempt to read the content of multiple files which may
        not exist. If none of them exist return None.
        )r�N)r�r-r�)�pathsrTr�)�nullr:r;�	multi_cat�s

z"sensors_battery.<locals>.multi_catZBAT0Nz/energy_nowz/charge_nowz
/power_nowz/current_nowz/energy_fullz/charge_fullgY@gz	/capacityr)r�z
AC0/onlinez	AC/onlinez/statusrF)r�r�Zdischarging�charging�fullTir�r�)rHrI)�objectrtrTr��POWER_SUPPLY_PATHr�ZeroDivisionErrorr�r�r�rZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)
rG�rootZ
energy_nowZ	power_nowZenergy_fullrIZ
power_pluggedZonlinerZsecsleftr:)rFr;�sensors_battery�sT







rNc
Cs`g}tj�}xN|D]F}|\}}}}}}|s,q|dkr8d}tj||pDd|||�}	|j|	�qW|S)z:Return currently connected users as a list of namedtuples.�:0.0�:0Z	localhostN)rOrP)r��usersrZsuserr�)
r5Zrawlist�itemr�ZttyZhostnameZtstampZuser_processr��ntr:r:r;rQs
rQcCsbdt�}t|��F}x2|D]*}|jd�rt|j�j�d�}|a|SqWtd|��WdQRXdS)zAReturn the system boot time expressed in seconds since the epoch.z%s/statsbtimerzline 'btime' not found in %sN)rqrgr�r�r�rv�	BOOT_TIMEr	)rTr�r�r�r:r:r;�	boot_times



rUcCsdd�tjtt���D�S)z7Returns a list of PIDs currently running on the system.cSsg|]}|j�rt|��qSr:)r-r�)r�rCr:r:r;r�,szpids.<locals>.<listcomp>)rtr�rrqr:r:r:r;r�*sr�cCs�tj|�sdSybdt�|f}t|��B}x.|D]&}|jd�r.t|j�d�}||kSq.Wtd|��WdQRXWnttfk
r�|t	�kSXdS)zcCheck for the existence of a unix PID. Linux TIDs are not
    supported (always return False).
    Fz%s/%s/statussTgid:rz'Tgid' line not found in %sN)
r�
pid_existsrqrgr�r�rvr��EnvironmentErrorr�)r�rTr�r�Ztgidr:r:r;rV/s




rVc	Cs�i}t�}x�t�D]�}y(td||f��}|j�}WdQRXWn>tk
r|}z"|jtjtjtjtj	fkrl�WYdd}~XqX|j
d�}||dd�j�}t|d�}|||<qW|S)zsObtain a {pid: ppid, ...} dict for all running processes in
    one shot. Used to speed up Process.children().
    z
%s/%s/statN�)r5r)
rqr�rgr�rWr�r�r�r�r�r"rvr�)	r�r�r�r��datar��rparZdset�ppidr:r:r;�ppid_mapOs
r\cstj���fdd��}|S)zlDecorator which translates bare OSError and IOError exceptions
    into NoSuchProcess and AccessDenied.
    cs�y�|f|�|�Stk
r�}zv|jtjtjfkrBt|j|j��|jtjkr\t|j|j��|jtj	kr�t
jjd|j
|jf�r�t|j|j���WYdd}~XnXdS)Nz%s/%s)rWr�r�r�rr��_namer�rr�rtrTrr�)r��argsrfr�)�funr:r;�wrapperksz wrap_exceptions.<locals>.wrapper)�	functools�wraps)r_r`r:)r_r;�wrap_exceptionsgsrcc@sneZdZdZddddgZdd�Zedd	��Zed
d��Zedd
��Z	dd�Z
dd�Zedd��Z
dd�Zedd��Zedd��Zedd��Zejjdej��r�edd��Zndd�Zed d!��Zed"d#��Zed`d%d&��Zed'd(��Zed)d*��Ze�r"eejd+�ejd,�ejd-�fd.d/��ZneZe�r:ed0d1��Z nd2d1�Z ed3d4��Z!eejd5�fd6d7��Z"eejd8�fd9d:��Z#ed;d<��Z$ed=d>��Z%ed?d@��Z&edAdB��Z'ejdC�fdDdE�Z(edFdG��Z)e*e+dH��r�edIdJ��Z,edKdL��Z-e.�redadMdN��Z/edOdP��Z0edQdR��Z1edbdTdU��Z2edVdW��Z3edXdY��Z4eejdZ�fd[d\��Z5eejd]�fd^d_��Z6d$S)c�ProcesszLinux process implementation.r�r]�_ppidr�cCs||_d|_d|_t�|_dS)N)r�r]rerqr�)r�r�r:r:r;r��szProcess.__init__c
Csftd|j|jf��}|j�}WdQRX|jd�}||jd�d|�}||dd�j�}|g|S)a{Parse /proc/{pid}/stat file. Return a list of fields where
        process name is in position 0.
        Using "man proc" as a reference: where "man proc" refers to
        position N, always substract 2 (e.g starttime pos 22 in
        'man proc' == pos 20 in the list returned here).
        The return value is cached in case oneshot() ctx manager is
        in use.
        z
%s/%s/statNrX�(rr5)rgr�r�r�r"�findrv)r�r�rYrZr&Zothersr:r:r;�_parse_stat_file�s

zProcess._parse_stat_filec	Cs(td|j|jf��
}|j�SQRXdS)z�Read /proc/{pid}/stat file and return its content.
        The return value is cached in case oneshot() ctx manager is
        in use.
        z%s/%s/statusN)rgr�r�r�)r�r�r:r:r;�_read_status_file�szProcess._read_status_filec	Cs0td|j|jftd��}|j�j�SQRXdS)Nz%s/%s/smaps)r)rgr�r�rr�r�)r�r�r:r:r;�_read_smaps_file�s
zProcess._read_smaps_filecCs"|jj�|jj�|jj�dS)N)rhZcache_activaterirj)r�r:r:r;�
oneshot_enter�s

zProcess.oneshot_entercCs"|jj�|jj�|jj�dS)N)rhZcache_deactivaterirj)r�r:r:r;�oneshot_exit�s

zProcess.oneshot_exitcCs|j�d}trt|�}|S)Nr)rhrrm)r�r&r:r:r;r&�szProcess.namecCs�ytd|j|jf�Stk
r�}z�|jtjtjfkr�tjj	d|j|jf�rTdSt
|j�snt|j|j��nt
|j|j|j��|jtjtjfkr�t|j|j���WYdd}~XnXdS)Nz	%s/%s/exez%s/%sr)rur�r�r�r�r�r�rtrT�lexistsrVrr]rrer�r�r)r�r�r:r:r;�exe�s
zProcess.exec
Csltd|j|jf��}|j�}WdQRX|s0gS|jd�r>dnd}|j|�rX|dd�}dd�|j|�D�S)Nz
%s/%s/cmdlinerrrarcSsg|]}|�qSr:r:)r�rCr:r:r;r��sz#Process.cmdline.<locals>.<listcomp>r�)rlr�r�r�rwrv)r�r�rY�sepr:r:r;�cmdline�s
zProcess.cmdlinec	Cs0td|j|jf��}|j�}WdQRXt|�S)Nz
%s/%s/environ)rlr�r�r�r)r�r�rYr:r:r;�environ�szProcess.environcCs:t|j�d�}tj�}y||Stk
r4dSXdS)N�)r�rhrZget_terminal_mapr�)r�Ztty_nrr�r:r:r;�terminal�szProcess.terminalz/proc/%s/iocCs�d|j|jf}i}t|��:}x2|D]*}|j�}|r$|jd�\}}t|�||<q$WWdQRX|sltd|��t|d|d|d|d|d|d	�S)
Nz%s/%s/ios: z%s file was emptyssyscrssyscws
read_bytesswrite_bytessrcharswchar)r�r�rgr�rvr�r	rb)r�rer�r�r�r&r�r:r:r;�io_counters�s"

zProcess.io_counterscCstd|j��dS)Nz+couldn't find /proc/%s/io (kernel too old?))r�r�)r�r:r:r;rtscCsX|j�}t|d�t}t|d�t}t|d�t}t|d�t}tj||||�S)N��
r1r0)rhr�r�rZ	pcputimes)r�r��utime�stimeZchildren_utimeZchildren_stimer:r:r;r�szProcess.cpu_timescCst|j�d�S)zWhat CPU the process is on.�%)r�rh)r�r:r:r;�cpu_numszProcess.cpu_numNcCstj|j||j�S)N)rZwait_pidr�r])r�Ztimeoutr:r:r;�waitszProcess.waitcCs&|j�}tpt�}t|d�t|S)N�)rhrTrUr�r�)r�r�Zbtr:r:r;�create_time"s
zProcess.create_timec	Cs`td|j|jf��2}dd�|j�j�dd�D�\}}}}}}}WdQRXt|||||||�S)Nz%s/%s/statmcSsg|]}t|�t�qSr:)r�r�)r�rCr:r:r;r�<sz'Process.memory_info.<locals>.<listcomp>r)rgr�r�r�rvrX)	r�r�Zvmsr^rP�text�librYZdirtyr:r:r;�memory_info-s
6zProcess.memory_infosPrivate.*:\s+(\d+)sPss.*:\s+(\d+)sSwap.*:\s+(\d+)c	Csj|j�}|j�}ttt|j|���d}ttt|j|���d}ttt|j|���d}t||||f�S)Ni)r�rjr�r#r��findallrY)	r�Z_private_reZ_pss_reZ_swap_reZ	basic_memZ
smaps_datarZr[r\r:r:r;�memory_full_infoCs
zProcess.memory_full_infocCsXdd�}|j�}|sgS|jd�}g}|jd�}|g}�x|||�D�]
\}}|jdd�}y|\}	}
}}}
}Wn*tk
r�|dg\}	}
}}}
}YnX|s�d}n4tr�t|�}|j�}|jd	�r�t|�r�|dd�}|j	t|	�t|
�||d|j
dd�|j
d
d�|j
dd�|j
dd�|j
dd�|j
dd�|j
dd�|j
dd�|j
dd�f
�qDW|S)z�Return process's mapped memory regions as a list of named
            tuples. Fields are explained in 'man proc'; here is an updated
            (Apr 2012) version: http://goo.gl/fmebo
            css�i}x�|D]�}|jdd�}|djd�sB|j�|fV|j|�q
yt|d�d||d<Wq
tk
r�|djd�r�w
ntd|��Yq
Xq
W|j�|fVdS)Nrrr�:risVmFlags:z#don't know how to interpret line %r)rvrw�popr�r�r�r�)r$�
current_blockrYr�r�r:r:r;�
get_blocksis
z'Process.memory_maps.<locals>.get_blocks�
rNrrrz[anon]z
 (deleted)rssRss:sSize:sPss:s
Shared_Clean:s
Shared_Dirty:sPrivate_Clean:sPrivate_Dirty:sReferenced:s
Anonymous:sSwap:i����)rjrvr�r�rrmr�rwrr�r�)r�r�rYr$r�Z
first_liner��headerZhfieldsrZperms�offsetZdevr�rTr:r:r;�memory_mapscsF











zProcess.memory_mapscCstd|j��dS)Nzn/proc/%s/smaps does not exist on kernels < 2.6.14 or if CONFIG_MMU kernel configuration option is not enabled.)r�r�)r�r:r:r;r��scCs|ytd|j|jf�Stk
rv}zF|jtjtjfkrdt|j�sRt|j|j	��nt
|j|j	|j���WYdd}~XnXdS)Nz	%s/%s/cwd)rur�r�r�r�r�r�rVrr]rre)r�r�r:r:r;�cwd�s
zProcess.cwdsctxt_switches:\t(\d+)cCsL|j�}|j|�}|s,td|j|jf��ntjt|d�t|d��SdS)Nz�'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'lines were not found in %s/%s/status; the kernel is probably older than 2.6.23rr)rir�r�r�r�rZpctxswr�)r�Z	_ctxsw_rerYZctxswr:r:r;�num_ctx_switches�s
zProcess.num_ctx_switchessThreads:\t(\d+)cCs|j�}t|j|�d�S)Nr)rir�r�)r�Z_num_threads_rerYr:r:r;�num_threads�szProcess.num_threadsc
Cstjd|j|jf�}|j�g}d}x�|D]�}d|j|j|f}y$t|��}|j�j�}WdQRXWn6tk
r�}z|j	t	j
kr�d}w,�WYdd}~XnX||jd�dd�}|jd�}	t
|	d�t}
t
|	d	�t}tjt|�|
|�}|j|�q,W|�rtjd
|j|jf�|S)Nz
%s/%s/taskFz%s/%s/task/%s/statTrXr5r��ruz%s/%s)rtr�r�r�r�rgr�r�r�r�r�rgrvr�r�rZpthreadr�r��stat)
r�Z
thread_idsr5�
hit_enoentZ	thread_idrer��str�r�rwrxr6r:r:r;�threads�s0


zProcess.threadscCstj|j�S)N)r)�getpriorityr�)r�r:r:r;�nice_get�szProcess.nice_getcCstj|j|�S)N)r)�setpriorityr�)r�r�r:r:r;�nice_set�szProcess.nice_setcCstj|j�S)N)r�Zproc_cpu_affinity_getr�)r�r:r:r;�cpu_affinity_get�szProcess.cpu_affinity_getsCpus_allowed_list:\t(\d+)-(\d+)cCsV|j�}|j|�}|r@ttt|dd�t|dd�d��Stttt����SdS)Nrr)rir�r��ranger�r�r�)r�Z_rerYr�r:r:r;�_get_eligible_cpus�s

*zProcess._get_eligible_cpuscCs�ytj|j|�Wn�ttfk
r�}zvt|t�s>|jtjkr�|j�}t	t
tt����}x<|D]4}||krztd||f��||kr^td||f��q^W�WYdd}~XnXdS)Nz(invalid CPU number %r; choose between %sz0CPU number %r is not eligible; choose between %s)
r�Zproc_cpu_affinity_setr�r�r��
isinstancer�r�r��tupler�r�r�)r�r�r�Z
eligible_cpusZall_cpusZcpur:r:r;�cpu_affinity_sets 
zProcess.cpu_affinity_set�proc_ioprio_getcCs,tj|j�\}}tdk	r t|�}tj||�S)N)r�r�r��enumr6rZpionice)r��ioclassr�r:r:r;�
ionice_getszProcess.ionice_getcCs�|dk	rNtr.t|ttf�r.d|}t|��d|ko@dknsNtd��|tdfkrx|rnd|}t|��t}d}nH|tkr�|r�d|}t|��d}n&|tt	fkr�|dkr�d}ntd|��t
j|j||�S)	Nz)value argument is not an integer (gor %r)rrz0value argument range expected is between 0 and 7z3can't specify value with IOPRIO_CLASS_NONE (got %r)z3can't specify value with IOPRIO_CLASS_IDLE (got %r)rzinvalid ioclass argument %r)
rr�r�r�	TypeErrorr�r r#r!r"r�Zproc_ioprio_setr�)r�r�r�r�r:r:r;�
ionice_set%s2zProcess.ionice_setcCs�|jdkrtd��yP|dkr*tj|j|�St|�dkrFtdt|���|\}}tj|j|||�WnNtk
r�}z2|jtjkr�t	|j�r�t
|j|j|j��n�WYdd}~XnXdS)Nrz)can't use prlimit() against PID 0 processr5z4second argument must be a (soft, hard) tuple, got %s)
r�r�r�r/r�rr�r�ZENOSYSrVrr]re)r�ZresourceZlimitsZsoftZhardr�r:r:r;�rlimitGs
zProcess.rlimitcCs$|j�d}tr|j�}tj|d�S)Nr�?)rhrrm�
PROC_STATUSESr�)r�Zletterr:r:r;rbszProcess.statusc
Cs�g}tjd|j|jf�}d}�xH|D�]>}d|j|j|f}yt|�}WnNtk
r�}z2|jtjtjfkrvd}w&n|jtj	kr�w&n�WYdd}~Xq&X|j
d�o�t|�r&d|j|j|f}yBt|��0}t
|j�j�d�}	t
|j�j�dd�}
WdQRXWn:tk
�r:}z|jtjk�r(d}n�WYdd}~Xq&Xt|
�}t|t
|�t
|	�||
�}|j|�q&W|�r�tjd	|j|jf�|S)
Nz%s/%s/fdFz%s/%s/fd/%sT�/z%s/%s/fdinfo/%srr�z%s/%s)rtr�r�r�rur�r�r�r�r�r�rrgr�r�rvr�r�rSr�r�)
r�r5�filesr�rUrrTr�r��posrWrVr6r:r:r;�
open_filesjs@
$zProcess.open_filesr�cCs(tj||j�}tjd|j|jf�|S)Nz%s/%s)rrr�rtr�r�)r�rr�r:r:r;�connections�szProcess.connectionscCsttjd|j|jf��S)Nz%s/%s/fd)r�rtr�r�r�)r�r:r:r;�num_fds�szProcess.num_fdscCst|j�d�S)Nr5)r�rh)r�r:r:r;r[�szProcess.ppidsUid:\t(\d+)\t(\d+)\t(\d+)cCs6|j�}|j|�d\}}}tjt|�t|�t|��S)Nr)rir�rZpuidsr�)r�Z_uids_rerY�real�	effective�savedr:r:r;�uids�szProcess.uidssGid:\t(\d+)\t(\d+)\t(\d+)cCs6|j�}|j|�d\}}}tjt|�t|�t|��S)Nr)rir�rZpgidsr�)r�Z_gids_rerYr�r�r�r:r:r;�gids�szProcess.gids)N)N)r�)7r7r8r9r�	__slots__r�rrhrirjrkrlrcr&rnrprqrsrtrTr�getpidrtr�rzr{r}r��	HAS_SMAPSr�r�r�r�r�r�r�r�r�r�r�r�r��hasattrr�r�r��HAS_PRLIMITr�rr�r�r�r[r�r�r:r:r:r;rd�st			B
		!2rd)rrr�)rZr[r\)r�)F)�rZ
__future__rr�r9r�rar�rtr�r�r�ro�	tracebackr�rrrrrrr�r	r)r
rrr
rrrrrrrrZ_compatrrrr�_exceptionsrrr�version_infor�Z__extra__all__rKrTrr�r�r�r�rJr��dirr&r�r�r�r�r�rTr�	byteorderr�r�Z	AF_PACKETr4�IntEnumr�r3r r!r"r#r6�globalsr��__members__ZSTATUS_RUNNINGZSTATUS_SLEEPINGZSTATUS_DISK_SLEEPZSTATUS_STOPPEDZSTATUS_TRACING_STOPZ
STATUS_ZOMBIEZSTATUS_DEADZSTATUS_WAKE_KILLZ
STATUS_WAKINGr�r$r%r&r'r(r)r*r+r,r-r.r
rFrQrSrXr�rYr]r�r`rbrgrlrmrqrur�r�r�r��	Exception�	print_excr�r�r�r�r�r�r�r�r�r�Znet_if_addrsr�r�rr r'r+Z
disk_usager2r4rBrDrNrQrUr�rVr\rcrdr:r:r:r;�<module>sH















5u:*q
%H
!1 T __pycache__/_common.cpython-36.pyc000064400000031666150466730540013057 0ustar003

��JZ�E�V@s.dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlm
Z
ddlmZddlmZddlmZddlmZydd	lmZWnek
r�dZYnXydd
lmZWnek
r�dZYnXe	jd�k�r�ddlZndZe	jddkZd
ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRgFZejdSkZejdTkZe	jjdU�Ze	jjdV�Ze	jjdW�Z e	jjdX�Z!e	jjdY�Z"e �p�e!�p�e"Z#e	jjdZ��pe	jjd[�Z$e	jjd\�Z%d]Z&d^Z'd_Z(d`Z)daZ*dbZ+dcZ,ddZ-deZ.dfZ/dgZ0dhZ1diZ2djZ3dkZ4dlZ5dmZ6dnZ7doZ8dpZ9dqZ:drZ;dsZ<dtZ=duZ>edk�r�dvZ?dwZ@dZAn Gdxdy�dyejB�ZCeD�jEeCjF�edk�r�d�ZGd�ZHn Gdzd{�d{ejB�ZIeD�jEeIjF�e	jJ�ZKe�s
d|ZLn2ye	jM�ZLWn$eNk
�r:e�r2d}nd|ZLYnXedFd~dd�d�d�d�g�ZOedBd~dd�d�g�ZPed@d�d�d�d�d�d�g�ZQedAd�d�d�d�g�ZRedCd�d�d�d�d�d�d�d�g�ZSedGd�d�d�d�d�g�ZTed>d�d�d�d�d�d�d�g�ZUedDd�d�d�d�d�g�ZVedEd�d�d�d�g�ZWed?d�d�d�d�g�ZXed�d�d�d�g�ZYed�d�d�d�d�g�ZZed�d�d�d�g�Z[ed�d�d�g�Z\ed6d�d�d�d�g�Z]ed;d�d�g�Z^ed<d�d�d�g�Z_ed=d�d�d�g�Z`ed8d�d�d�g�Zaed9d�d�d�d�g�Zbed:d�d�g�Zced7d�d�g�Zded5d�d�d�d�d�d�g�Zeed�d�d�g�Zfeeegeegfeegegfegegfeegegfegegfeegeegfegeegfegeegfd˜Zgedk	�r~egjEegegfegegfd̜�edk	�r�egjEd�egeegfi�[[[[d�d�dN�Zhd�dK�Zid�dфZjd�dJ�Zkd�dM�Zleid�dO��Zmd�dL�Znd�dP�Zod�dQ�Zpd�dI�ZqGd�dڄdڃZrd�dR�Zser�Ztetjues_uetjves_vdS)�z9Common objects shared by __init__.py and _ps*.py modules.�)�divisionN)�defaultdict)�
namedtuple)�AF_INET)�
SOCK_DGRAM)�SOCK_STREAM)�AF_INET6)�AF_UNIX���FREEBSD�BSD�LINUX�NETBSD�OPENBSD�OSX�POSIX�SUNOS�WINDOWS�ENCODING�
ENCODING_ERRSr�
CONN_CLOSE�CONN_CLOSE_WAIT�CONN_CLOSING�CONN_ESTABLISHED�CONN_FIN_WAIT1�CONN_FIN_WAIT2�
CONN_LAST_ACK�CONN_LISTEN�	CONN_NONE�
CONN_SYN_RECV�
CONN_SYN_SENT�CONN_TIME_WAIT�NIC_DUPLEX_FULL�NIC_DUPLEX_HALF�NIC_DUPLEX_UNKNOWN�STATUS_DEAD�STATUS_DISK_SLEEP�STATUS_IDLE�
STATUS_LOCKED�STATUS_RUNNING�STATUS_SLEEPING�STATUS_STOPPED�STATUS_SUSPENDED�STATUS_TRACING_STOP�STATUS_WAITING�STATUS_WAKE_KILL�
STATUS_WAKING�
STATUS_ZOMBIE�pconn�	pcputimes�pctxsw�pgids�pio�pionice�	popenfile�pthread�puids�sconn�	scpustats�sdiskio�	sdiskpart�
sdiskusage�snetio�snic�	snicstats�sswap�suser�	conn_tmap�deprecated_method�
isfile_strict�memoize�parse_environ_block�path_exists_strict�
usage_percent�
supports_ipv6�sockfam_to_enum�socktype_to_enum�wrap_numbers�posix�nt�linux�darwinZfreebsdZopenbsdZnetbsd�sunos�solaris�aixZrunningZsleepingz
disk-sleepZstoppedztracing-stopZzombieZdeadz	wake-killZwakingZidle�lockedZwaitingZ	suspendedZESTABLISHEDZSYN_SENTZSYN_RECVZ	FIN_WAIT1Z	FIN_WAIT2Z	TIME_WAITZCLOSEZ
CLOSE_WAITZLAST_ACKZLISTENZCLOSINGZNONE��c@seZdZdZdZdZdS)�	NicDuplexrYrZrN)�__name__�
__module__�__qualname__r#r$r%�r_r_�/usr/lib64/python3.6/_common.pyr[sr[c@seZdZdZdZdS)�BatteryTimerZrYN������)r\r]r^�POWER_TIME_UNKNOWN�POWER_TIME_UNLIMITEDr_r_r_r`ra�sra�replace�surrogateescape�total�usedZfreeZpercentZsinZsoutZ
read_countZwrite_countZ
read_bytesZwrite_bytesZ	read_timeZ
write_timeZdeviceZ
mountpointZfstypeZoptsZ
bytes_sentZ
bytes_recvZpackets_sentZpackets_recvZerrinZerroutZdropinZdropout�nameZterminal�hostZstarted�pid�fdZfamily�typeZladdrZraddrZstatusZaddressZnetmaskZ	broadcastZptpZisupZduplexZspeedZmtuZctx_switchesZ
interruptsZsoft_interruptsZsyscalls�scpufreqZcurrent�min�max�shwtempZlabelZhighZcritical�sbatteryZsecsleftZ
power_plugged�sfan�user�system�
children_user�children_system�path�idZ	user_timeZsystem_time�realZ	effectiveZsavedZioclass�valueZ	voluntaryZinvoluntary�addrZipZport)�allZtcpZtcp4ZudpZudp4ZinetZinet4Zinet6)Ztcp6Zudp6ZunixcCs\y||d}Wn0tk
r@t|t�s4t|t�r8dnd}YnX|dk	rTt||�S|SdS)z5Calculate percentage usage of 'used' against 'total'.�dgrN)�ZeroDivisionError�
isinstance�float�round)rirhZ_round�retr_r_r`rLs"
cs2tj����fdd��}�fdd�}i�||_|S)aA simple memoize decorator for functions supporting (hashable)
    positional arguments.
    It also provides a cache_clear() function for clearing the cache:

    >>> @memoize
    ... def foo()
    ...     return 1
        ...
    >>> foo()
    1
    >>> foo.cache_clear()
    >>>
    csH|tt|j���f}y�|Stk
rB�||�}�|<|SXdS)N)�	frozenset�sorted�items�KeyError)�args�kwargs�keyr�)�cache�funr_r`�wrapper"szmemoize.<locals>.wrappercs�j�dS)zClear cache.N)�clearr_)r�r_r`�cache_clear+szmemoize.<locals>.cache_clear)�	functools�wrapsr�)r�r�r�r_)r�r�r`rIs
	csNtj�����fdd����fdd�}��fdd�}i�d�_|�_|�_�S)a�A memoize decorator which is disabled by default. It can be
    activated and deactivated on request.
    For efficiency reasons it can be used only against class methods
    accepting no arguments.

    >>> class Foo:
    ...     @memoize
    ...     def foo()
    ...         print(1)
    ...
    >>> f = Foo()
    >>> # deactivated (default)
    >>> foo()
    1
    >>> foo()
    1
    >>>
    >>> # activated
    >>> foo.cache_activate()
    >>> foo()
    1
    >>> foo()
    >>> foo()
    >>>
    csH�js�|�Sy��}Wn$tk
r>�|�}��<YnX|SdS)N)�cache_activatedr�)�selfr�)r�r�r�r_r`r�Nsz'memoize_when_activated.<locals>.wrappercs
d�_dS)zActivate cache.TN)r�r_)r�r_r`�cache_activateYsz.memoize_when_activated.<locals>.cache_activatecsd�_�j�dS)zDeactivate and clear cache.FN)r�r�r_)r�r�r_r`�cache_deactivate]sz0memoize_when_activated.<locals>.cache_deactivateF)r�r�r�r�r�)r�r�r�r_)r�r�r�r`�memoize_when_activated4sr�cCsTytj|�}Wn4tk
rB}z|jtjtjfkr4�dSd}~XnXtj|j�SdS)z�Same as os.path.isfile() but does not swallow EACCES / EPERM
    exceptions, see:
    http://mail.python.org/pipermail/python-dev/2012-June/120787.html
    FN)�os�stat�OSError�errno�EPERM�EACCES�S_ISREG�st_mode)ry�st�errr_r_r`rHiscCsLytj|�Wn4tk
rB}z|jtjtjfkr4�dSd}~XnXdSdS)z�Same as os.path.exists() but does not swallow EACCES / EPERM
    exceptions, see:
    http://mail.python.org/pipermail/python-dev/2012-June/120787.html
    FNT)r�r�r�r�r�r�)ryr�r_r_r`rKxscCsbtjstdkrdSy2tjttj�}tj|��|jd�WdQRXdStjk
r\dSXdS)z2Return True if IPv6 is supported on this platform.NF�::1rT)r�r)�socketZhas_ipv6rr�
contextlib�closingZbind�error)Zsockr_r_r`rM�scCszi}d}t}xh|jd|�}||kr$P|jd||�}||krj|||�}||d|�}|rb|j�}|||<|d}qW|S)zCParse a C environ block of environment variables into a dictionary.r��=rZ)r�find�upper)�datar��posZWINDOWS_Znext_posZ	equal_posr�r|r_r_r`rJ�s cCs4tdkr|Sy
tj|�Sttfk
r.|SXdS)z�Convert a numeric socket family value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    N)�enumr�Z
AddressFamily�
ValueError�AttributeError)�numr_r_r`rN�s
cCs4tdkr|Sy
tj|�Sttfk
r.|SXdS)zConvert a numeric socket type value to an IntEnum member.
    If it's not a known member, return the numeric value itself.
    N)r�r�ZAddressTyper�r�)r�r_r_r`rO�s
cs�fdd�}|S)z�A decorator which can be used to mark a method as deprecated
    'replcement' is the method name which will be called instead.
    cs:d|j�f�|jdkr�|_tj|���fdd��}|S)Nz8%s() is deprecated and will be removed; use %s() insteadcs tj�tdd�t|��||�S)NrY)�category�
stacklevel)�warnings�warn�
FutureWarning�getattr)r�r�r�)�msg�replacementr_r`�inner�sz/deprecated_method.<locals>.outer.<locals>.inner)r\�__doc__r�r�)r�r�)r�)r�r`�outer�s
z deprecated_method.<locals>.outerr_)r�r�r_)r�r`rG�sc@sBeZdZdZdd�Zdd�Zdd�Zdd	�Zddd�Zd
d�Z	d
S)�_WrapNumberszNWatches numbers so that they don't overflow and wrap
    (reset to zero).
    cCs tj�|_i|_i|_i|_dS)N)�	threadingZLock�lockr��	reminders�
reminder_keys)r�r_r_r`�__init__�s
z_WrapNumbers.__init__cCsT||jkst�||jkst�||jks*t�||j|<tt�|j|<tt�|j|<dS)N)r��AssertionErrorr�r�r�int�set)r��
input_dictrjr_r_r`�	_add_dict�s
z_WrapNumbers._add_dictcCsd|j|}t|j��t|j��}x<|D]4}x"|j||D]}|j||=q<W|j||=q(WdS)z�In case the number of keys changed between calls (e.g. a
        disk disappears) this removes the entry from self.reminders.
        N)r�r��keysr�r�)r�r�rj�old_dictZ	gone_keysZgone_key�remkeyr_r_r`�_remove_dead_reminders�s

z#_WrapNumbers._remove_dead_remindersc
Cs||jkr|j||�|S|j||�|j|}i}x�|j�D]�}||}y||}Wntk
rt|||<w>YnXg}xvtt|��D]f}	||	}
||	}||	f}|
|kr�|j|||7<|j||j	|�|j
|
|j||�q�Wt|�||<q>W||j|<|S)zkCache dict and sum numbers which overflow and wrap.
        Return an updated copy of `input_dict`
        )r�r�r�r�r��range�lenr�r��add�append�tuple)
r�r�rjr�Znew_dictr�Zinput_tupleZ	old_tuple�bits�iZinput_valueZ	old_valuer�r_r_r`�run�s2


z_WrapNumbers.runNc
Csh|j�X|dkr0|jj�|jj�|jj�n*|jj|d�|jj|d�|jj|d�WdQRXdS)z>Clear the internal cache, optionally only for function 'name'.N)r�r�r�r�r��pop)r�rjr_r_r`r�"s

z_WrapNumbers.cache_clearc
Cs"|j�|j|j|jfSQRXdS)z5Return internal cache dicts as a tuple of 3 elements.N)r�r�r�r�)r�r_r_r`�
cache_info.sz_WrapNumbers.cache_info)N)
r\r]r^r�r�r�r�r�r�r�r_r_r_r`r��s'
r�c
Cstj�tj||�SQRXdS)z�Given an `input_dict` and a function `name`, adjust the numbers
    which "wrap" (restart from zero) across different calls by adding
    "old value" to "new value" and return an updated dict.
    N)�_wnr�r�)r�rjr_r_r`rP4s)r
rrbrc)N)wr�Z
__future__rr�r�r�r�r�r��sysr�r��collectionsrrrrrr�ImportErrorr	�version_infor�ZPY3�__all__rjrr�platform�
startswithrrrrrr
rZAIXr*r+r'r,r.r2r&r0r1r(r)r/r-rr!r rrr"rrrrrrr#r$r%�IntEnumr[�globals�update�__members__rdrera�getfilesystemencodingrr�getfilesystemencodeerrorsr�rDr@r>r?rArEr<rBrCr=rorrrsrtr4r9r:r;r6r7r8r5r3r}rFrLrIr�rHrKrMrJrNrOrGr�rPr�r�r�r_r_r_r`�<module>sH


	

	






	





 5

W	__pycache__/_psbsd.cpython-36.pyc000064400000045340150466730540012674 0ustar003

��JZ$v�@sldZddlZddlZddlZddlZddljjZddl	m
Z
ddlmZddl
mZddl
mZddl
mZdd	l
mZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!ddl m"Z"ddl m#Z#gZ$e�rhej%ej&ej'ej(ej)ej*ej+ej,ej-ej.ej/ej0ej1ej2iZ3n�e�ste�r�ej%ej&ej)ej*ej+ej,ej4ej.ej-ej.ej'ej5ej6ej(iZ3nBe�r�ej%ej&ej7ej(ej8ej.ej+ej,ej-ej.ej4ej9ej:ej;iZ3ej<ej=ej>ej?ej@ejAejBejCejDejEejFejGejHejIejJejKejLejMejNejOejPejQejRejSiZTe�rjejUd�ZVn
ejUd�ZVejWZWeXddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1�ZYe
d2d3d4d5d6d7d8d9d:d;d<d=g�ZZe
d>d?d@dAdBdCg�Z[e
dDdEdFdGdHdIg�Z\e\Z]e
dJd?dAdKdLg�Z^e
dMdN�Z_e
dOdP�Z`e�rFe
dQdRdSdTdUdVdWdXg�Zane
dQdRdSdTdUg�ZadYdZ�Zbd[d\�Zcd]d^�Zdeeed_��r�d`d_�Zfndad_�Zfdbef_gdcdd�Zhe�s�e�r�dedf�Zindgdf�Zidhdi�Zjd�djdk�ZkejlZlejmZmejnZnejoZodldm�Zpdndo�Zqe�rdpdq�Zrdrds�Zsdtdu�Ztedvdw��Zudxdy�Zve�s2e�r<dzd{�ZwnejwZwd|d}�Zxejyd~d��ZzGd�d��d�e{�Z|dS)�z5FreeBSD, OpenBSD and NetBSD platforms implementation.�N)�
namedtuple)�AF_INET�)�_common)�_psposix)�_psutil_bsd)�
_psutil_posix)�AF_INET6)�	conn_tmap)�FREEBSD)�memoize)�memoize_when_activated)�NETBSD)�OPENBSD)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�which)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�SC_PAGESIZE�SC_PAGE_SIZE��������	�
���
�����������)�ppid�status�real_uid�
effective_uid�	saved_uid�real_gid�
effective_gid�	saved_gid�ttynr�create_time�ctx_switches_vol�ctx_switches_unvol�
read_io_count�write_io_count�	user_time�sys_time�ch_user_time�ch_sys_time�rss�vms�memtext�memdata�memstack�cpunum�name�svmem�totalZ	available�percent�used�free�active�inactive�buffers�cached�shared�wired�	scputimes�user�nice�system�idle�irq�pmemrBrC�text�data�stack�	pcputimes�
children_user�children_system�
pmmap_groupedz*path rss, private, ref_count, shadow_count�	pmmap_extz6addr, perms path rss, private, ref_count, shadow_count�sdiskioZ
read_countZwrite_countZ
read_bytesZwrite_bytesZ	read_timeZ
write_timeZ	busy_timecCs�tj�}|\}}}}}}}}tr�tdd��R}	xJ|	D]B}
|
jd�rVt|
j�d�d}q2|
jd�r2t|
j�d�d}q2WWdQRX|||}|||}t|||dd�}
t|||
||||||||�S)	z&System virtual memory as a namedtuple.z
/proc/meminfo�rbsBuffers:ris
MemShared:N)�_round)	�cextZvirtual_memr�open�
startswith�int�splitrrI)ZmemrJrMrNrOrSrQrPrR�f�lineZavailrLrK�rm�/usr/lib64/python3.6/_psbsd.py�virtual_memory�s


"rocCs4tj�\}}}}}t||dd�}tj||||||�S)z@System swap memory as (total, used, free, sin, sout) namedtuple.r)re)rfZswap_memrrZsswap)rJrLrMZsinZsoutrKrmrmrn�swap_memory�srpcCs"tj�\}}}}}t|||||�S)z+Return system per-CPU times as a namedtuple)rf�	cpu_timesrT)rUrVrWrXrYrmrmrnrq�srq�
per_cpu_timescCsBg}x8tj�D],}|\}}}}}t|||||�}|j|�qW|S)z'Return system CPU times as a namedtuple)rfrrrT�append)�retZcpu_trUrVrWrXrY�itemrmrmrnrr�scCs.t�dkrt�gStjr td��dt_t�gS)z'Return system CPU times as a namedtuplerz&supported only starting from FreeBSD 8T)�cpu_count_logicalrqrr�
__called__�NotImplementedErrorrmrmrmrnrr�s
FcCstj�S)z0Return the number of logical CPUs in the system.)rfrvrmrmrmrnrv�srvcCst�dkrdSdS)Nr)rvrmrmrmrn�cpu_count_physical�sryc
Csxd}tj�}|dk	rb|jd�}|dkrb|d|d�}tj|�}zt|jd��pRd}Wd|j�X|stt�dkrtdS|S)z1Return the number of physical CPUs in the system.Nz	</groups>rr zgroup/children/group/cpu���)	rfZcpu_count_phys�rfind�ETZ
fromstring�len�findall�clearrv)rt�s�index�rootrmrmrnry�s



c	Cs�trtj�\}}}}}nttrrtj�\}}}}}}}tdd��.}x&|D]}|jd�rDt|j�d�}qDWWdQRXntr�tj�\}}}}}}}t	j
||||�S)z*Return various CPU stats as a named tuple.z
/proc/statrdsintrrN)rrf�	cpu_statsrrgrhrirjrrZ	scpustats)	ZctxswZintrsZ
soft_intrsZsyscallsZtrapsZfaultsZforksrkrlrmrmrnr�s

 r�c	CsDg}tj�}x2|D]*}|\}}}}tj||||�}|j|�qW|S)z�Return mounted disk partitions as a list of namedtuples.
    'all' argument is ignored, see:
    https://github.com/giampaolo/psutil/issues/906
    )rf�disk_partitionsrZ	sdiskpartrs)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZopts�ntuplermrmrnr�<s
r�cCsjt�j�}i}xV|D]N}tj|�}tj|�}tj|�\}}ttd�rNtj|�}tj	||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)
�net_io_counters�keys�
cext_posixZ
net_if_mtuZnet_if_flagsZnet_if_duplex_speed�hasattrrr�Z	snicstats)�namesrtrHZmtuZisupZduplexZspeedrmrmrn�net_if_statsWs





r�cCs�trzg}xlt�D]b}yt|�j|�}Wnttfk
r@wYqXx.|D]&}t|�}|j|�|jtj	|��qHWqW|S|tj
kr�td|djdd�t
D��f��t
|\}}t
�}tr�tjd�}ntj�}x�|D]�}|\}	}
}}}
}}|
|ko�||kr�yt|}Wn tk
�r&ttj}YnX|
ttfk�rV|�rFtj|�}|
�rVtj|
�}
t|
�}
t|�}tj	|	|
|||
||�}|j|�q�Wt|�S)z System-wide network connections.z+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSrm)�repr)�.0�xrmrmrn�
<listcomp>wsz#net_connections.<locals>.<listcomp>rrz)r�pids�Process�connectionsrr�listrsrZsconnr
�
ValueError�join�setrrf�net_connections�TCP_STATUSES�KeyError�PSUTIL_CONN_NONErr	�addrrr�add)�kindrt�pidZconsZconn�families�types�rawlistru�fd�fam�type�laddr�raddrr1�ntrmrmrnr�esJ





r�cCsbytj�\}}}Wntk
r&dSX|dk}|r<tj}n|dkrLtj}n|d}tj|||�S)zReturn battery info.Nr�<rz)rf�sensors_batteryrxrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)rKZminsleftZ
power_pluggedZsecsleftrmrmrnr��sr�cCstj�S)z:The system boot time expressed in seconds since the epoch.)rf�	boot_timermrmrmrnr��sr�c	Csjg}tj�}xX|D]P}|\}}}}}|dkr8ts4t�d}|dkrBqtj||pNd|||�}|j|�qW|S)z:Return currently connected users as a list of namedtuples.rN�~rz)rf�usersr�AssertionErrorrZsuserrs)	r�r�rurUZttyZhostnameZtstampr�r�rmrmrnr��s
r�cCs@ytd�j�Wn&tk
r$dStk
r6dSXdSdS)NrFT)r�rHrrrmrmrmrn�
_pid_0_exists�sr�cCs*tj�}tr&d|kr&t�r&|jdd�|S)z7Returns a list of PIDs currently running on the system.r)rfr�rr��insert)rtrmrmrnr��sr�cCs tj|�}|s|t�kSdSdS)zReturn True if pid exists.TN)r�
pid_existsr�)r��existsrmrmrnr��s

r�cstj���fdd��}|S)z`Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    cs�y�|f|�|�Stk
r�}z�|jdkrHdt�krFt|j|j��n�|jtjkr�t|j�snt|j|j��nt	|j|j|j
��|jtjtjfkr�t|j|j���WYdd}~XnXdS)Nr)
�OSErrorr�r�r�_name�errno�ESRCHr�rr�_ppid�EPERM�EACCES)�self�args�kwargs�err)�funrmrn�wrapper�s


z wrap_exceptions.<locals>.wrapper)�	functools�wraps)r�r�rm)r�rn�wrap_exceptions�sr�ccs�y
dVWn�tk
r�}zf|jtjtjfkrZt|j�sHt|j|j��nt|j|j|j	��|jtj
tjfkrzt|j|j���WYdd}~XnXdS)z8Same as above, for routines relying on reading /proc fs.N)
�EnvironmentErrorr��ENOENTr�r�r�rr�rr�r�r�r)Zinstr�rmrmrn�wrap_exceptions_procfs
s

r�c@s�eZdZdZdddgZdd�Zedd��Zd	d
�Zdd�Z	e
d
d��Ze
dd��Ze
dd��Z
e
dd��Ze
dd��Ze
dd��Ze
dd��Ze
dd��Zer�e
dd��Ze
dd ��ZeZe
d!d"��Ze
d#d$��Ze
d%d&��Ze
d'd(��Ze
dJd*d+��Ze
dKd-d.��Ze
d/d0��Ze
d1d2��Ze
d3d4��Ze
d5d6��Z e
d7d8��Z!e"d9d:�Z#e"d9d;�Z$d<d=�Z%e&e'd>��rxe
d?d@��Z(ne%Z(e&e'dA��r�e
dBdC��Z)ne%Z)e�r�e
dDdE��Z*e
dFdG��Z+e
dHdI��Z,d,S)Lr�z1Wrapper class around underlying C implementation.r�r�r�cCs||_d|_d|_dS)N)r�r�r�)r�r�rmrmrn�__init__"szProcess.__init__cCs$tj|j�}t|�tt�ks t�|S)z;Retrieves multiple process info in one shot as a raw tuple.)rfZproc_oneshot_infor�r}�kinfo_proc_mapr�)r�rtrmrmrn�oneshot'szProcess.oneshotcCs|jj�dS)N)r�Zcache_activate)r�rmrmrn�
oneshot_enter.szProcess.oneshot_entercCs|jj�dS)N)r�Zcache_deactivate)r�rmrmrn�oneshot_exit1szProcess.oneshot_exitcCs(|j�td}|dk	r|Stj|j�S)NrH)r�r�rfZ	proc_namer�)r�rHrmrmrnrH4szProcess.namec
Csdtrtj|j�StrD|jdkr"dSt|��tjd|j�SQRXn|j�}|r\t	|d�SdSdS)Nr�z/proc/%s/exe)
rrfZproc_exer�rr��os�readlink�cmdliner)r�r�rmrmrn�exe9s

zProcess.execCs�tr|jdkrgStr�ytj|j�Stk
r�}zB|jtjkrnt|j�sZt	|j|j
��qpt|j|j
|j��n�WYdd}~Xq�Xntj|j�SdS)Nr)
rr�rrfZproc_cmdliner�r��EINVALr�rr�rr�)r�r�rmrmrnr�Os
zProcess.cmdlinecCs:|j�td}tj�}y||Stk
r4dSXdS)Nr8)r�r�rZget_terminal_mapr�)r�Ztty_nrZtmaprmrmrn�terminaleszProcess.terminalcCs|j�td|_|jS)Nr0)r�r�r�)r�rmrmrnr0nszProcess.ppidcCs.|j�}tj|td|td|td�S)Nr2r3r4)r�rZpuidsr�)r��rawtuplermrmrn�uidsss


zProcess.uidscCs.|j�}tj|td|td|td�S)Nr5r6r7)r�rZpgidsr�)r�r�rmrmrn�gids{s


zProcess.gidscCs8|j�}tj|td|td|td|td�S)Nr>r?r@rA)r�rr^r�)r�r�rmrmrnrq�s


zProcess.cpu_timescCs|j�tdS)NrG)r�r�)r�rmrmrn�cpu_num�szProcess.cpu_numcCs@|j�}t|td|td|td|td|td�S)NrBrCrDrErF)r�rZr�)r�r�rmrmrn�memory_info�s



zProcess.memory_infocCs|j�tdS)Nr9)r�r�)r�rmrmrnr9�szProcess.create_timecCs&ttd�rtj|j�St|j��SdS)N�proc_num_threads)r�rfr�r�r}�threads)r�rmrmrn�num_threads�s
zProcess.num_threadscCs$|j�}tj|td|td�S)Nr:r;)r�rZpctxswr�)r�r�rmrmrn�num_ctx_switches�s
zProcess.num_ctx_switchescCsLtj|j�}g}x*|D]"\}}}tj|||�}|j|�qWtrH|j�|S)N)rfZproc_threadsr�rZpthreadrsrrH)r�r�r�Z	thread_id�utimeZstimer�rmrmrnr��szProcess.threads�inetcCs�|tkr(td|djdd�tD��f��t�rt|\}}t�}tj|j�}x�|D]�}|\}}}	}
}}}
|
|jksvt�||ko�|	|krRyt	|}Wnt
k
r�t	tj}YnX|tt
fkr�|
r�tj|
�}
|r�tj|�}t|�}t|	�}	tj|||	|
||�}|j|�qRW|j�t|�St|\}}tj|j||�}g}x�|D]z}|\}}}	}
}}|tt
fk�r�|
�rttj|
�}
|�r�tj|�}t|�}t|	�}	t	|}tj|||	|
||�}|j|��qBWt�r�|j�|S)Nz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSrm)r�)r�r�rmrmrnr��sz'Process.connections.<locals>.<listcomp>)r
r�r�rr�rfr�r�r�r�r�r�rr	rr�rrZpconnr�rHr�Zproc_connectionsrsr)r�r�r�r�rtr�rur�r�r�r�r�r1r�r�rmrmrnr��sX





zProcess.connectionsNcCstj|j||j�S)N)rZwait_pidr�r�)r�Ztimeoutrmrmrn�wait�szProcess.waitcCstj|j�S)N)r��getpriorityr�)r�rmrmrn�nice_get�szProcess.nice_getcCstj|j|�S)N)r��setpriorityr�)r��valuermrmrn�nice_set�szProcess.nice_setcCs|j�td}tj|d�S)Nr1�?)r�r��
PROC_STATUSES�get)r��codermrmrnr1szProcess.statuscCs(|j�}tj|td|tddd�S)Nr<r=rrzrz)r�rZpior�)r�r�rmrmrn�io_counterss

zProcess.io_countersc
Csftr|jdkrdStr8t|��tjd|j�SQRXn*ttd�rRtj|j�pPdSt	t
r\dnd��dS)z)Return process current working directory.rNz/proc/%s/cwd�proc_open_filesz&supported only starting from FreeBSD 8r�)rr�rr�r�r�r�rfZproc_cwdrxr)r�rmrmrn�cwds

zProcess.cwdZmmapz*path rss, private, ref_count, shadow_countz6addr, perms path rss, private, ref_count, shadow_countcCst�dS)N)rx)r�rmrmrn�_not_implemented)szProcess._not_implementedr�cCstj|j�}dd�|D�S)z8Return files opened by process as a list of namedtuples.cSsg|]\}}tj||��qSrm)rZ	popenfile)r��pathr�rmrmrnr�3sz&Process.open_files.<locals>.<listcomp>)rfr�r�)r�r�rmrmrn�
open_files/szProcess.open_files�proc_num_fdscCstj|j�}tr|j�|S)z=Return the number of file descriptors opened by this process.)rfr�r�rrH)r�rtrmrmrn�num_fds:szProcess.num_fdscCstj|j�S)N)rfZproc_cpu_affinity_getr�)r�rmrmrn�cpu_affinity_getJszProcess.cpu_affinity_getcCs�tttt����}x$|D]}||krtd||f��qWytj|j|�Wn\tk
r�}z@|j	t	j
t	jfkr�x$|D]}||krttd||f��qtW�WYdd}~XnXdS)Nz#invalid CPU #%i (choose between %s))�tuple�ranger}rrr�rfZproc_cpu_affinity_setr�r�r�r�ZEDEADLK)r�ZcpusZallcpusZcpur�rmrmrn�cpu_affinity_setNs

zProcess.cpu_affinity_setcCstj|j�S)N)rfZproc_memory_mapsr�)r�rmrmrn�memory_mapsgszProcess.memory_maps)r�)N)-�__name__�
__module__�__qualname__�__doc__�	__slots__r�r
r�r�r�r�rHr�r�r�r0r�r�rqrr�r�Zmemory_full_infor9r�r�r�r�r�r�r�r1r�r�rZnt_mmap_groupedZnt_mmap_extr�r�rfr�r�r�r�r�rmrmrmrnr�s\
		
6	
r�)F)}r��
contextlibr�r�r�Zxml.etree.ElementTreeZetreeZElementTreer|�collectionsrZsocketrr�rrrrfrr�r	r
rrr
rrrrrZ_compatr�_exceptionsrrrZ__extra__all__ZSIDLZSTATUS_IDLEZSRUNZSTATUS_RUNNINGZSSLEEPZSTATUS_SLEEPINGZSSTOPZSTATUS_STOPPEDZSZOMBZ
STATUS_ZOMBIEZSWAITZSTATUS_WAITINGZSLOCKZ
STATUS_LOCKEDr�ZSDEADZ
STATUS_WAKINGZSONPROCZSACTIVEZSDYINGZSTATUS_DEADZ
SSUSPENDEDZSTATUS_SUSPENDEDZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZTCPS_SYN_RECEIVEDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGr�Z	CONN_NONEr��sysconfZPAGESIZEZAF_LINK�dictr�rIrTrZZpfullmemr^rarbrcrorprqr�rrrwrvryr�r�Z
disk_usageZdisk_io_countersr�Znet_if_addrsr�r�r�r�r�r�r�r�r��contextmanagerr��objectr�rmrmrmrn�<module>s




	
#
6


__pycache__/_psposix.cpython-36.pyc000064400000007116150466730540013265 0ustar003

��JZ��@s�dZddlZddlZddlZddlZddlZddlmZddlmZddlm	Z	ddl
mZddl
mZdd	l
mZd
ddd
gZdd
�Zddd�Zdd�Zedd
��ZdS)z%Routines common to all posix systems.�N�)�memoize)�
sdiskusage)�
usage_percent)�PY3)�unicode)�TimeoutExpired�
pid_exists�wait_pid�
disk_usage�get_terminal_mapcCsl|dkrdSytj|d�WnFtk
rb}z*|jtjkr>dS|jtjkrNdS|�WYdd}~XnXdSdS)z6Check whether pid exists in the current process table.rTFN)�os�kill�OSError�errnoZESRCHZEPERM)�pid�err�r� /usr/lib64/python3.6/_psposix.pyr	sc	s�����fdd�}ttdtj���dk	rB�fdd�}����n�fdd�}d}x�y|�\}}Wnftk
r�}zJ|jtjkr�||�}wTn,|jtjkr�xt��r�||�}q�dSq�Wn�WYdd}~XqTX|d	kr�||�}qTtj|�r�tj	|�Stj
|��rtj|�Std
|��qTWdS)aIWait for process with pid 'pid' to terminate and return its
    exit status code as an integer.

    If pid is not a children of os.getpid() (current process) just
    waits until the process disappears and return None.

    If pid does not exist at all return None immediately.

    Raise TimeoutExpired on timeout expired.
    cs8�dk	r ���kr t���d��tj|�t|dd�S)N)r�name�g{�G�z�?)r�timeZsleep�min)�delay)r�	proc_name�stop_at�timeout�timerrr�
check_timeout?s


zwait_pid.<locals>.check_timeoutZ	monotonicNcstj�tj�S)N)r
�waitpid�WNOHANGr)rrr�waitcallHszwait_pid.<locals>.waitcallcstj�d�S)Nr)r
rr)rrrr!Lsg-C��6?rzunknown process exit status %r)
�getattrrrrZEINTRZECHILDr	r
�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS�
ValueError)	rrrrr!rZretpidZstatusrr)rrrrrrr
4s8



cCs�trtj|�}ndytj|�}WnTtk
rrt|t�rly|jtj��}Wntk
r^YnXtj|�}n�YnX|j	|j
}|j|j
}|j|j
}||}||}t
||dd�}t||||d�S)a.Return disk usage associated with path.
    Note: UNIX usually reserves 5% disk space which is not accessible
    by user. In this function "total" and "used" values reflect the
    total and used disk space whereas "free" and "percent" represent
    the "free" and "used percent" user disk space.
    r)Z_round)�total�usedZfreeZpercent)rr
�statvfs�UnicodeEncodeError�
isinstancer�encode�sys�getfilesystemencoding�f_blocks�f_frsize�f_bfree�f_bavailrr)�path�str(Z
avail_to_rootZ
avail_to_userr)Z
total_userZusage_percent_userrrrrws(
cCs�i}tjd�tjd�}xb|D]Z}||ks2t|��y||tj|�j<Wqtk
rv}z|jtjkrf�WYdd}~XqXqW|S)zMGet a map of device-id -> path as a dict.
    Used by Process.terminal()
    z	/dev/tty*z
/dev/pts/*N)�glob�AssertionErrorr
�stat�st_rdevrr�ENOENT)�retZlsrrrrrr�s
)NN)�__doc__rr6r
r.rZ_commonrrrZ_compatrr�_exceptionsr�__all__r	r
rrrrrr�<module>s 
C1__pycache__/_compat.cpython-36.opt-1.pyc000064400000015316150466730540014003 0ustar003

��JZ��!@s�dZddlZddlZddlZddlZddddddd	d
ddg
Zejdd
kZerpeZ	e
ZeZ
eZdd�Zdd	�Zn e	Z	eZe
Z
eZdd�Zdd	�ZyeZWnek
r�dd
�ZYnXyddlmZWn�ek
�rhyddlmZWn"ek
�r
ddlmZYnXejdddddg�ZGdd�de�Ze�feeeeed�f�e e!ee"fdd�Z#d#d d�ZYnXydd!l$m%Z%Wn,ek
�r�ej&ej'Bdfd"d�Z%YnXdS)$z?Module which provides compatibility with older Python versions.�N�PY3�long�xrange�unicode�
basestring�u�b�callable�	lru_cache�which�cCs|S)N�)�sr
r
�/usr/lib64/python3.6/_compat.pyrscCs
|jd�S)Nzlatin-1)�encode)rr
r
rrscCs
t|d�S)NZunicode_escape)r)rr
r
rr"scCs|S)Nr
)rr
r
rr%scCstdd�t|�jD��S)Ncss|]}d|jkVqdS)�__call__N)�__dict__)�.0�klassr
r
r�	<genexpr>.szcallable.<locals>.<genexpr>)�any�type�__mro__)�objr
r
rr	-s)r
)�RLock�	CacheInfo�hits�misses�maxsize�currsizec@s$eZdZdZefdd�Zdd�ZdS)�
_HashedSeq�	hashvaluecCs||dd�<||�|_dS)N)r!)�self�tup�hashr
r
r�__init__Esz_HashedSeq.__init__cCs|jS)N)r!)r"r
r
r�__hash__Isz_HashedSeq.__hash__N)�__name__�
__module__�__qualname__�	__slots__r$r%r&r
r
r
rr Bsr c	s�|}	|r2||j��}
|	|7}	x|
D]}|	|7}	q"W|rp|	|�fdd�|D��7}	|r�|	|�fdd�|
D��7}	n$||	�dkr��|	d�|kr�|	dSt|	�S)Nc3s|]}�|�VqdS)Nr
)r�v)rr
rrWsz_make_key.<locals>.<genexpr>c3s|]\}}�|�VqdS)Nr
)r�kr+)rr
rrYs�r)�itemsr )�args�kwds�typed�kwd_mark�	fasttypes�sorted�tupler�len�keyZsorted_items�itemr
)rr�	_make_keyLs
r9�dFcs��fdd�}|S)z~Least-recently-used cache decorator, see:
        http://docs.python.org/3/library/functools.html#functools.lru_cache
        cst��ddg�
d
\��t�
�j�t�t��	g���ddg�dd�<�g�d\�����dkrn��
�fdd�}nP�dkr������
��
��f	dd�}n*����������	�
���
��fdd�}����	��
fd	d
�}��	��
fdd�}�|_||_||_tj	|��S)Nrr-�rcs�||�}��d7<|S)Nr-r
)r/r0�result)�MISSES�stats�
user_functionr
r�wrapperos
z7lru_cache.<locals>.decorating_function.<locals>.wrappercsX�||��}�|��}|�k	r2��d7<|S�||�}|�|<��d7<|S)Nr-r
)r/r0r7r<)	�HITSr=�cache�	cache_get�make_key�rootr>r1r?r
rr@ts

csl|s�r�
||��}n|}�	j�zr�|�}|dk	r��\}|\}}}}||�<||�<|�}||�<|�<||�<||�<�
�d7<|SWd�	j�X�||�}�	j�z��\}|�kr�n�����k�r|}	||	�<||	�<|	�}�d<|�}
d|�<|�<�|
=|	�|<n,|�}||||g}||�<|�<�|<�
�d7<Wd�	j�X|S)Nr-r)�acquire�release)r/r0r7�linkrEZ	link_prevZ	link_nextr<ZlastZoldrootZoldkey)rA�KEYr=�NEXT�PREV�RESULT�_lenrBrC�lockrDr�
nonlocal_rootr>r1r?r
rr@sN



cs2�j�zt�����t���S�j�XdS)zReport cache statisticsN)rF�
_CacheInfor6rGr
)rAr=rBrNrr>r
r�
cache_info�s

z:lru_cache.<locals>.decorating_function.<locals>.cache_infoc
sP�j�z8�j��d}||ddg|dd�<ddg�dd�<Wd�j�XdS)z$Clear the cache and cache statisticsrN)rF�clearrG)rE)rBrNrOr>r
r�cache_clear�sz;lru_cache.<locals>.decorating_function.<locals>.cache_clear)rr-)rr-r;r)
�dictr9�getr6r�__wrapped__rQrS�	functools�update_wrapper)r?r@rQrS)rr1)rArIr=rJrKrLrMrBrCrNrDrOrEr>r?r�decorating_functionbs,*-	z&lru_cache.<locals>.decorating_functionr
)rr1rYr
)rr1rr
^sc)rcs"dd�}tjj��r&|�|�r"�SdS|dkr>tjjdtj�}|sFdS|jtj�}tj	dkr�tj
|krt|jdtj
�tjjdd�jtj�}t�fd	d
�|D��r��g}q‡fdd�|D�}n�g}t
�}xT|D]L}tjj|�}||kr�|j|�x(|D] }	tjj||	�}
||
|�r�|
Sq�Wq�WdS)
aJGiven a command, mode, and a PATH string, return the path which
        conforms to the given mode on the PATH, or None if there is no such
        file.

        `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
        of os.environ.get("PATH"), or can be overridden with a custom search
        path.
        cSs&tjj|�o$tj||�o$tjj|�S)N)�os�path�exists�access�isdir)�fn�moder
r
r�
_access_check�szwhich.<locals>._access_checkN�PATHZwin32rZPATHEXT�c3s |]}�j�j|j��VqdS)N)�lower�endswith)r�ext)�cmdr
rr�szwhich.<locals>.<genexpr>csg|]}�|�qSr
r
)rrf)rgr
r�
<listcomp>�szwhich.<locals>.<listcomp>)rZr[�dirname�environrU�defpath�split�pathsep�sys�platform�curdir�insertr�set�normcase�add�join)rgr`r[raZpathext�files�seen�dirZnormdirZthefile�namer
)rgrr�s8	






)r:F)(�__doc__�collectionsrWrZrn�__all__�version_infor�intr�ranger�strrrrrr	�	NameErrorr
�ImportErrorZ	threadingrZdummy_threading�
namedtuplerP�listr �objectrr�	frozensetrr4r5r6r9Zshutilr�F_OK�X_OKr
r
r
r�<module>sT


k__pycache__/_psaix.cpython-36.opt-1.pyc000064400000036141150466730540013643 0ustar003

��JZ�K�@s�dZddlZddlZddlZddlZddlZddlZddlmZddl	m
Z
ddlmZddlm
Z
ddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZdgZ e!ed�Z"ej#d�Z$ej%Z%ej&ej'ej(ej)ej*ej+ej,ej+ej-ej.iZ/ej0ej1ej2ej3ej4ej5ej6ej7ej8ej9ej:ej;ej<ej=ej>ej?ej@ejAejBejCejDejEejFejGiZHeIddddddddd�ZJed d!d"g�ZKeKZLed#d$d%d&d'g�ZMed(d)d*d+d,d-g�ZNed.d/d!d0d1g�ZOed2d3d4jPeOjQ��ZRd5d6�ZSd7d8�ZTd9d:�ZUd;d<�ZVd=d>�ZWd?d@�ZXdAdB�ZYdCdD�ZZej[Z[e
j\Z\dXdFdG�Z]ej^Z^ej_Z_dZdHdI�Z`dJdK�ZadLdM�ZbdNdO�ZcdPdQ�ZddRdS�ZedTdU�ZfGdVdW�dWeg�ZhdS)[zAIX platform implementation.�N)�
namedtuple)�AF_INET�)�_common)�_psposix)�_psutil_aix)�
_psutil_posix)�AF_INET6)�memoize_when_activated)�NIC_DUPLEX_FULL)�NIC_DUPLEX_HALF)�NIC_DUPLEX_UNKNOWN)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�PY3)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�PROCFS_PATH�proc_threads�SC_PAGE_SIZE������)�ppid�rss�vms�create_time�nice�num_threads�status�ttynr�pmemrr �	scputimes�user�systemZidleZiowait�svmem�totalZ	available�percent�used�free�
pmmap_grouped�pathZanon�locked�	pmmap_extzaddr perms � cCstjdjS)z+Return updated psutil.PROCFS_PATH constant.Zpsutil)�sys�modulesr�r6r6�/usr/lib64/python3.6/_psaix.py�get_procfs_pathlsr8cCs4tj�\}}}}}t|||dd�}t|||||�S)Nr)�_round)�cextZvirtual_memrr*)r+Zavailr.ZpinnedZinuser,r6r6r7�virtual_memoryvsr;cCs:tj�\}}}}||}t||dd�}tj||||||�S)z=Swap system memory as a (total, used, free, sin, sout) tuple.r)r9)r:Zswap_memrrZsswap)r+r.ZsinZsoutr-r,r6r6r7�swap_memory|sr<cCstj�}tdd�t|�D��S)z-Return system-wide CPU times as a named tuplecSsg|]}t|��qSr6)�sum)�.0�xr6r6r7�
<listcomp>�szcpu_times.<locals>.<listcomp>)r:�
per_cpu_timesr'�zip)�retr6r6r7�	cpu_times�srDcCstj�}dd�|D�S)z5Return system per-CPU times as a list of named tuplescSsg|]}t|��qSr6)r')r>r?r6r6r7r@�sz!per_cpu_times.<locals>.<listcomp>)r:rA)rCr6r6r7rA�srAcCs$y
tjd�Stk
rdSXdS)z0Return the number of logical CPUs in the system.�SC_NPROCESSORS_ONLNN)�os�sysconf�
ValueErrorr6r6r6r7�cpu_count_logical�s
rIcCsrd}tj|dtjtjd�}|j�\}}tr@dd�||fD�\}}|jdkrZtd||f��|j�j�}t	|�ppdS)Nzlsdev -Cc processorT)�shell�stdout�stderrcSsg|]}|jtjj��qSr6)�decoder4rK�encoding)r>r?r6r6r7r@�sz&cpu_count_physical.<locals>.<listcomp>rz%r command error
%s)
�
subprocess�Popen�PIPE�communicater�
returncode�RuntimeError�strip�
splitlines�len)�cmd�prKrLZ
processorsr6r6r7�cpu_count_physical�s

rZcCs tj�\}}}}tj||||�S)z*Return various CPU stats as a named tuple.)r:�	cpu_statsrZ	scpustats)Zctx_switchesZ
interruptsZsoft_interruptsZsyscallsr6r6r7r[�sr[Fc	Cs`g}tj�}xN|D]F}|\}}}}|dkr.d}|s>t|�js>qtj||||�}|j|�qW|S)zReturn system disk partitions.Znone�)r:�disk_partitions�
disk_usager+rZ	sdiskpart�append)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZopts�ntupler6r6r7r]�s

r]c	Cstj}||kr.td|djdd�|D��f��tj|\}}tj|�}t�}x�|D]�}|\}}	}
}}}
}|	|krrqR|
|kr|qRt|
}
|	tt	fkr�|r�tj
|�}|r�tj
|�}t|	�}	t|
�}
|dkr�tj
||	|
|||
|�}ntj||	|
|||
�}|j|�qRWt|�S)z�Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    z+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSr6)�repr)r>r?r6r6r7r@�sz#net_connections.<locals>.<listcomp>r���)rZ	conn_tmaprH�joinr:�net_connections�set�TCP_STATUSESrr	ZaddrrrZsconnZpconn�add�list)�kind�_pidZcmapZfamilies�types�rawlistrC�item�fdZfamZtype_ZladdrZraddrr$�pid�ntr6r6r7rg�s4



rgcCs�ttd�}tdd�t�D��}i}x�|D]�}tj|�\}}d}d}tjdd|gtjtjd�}|j	�\}	}
t
r�d	d�|	|
fD�\}	}
|jdkr�tj
d
|	�}|dk	r�t|jd��}|jd
�}|j|t�}tj||||�||<q(W|S)z)Get NIC stats (isup, duplex, speed, mtu).)ZFullZHalfcSsg|]}|d�qS)rr6)r>r?r6r6r7r@�sz net_if_stats.<locals>.<listcomp>r\rz/usr/bin/entstatz-d)rKrLcSsg|]}|jtjj��qSr6)rMr4rKrN)r>r?r6r6r7r@
sz"Running: (\d+) Mbps.*?(\w+) DuplexNrr)rrrh�net_if_addrsr:�net_if_statsrOrPrQrRrrS�re�search�int�group�getr
rZ	snicstats)Z
duplex_map�namesrC�nameZisupZmtuZduplexZspeedrYrKrLZ	re_resultr6r6r7ru�s,


rucCstj�S)z:The system boot time expressed in seconds since the epoch.)r:�	boot_timer6r6r6r7r}sr}cCs`g}tj�}d}xJ|D]B}|\}}}}}}	|s0q||kr<d}tj|||||	�}
|j|
�qW|S)z:Return currently connected users as a list of namedtuples.�:0.0�:0�	localhost)r~r)r:�usersrZsuserr_)raror�rpr(ZttyZhostnameZtstampZuser_processrrrsr6r6r7r�$s
r�cCsdd�tjt��D�S)z7Returns a list of PIDs currently running on the system.cSsg|]}|j�rt|��qSr6)�isdigitrx)r>r?r6r6r7r@>szpids.<locals>.<listcomp>)rF�listdirr8r6r6r6r7�pids<sr�cCstjjtjjt�t|�d��S)z&Check for the existence of a unix pid.Zpsinfo)rFr0�existsrfr8�str)rrr6r6r7�
pid_existsAsr�cs�fdd�}|S)z�Call callable into a try/except clause and translate ENOENT,
    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
    cs�y�|f|�|�Stk
r�}z�tdks:tdks:tdkr<�|jtjtjfkrzt|j�sht|j|j	��nt|j|j	|j
��|jtjtjfkr�t|j|j	���WYdd}~XnXdS)N)
�EnvironmentErrorrrr�errno�ENOENTZESRCHr�rr�_name�_ppidZEPERMZEACCES)�self�args�kwargs�err)�funr6r7�wrapperKs
z wrap_exceptions.<locals>.wrapperr6)r�r�r6)r�r7�wrap_exceptionsFsr�c@sheZdZdZddddgZdd�Zdd	�Zd
d�Zedd
��Z	edd��Z
edd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zer�edd��Zed@dd ��Zed!d"��Zed#d$��Zed%d&��Zed'd(��Zed)d*��Zed+d,��Zed-d.��Zed/d0��Zed1d2��ZeZed3d4��Zd5d6�Z ed7d8��Z!ed9d:��Z"edAd<d=��Z#ed>d?��Z$d;S)B�Processz1Wrapper class around underlying C implementation.rrr�r��_procfs_pathcCs||_d|_d|_t�|_dS)N)rrr�r�r8r�)r�rrr6r6r7�__init__fszProcess.__init__cCs"|jj�|jj�|jj�dS)N)�_proc_name_and_argsZcache_activate�_proc_basic_info�
_proc_cred)r�r6r6r7�
oneshot_enterls

zProcess.oneshot_entercCs"|jj�|jj�|jj�dS)N)r�Zcache_deactivater�r�)r�r6r6r7�oneshot_exitqs

zProcess.oneshot_exitcCstj|j|j�S)N)r:Zproc_name_and_argsrrr�)r�r6r6r7r�vszProcess._proc_name_and_argscCstj|j|j�S)N)r:Zproc_basic_inforrr�)r�r6r6r7r�zszProcess._proc_basic_infocCstj|j|j�S)N)r:Z	proc_credrrr�)r�r6r6r7r�~szProcess._proc_credcCs |jdkrdS|j�djd�S)NrZswapper�)rrr��rstrip)r�r6r6r7r|�s
zProcess.namecCs�|j�d}tjj|krttjj|�s>tjjtjj|j�|��}tjj|�rhtjj|�rhtj	|tj
�rh|Stjj|�}xLtjdj
d�D]8}tjjtjj||��}tjj|�r�tj	|tj
�r�|Sq�WdS)Nr�PATH�:r\)�cmdlinerFr0�sep�isabs�abspathrf�cwd�isfile�access�X_OK�basename�environ�split)r��exer0Zpossible_exer6r6r7r��szProcess.execCs|j�djd�S)Nrr3)r�r�)r�r6r6r7r��szProcess.cmdlinecCs|j�tdS)Nr!)r��
proc_info_map)r�r6r6r7r!�szProcess.create_timecCs|j�tdS)Nr#)r�r�)r�r6r6r7r#�szProcess.num_threadscCsZtj|j�}g}x*|D]"\}}}tj|||�}|j|�qW|sVtjd|j|jf�|S)Nz%s/%s)	r:rrrrZpthreadr_rF�statr�)r�roraZ	thread_id�utimeZstimercr6r6r7�threads�szProcess.threads�inetcCs,t||jd�}|s(tjd|j|jf�|S)N)rmz%s/%s)rgrrrFr�r�)r�rlrCr6r6r7�connections�szProcess.connectionscCstj|j�S)N)�
cext_posix�getpriorityrr)r�r6r6r7�nice_get�szProcess.nice_getcCstj|j|�S)N)r��setpriorityrr)r��valuer6r6r7�nice_set�szProcess.nice_setcCs|j�td|_|jS)Nr)r�r�r�)r�r6r6r7r�szProcess.ppidcCs"|j�\}}}}}}tj|||�S)N)r�r�puids)r��real�	effective�saved�_r6r6r7�uids�szProcess.uidscCs"|j�\}}}}}}tj|||�S)N)r�rr�)r�r�r�r�r�r6r6r7�gids�szProcess.gidscCstj|j|j�}tj|�S)N)r:Zproc_cpu_timesrrr�rZ	pcputimes)r�rDr6r6r7rD�szProcess.cpu_timescCsP|j�td}|d@d?|d@B}x&tjd�D]}tj|�j|kr0|Sq0WdS)Nr%l��i��z	/dev/**/*)r�r��globrFr��st_rdev)r�ZttydevZdevr6r6r7�terminal�szProcess.terminalcCsr|j}ytjd||jf�}|jd�Stk
rl}z,|jtjkrZtjd||jf�dS�WYdd}~XnXdS)Nz	%s/%s/cwd�/z%s/%s)	r�rF�readlinkrrr��OSErrorr�r�r�)r�Zprocfs_path�resultr�r6r6r7r��s
zProcess.cwdcCs2|j�}|tdd}|tdd}t||�S)Nrir )r�r�r&)r�rCrr r6r6r7�memory_info�szProcess.memory_infocCs|j�td}tj|d�S)Nr$�?)r�r��
PROC_STATUSESrz)r��coder6r6r7r$szProcess.statuscCs�tjddt|j�gtjtjd�}|j�\}}trFdd�||fD�\}}d|j�kr`t|j|j	��t
jd|�}g}xR|D]J\}}|j�}|j
d�r�|d	d�}|j�d
kr�qv|jtj|t|���qvW|S)Nz/usr/bin/procfilesz-n)rKrLcSsg|]}|jtjj��qSr6)rMr4rKrN)r>r?r6r6r7r@sz&Process.open_files.<locals>.<listcomp>zno such processz(\d+): S_IFREG.*\s*.*name:(.*)
z//rzcannot be retrieved)rOrPr�rrrQrRr�lowerrr�rv�findallrU�
startswithr_rZ	popenfilerx)r�rYrKrLZ	procfilesrarqr0r6r6r7�
open_filess$
zProcess.open_filescCs(|jdkrdSttjd|j|jf��S)Nrz%s/%s/fd)rrrWrFr�r�)r�r6r6r7�num_fds$s
zProcess.num_fdscCstjtj|j��S)N)rZpctxswr:Zproc_num_ctx_switchesrr)r�r6r6r7�num_ctx_switches*szProcess.num_ctx_switchesNcCstj|j||j�S)N)rZwait_pidrrr�)r�Ztimeoutr6r6r7�wait/szProcess.waitc
CsXytj|j�\}}}}Wn.tk
rFt|j�s@t|j|j���YnXtj||||�S)N)	r:Zproc_io_countersrrr�r�rr�rZpio)r�ZrcZwc�rb�wbr6r6r7�io_counters3s
zProcess.io_counters)r�)N)%�__name__�
__module__�__qualname__�__doc__�	__slots__r�r�r�r
r�r�r�r�r|r�r�r!r#�HAS_THREADSr�r�r�r�rr�r�rDr�r�r�Zmemory_full_infor$r�r�r�r�r�r6r6r6r7r�asDr�)Fre)re)ir�r�r�rFrvrOr4�collectionsrZsocketrr\rrrr:rr�r	r
rrr
rrrZ_compatr�_exceptionsrrrZ__extra__all__�hasattrr�rGZ	PAGE_SIZEZAF_LINKZSIDLZSTATUS_IDLEZSZOMBZ
STATUS_ZOMBIEZSACTIVEZSTATUS_RUNNINGZSSWAPZSSTOPZSTATUS_STOPPEDr�ZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZ
TCPS_SYN_RCVDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGZPSUTIL_CONN_NONEZ	CONN_NONEri�dictr�r&Zpfullmemr'r*r/rf�_fieldsr2r8r;r<rDrArIrZr[Zdisk_io_countersr^r]rtZnet_io_countersrgrur}r�r�r�r��objectr�r6r6r6r7�<module>s�

	

	

!$__pycache__/_compat.cpython-36.pyc000064400000015316150466730540013044 0ustar003

��JZ��!@s�dZddlZddlZddlZddlZddddddd	d
ddg
Zejdd
kZerpeZ	e
ZeZ
eZdd�Zdd	�Zn e	Z	eZe
Z
eZdd�Zdd	�ZyeZWnek
r�dd
�ZYnXyddlmZWn�ek
�rhyddlmZWn"ek
�r
ddlmZYnXejdddddg�ZGdd�de�Ze�feeeeed�f�e e!ee"fdd�Z#d#d d�ZYnXydd!l$m%Z%Wn,ek
�r�ej&ej'Bdfd"d�Z%YnXdS)$z?Module which provides compatibility with older Python versions.�N�PY3�long�xrange�unicode�
basestring�u�b�callable�	lru_cache�which�cCs|S)N�)�sr
r
�/usr/lib64/python3.6/_compat.pyrscCs
|jd�S)Nzlatin-1)�encode)rr
r
rrscCs
t|d�S)NZunicode_escape)r)rr
r
rr"scCs|S)Nr
)rr
r
rr%scCstdd�t|�jD��S)Ncss|]}d|jkVqdS)�__call__N)�__dict__)�.0�klassr
r
r�	<genexpr>.szcallable.<locals>.<genexpr>)�any�type�__mro__)�objr
r
rr	-s)r
)�RLock�	CacheInfo�hits�misses�maxsize�currsizec@s$eZdZdZefdd�Zdd�ZdS)�
_HashedSeq�	hashvaluecCs||dd�<||�|_dS)N)r!)�self�tup�hashr
r
r�__init__Esz_HashedSeq.__init__cCs|jS)N)r!)r"r
r
r�__hash__Isz_HashedSeq.__hash__N)�__name__�
__module__�__qualname__�	__slots__r$r%r&r
r
r
rr Bsr c	s�|}	|r2||j��}
|	|7}	x|
D]}|	|7}	q"W|rp|	|�fdd�|D��7}	|r�|	|�fdd�|
D��7}	n$||	�dkr��|	d�|kr�|	dSt|	�S)Nc3s|]}�|�VqdS)Nr
)r�v)rr
rrWsz_make_key.<locals>.<genexpr>c3s|]\}}�|�VqdS)Nr
)r�kr+)rr
rrYs�r)�itemsr )�args�kwds�typed�kwd_mark�	fasttypes�sorted�tupler�len�keyZsorted_items�itemr
)rr�	_make_keyLs
r9�dFcs��fdd�}|S)z~Least-recently-used cache decorator, see:
        http://docs.python.org/3/library/functools.html#functools.lru_cache
        cst��ddg�
d
\��t�
�j�t�t��	g���ddg�dd�<�g�d\�����dkrn��
�fdd�}nP�dkr������
��
��f	dd�}n*����������	�
���
��fdd�}����	��
fd	d
�}��	��
fdd�}�|_||_||_tj	|��S)Nrr-�rcs�||�}��d7<|S)Nr-r
)r/r0�result)�MISSES�stats�
user_functionr
r�wrapperos
z7lru_cache.<locals>.decorating_function.<locals>.wrappercsX�||��}�|��}|�k	r2��d7<|S�||�}|�|<��d7<|S)Nr-r
)r/r0r7r<)	�HITSr=�cache�	cache_get�make_key�rootr>r1r?r
rr@ts

csl|s�r�
||��}n|}�	j�zr�|�}|dk	r��\}|\}}}}||�<||�<|�}||�<|�<||�<||�<�
�d7<|SWd�	j�X�||�}�	j�z��\}|�kr�n�����k�r|}	||	�<||	�<|	�}�d<|�}
d|�<|�<�|
=|	�|<n,|�}||||g}||�<|�<�|<�
�d7<Wd�	j�X|S)Nr-r)�acquire�release)r/r0r7�linkrEZ	link_prevZ	link_nextr<ZlastZoldrootZoldkey)rA�KEYr=�NEXT�PREV�RESULT�_lenrBrC�lockrDr�
nonlocal_rootr>r1r?r
rr@sN



cs2�j�zt�����t���S�j�XdS)zReport cache statisticsN)rF�
_CacheInfor6rGr
)rAr=rBrNrr>r
r�
cache_info�s

z:lru_cache.<locals>.decorating_function.<locals>.cache_infoc
sP�j�z8�j��d}||ddg|dd�<ddg�dd�<Wd�j�XdS)z$Clear the cache and cache statisticsrN)rF�clearrG)rE)rBrNrOr>r
r�cache_clear�sz;lru_cache.<locals>.decorating_function.<locals>.cache_clear)rr-)rr-r;r)
�dictr9�getr6r�__wrapped__rQrS�	functools�update_wrapper)r?r@rQrS)rr1)rArIr=rJrKrLrMrBrCrNrDrOrEr>r?r�decorating_functionbs,*-	z&lru_cache.<locals>.decorating_functionr
)rr1rYr
)rr1rr
^sc)rcs"dd�}tjj��r&|�|�r"�SdS|dkr>tjjdtj�}|sFdS|jtj�}tj	dkr�tj
|krt|jdtj
�tjjdd�jtj�}t�fd	d
�|D��r��g}q‡fdd�|D�}n�g}t
�}xT|D]L}tjj|�}||kr�|j|�x(|D] }	tjj||	�}
||
|�r�|
Sq�Wq�WdS)
aJGiven a command, mode, and a PATH string, return the path which
        conforms to the given mode on the PATH, or None if there is no such
        file.

        `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
        of os.environ.get("PATH"), or can be overridden with a custom search
        path.
        cSs&tjj|�o$tj||�o$tjj|�S)N)�os�path�exists�access�isdir)�fn�moder
r
r�
_access_check�szwhich.<locals>._access_checkN�PATHZwin32rZPATHEXT�c3s |]}�j�j|j��VqdS)N)�lower�endswith)r�ext)�cmdr
rr�szwhich.<locals>.<genexpr>csg|]}�|�qSr
r
)rrf)rgr
r�
<listcomp>�szwhich.<locals>.<listcomp>)rZr[�dirname�environrU�defpath�split�pathsep�sys�platform�curdir�insertr�set�normcase�add�join)rgr`r[raZpathext�files�seen�dirZnormdirZthefile�namer
)rgrr�s8	






)r:F)(�__doc__�collectionsrWrZrn�__all__�version_infor�intr�ranger�strrrrrr	�	NameErrorr
�ImportErrorZ	threadingrZdummy_threading�
namedtuplerP�listr �objectrr�	frozensetrr4r5r6r9Zshutilr�F_OK�X_OKr
r
r
r�<module>sT


k__pycache__/__init__.cpython-36.pyc000064400000172473150466730540013171 0ustar003

��JZ�K�u@sZ	dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
yddlZWnek
r�dZYnXddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ddlm,Z,ddlm-Z-ddlm.Z.dd lm/Z/dd!lm0Z0dd"lm1Z1dd#lm2Z2dd$lm3Z3dd%lm4Z4dd&lm5Z5dd'lm6Z6dd(lm7Z7dd)lm8Z8dd*lm9Z9dd+lm:Z:dd,lm;Z;dd-lm<Z<dd.lm=Z=dd/lm>Z>dd0lm?Z?dd1l@mAZAdd2l@mBZBdd3l@mCZCdd4l@mDZDdd5l@mEZEe9�rpd6ZFdd7lmGZHdd8lGmIZIdd9lGmJZJdd:lGmKZKdd;lGmLZLeHjM�rVdd<lNmOZOdd=lNmPZPdd>lNmQZQdd?lNmRZRdd@lNmSZSddAlNmTZTddBlNmUZUddClNmVZVddDlNmWZWddElNmXZXddFlNmYZYddGlNmZZZddHlmNZNy
eNj[Z[Wne\k
�r�YnXy
eNj]Z]Wne\k
�rYnXy
eNj^Z^Wne\k
�r(YnXy
eNj_Z_Wne\k
�rJYnXy
eNj`Z`Wne\k
�rlYnXn�e?�r�ddIlmaZHddJlbmcZcddKlbmdZdddLlbmeZeddMlbmfZfddNlbmgZgddOlbmhZhddPlamiZin~e<�r�ddQlmjZHnje7�rddRlmkZHnVe>�r0ddSlmlZHddTllmmZmddUllmnZnd6ZFn&e6�rHddVlmoZHd6ZFnepdWejq��dXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidhdjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dd�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�gEZrerjseHjt�d�Zud�Zvewd�d��evjxd��D��ZyeHjzZzej{Z{ej|Z|da}e~ed�ej�Ze�evj�d�d���e~eHj�d�d�k�r�d�e~eHj�d��Z�e�eHj�d���r�e�d�d�j�d�d��e�eHj�j��D��evf7Z�ne�d�ev7Z�e�d�e~eHj�d�d��7Z�e�d�7Z�ee���e�eHd���r�eHj�Z�nd�d��Z�d�d��Z�d�d��Z�Gd�d��d�e��Z�Gd�d��d�e��Z�e�d�d��e�e��D��Z�d�d��Z�d�d��Z�iZ�d�d�d��Z�d�d�d��Z�d�d�d��Z�d�d�d��Z�y
e��a�Wn"e�k
�r�da�e
j��YnXye�d�d��a�Wn"e�k
�r�da�e
j��YnXd�d��Z�d�d„Z�d�d�d��Z�t�a�t�a�d�d�d��Z�d�d��Z�e�eHdƃ�r d�d�dƄZ�erj�dƃd�d��Z�d�d��Z�d�d��Z�d�d�d��Z�d�d�d��Z�ej�ej�d̓e�_�d�e�j�_d�d�d��Z�ej�ej�dЃe�_�d�e�j�_d�d�d��Z�d�d��Z�d�d��Z�e�eHdՃ�r�d�d�dՄZ�erj�dՃe�eHd׃�r�d�dׄZ�erj�d׃e�eHdك�r�d�dلZ�erj�dكd�d��Z�d�d��Z�e?�	r"d�dބZ�d�d�Z�d�d�Z�[[[[ejydd�k�	rF[�[�e�d�k�	rVe��dS)�a0psutil is a cross-platform library for retrieving information on
running processes and system utilization (CPU, memory, disks, network,
sensors) in Python. Supported platforms:

 - Linux
 - Windows
 - OSX
 - FreeBSD
 - OpenBSD
 - NetBSD
 - Sun Solaris
 - AIX

Works with Python versions from 2.6 to 3.X.
�)�divisionN�)�_common)�deprecated_method)�memoize)�memoize_when_activated)�wrap_numbers)�callable)�long)�PY3)�STATUS_DEAD)�STATUS_DISK_SLEEP)�STATUS_IDLE)�
STATUS_LOCKED)�STATUS_RUNNING)�STATUS_SLEEPING)�STATUS_STOPPED)�STATUS_TRACING_STOP)�STATUS_WAITING)�
STATUS_WAKING)�
STATUS_ZOMBIE)�
CONN_CLOSE)�CONN_CLOSE_WAIT)�CONN_CLOSING)�CONN_ESTABLISHED)�CONN_FIN_WAIT1)�CONN_FIN_WAIT2)�
CONN_LAST_ACK)�CONN_LISTEN)�	CONN_NONE)�
CONN_SYN_RECV)�
CONN_SYN_SENT)�CONN_TIME_WAIT)�NIC_DUPLEX_FULL)�NIC_DUPLEX_HALF)�NIC_DUPLEX_UNKNOWN)�AIX)�BSD)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�AccessDenied)�Error)�
NoSuchProcess)�TimeoutExpired)�
ZombieProcessz/proc)�_pslinux)�IOPRIO_CLASS_BE)�IOPRIO_CLASS_IDLE)�IOPRIO_CLASS_NONE)�IOPRIO_CLASS_RT)�
RLIM_INFINITY)�	RLIMIT_AS)�RLIMIT_CORE)�
RLIMIT_CPU)�RLIMIT_DATA)�RLIMIT_FSIZE)�RLIMIT_LOCKS)�RLIMIT_MEMLOCK)�
RLIMIT_NOFILE)�RLIMIT_NPROC)�
RLIMIT_RSS)�RLIMIT_STACK)�
_psutil_linux)�
_pswindows)�ABOVE_NORMAL_PRIORITY_CLASS)�BELOW_NORMAL_PRIORITY_CLASS)�HIGH_PRIORITY_CLASS)�IDLE_PRIORITY_CLASS)�NORMAL_PRIORITY_CLASS)�REALTIME_PRIORITY_CLASS)�CONN_DELETE_TCB)�_psosx)�_psbsd)�_pssunos)�
CONN_BOUND)�	CONN_IDLE)�_psaixzplatform %s is not supportedr1r2r4r0r3�version_info�__version__rrrr
rrrrrrrrr!r rrr"rrrrrr�AF_LINKr#r$r%�POWER_TIME_UNKNOWN�POWER_TIME_UNLIMITEDr'r(r)r*r+r,r-r.r/r&�Process�Popen�
pid_exists�pids�process_iter�
wait_procs�virtual_memory�swap_memory�	cpu_times�cpu_percent�cpu_times_percent�	cpu_count�	cpu_stats�net_io_counters�net_connections�net_if_addrs�net_if_stats�disk_io_counters�disk_partitions�
disk_usage�users�	boot_timezGiampaolo Rodola'z5.4.3cCsg|]}t|��qS�)�int)�.0�numrprp� /usr/lib64/python3.6/__init__.py�
<listcomp>�sru�.Z	monotonic��versionzOversion conflict: %r C extension module was built for another version of psutil�__file__z (%s instead of %s)cCsg|]}|�qSrprp)rr�xrprprtru�sz (different than %s)z;; you may try to 'pip uninstall psutil', manually remove %sz%the existing psutil install directoryz1 or clean the virtual env somehow, then reinstall�ppid_mapc
CsPi}xFt�D]<}ytj|�}|j�}Wnttfk
r>YqX|||<qW|S)z{Return a {pid: ppid, ...} dict for all running processes in
        one shot. Used to speed up Process.children().
        )r]�_psplatformrZ�ppidr2r0)�ret�pid�procr}rprprt�	_ppid_maps
r�cstj���fdd��}|S)zpDecorator which raises NoSuchProcess in case a process is no
    longer running or its PID has been reused.
    cs&|j�st|j|j���|f|�|�S)N)�
is_runningr2r�_name)�self�args�kwargs)�funrprt�wrappersz'_assert_pid_not_reused.<locals>.wrapper)�	functools�wraps)r�r�rp)r�rt�_assert_pid_not_reusedsr�cCs8tj�}t||�}|dkr"d}nd}tjj|�j|�S)z(Format seconds in a human readable form.�<�z%H:%M:%Sz%Y-%m-%d %H:%M:%Sii�Q)�timerq�datetime�
fromtimestamp�strftime)ZsecsZnowZsecs_agoZfmtrprprt�_pprint_secs#sr�c@s�eZdZdZdwdd�Zdxdd�Zdd	�ZeZd
d�Zdd
�Z	dd�Z
edd��Ze
jdd��Zdydd�Zdd�Zdd�Zedd��Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zdzd*d+�Zer�ed,d-��Zd.d/�Zd0d1�Z d2d3�Z!e"e#j$d4��rd5d6�Z%e"e#j$d7��rd{d8d9�Z&e"e#j$d:��r4d|d;d<�Z'e"e#j$d=��rLd}d>d?�Z(e"e#j$d@��rbdAdB�Z)e"e#j$dC��rxdDdE�Z*e+�r�dFdG�Z,dHdI�Z-dJdK�Z.e"e#j$dL��r�dMdN�Z/e0d~dOdP��Z1ddQdR�Z2edSdT��Z3edUdV��Z4e5dWdX�dYdZ��Z6d[d\�Z7d�d^d_�Z8e"e#j$d`��rd�dbdc�Z9ddde�Z:d�dgdh�Z;e�r8didj�Z<e0dkdl��Z=e0dmdn��Z>e0dodp��Z?e0dqdr��Z@e0dsdt��ZAd�dudv�ZBdS)�rZa'Represents an OS process with the given PID.
    If PID is omitted current process PID (os.getpid()) is used.
    Raise NoSuchProcess if PID does not exist.

    Note that most of the methods of this class do not make sure
    the PID of the process being queried has been reused over time.
    That means you might end up retrieving an information referring
    to another process in case the original one this instance
    refers to is gone in the meantime.

    The only exceptions for which process identity is pre-emptively
    checked and guaranteed are:

     - parent()
     - children()
     - nice() (set)
     - ionice() (set)
     - rlimit() (set)
     - cpu_affinity (set)
     - suspend()
     - resume()
     - send_signal()
     - terminate()
     - kill()

    To prevent this problem for all other methods you can:
     - use is_running() before querying the process
     - if you're continuously iterating over a set of Process
       instances use process_iter() which pre-emptively checks
     process identity for every yielded instance
    NcCs|j|�dS)N)�_init)r�rrprprt�__init__TszProcess.__init__FcCs|dkrtj�}n6tr4t|ttf�r4td|��|dkrHtd|��||_d|_	d|_
d|_d|_d|_
d|_d|_tj|�|_d|_d|_y|j�WnXtk
r�YnFtk
r�Yn4tk
r�|s�d|}t|d|��nd|_YnX|j|jf|_dS)Nzpid must be an integer (got %r)rz'pid must be a positive integer (got %s)Fzno process found with pid %sT)�os�getpid�_PY3�
isinstancerqr
�	TypeError�
ValueError�_pidr��_exe�_create_time�_gone�_hash�_oneshot_inctx�_ppidr|rZ�_proc�_last_sys_cpu_times�_last_proc_cpu_times�create_timer0r4r2r�_ident)r�r�_ignore_nsp�msgrprprtr�Ws<
z
Process._initcCs�ytj�}Wntk
r$i}YnX|j|d<y$|j�|d<|jrRt|j�|d<WnHtk
rpd|d<Yn.tk
r�d|d<Ynt	k
r�YnXd|j
j|j
jdj
d	d
�|j�D��fS)Nr�nameZstartedZzombie�statusZ
terminatedz	%s.%s(%s)z, cSsg|]\}}d||f�qS)z%s=%rrp)rr�k�vrprprtru�sz#Process.__str__.<locals>.<listcomp>)�collections�OrderedDict�AttributeErrorrr�r�r�r4r2r0�	__class__�
__module__�__name__�join�items)r��inforprprt�__str__�s&

zProcess.__str__cCst|t�stS|j|jkS)N)r�rZ�NotImplementedr�)r��otherrprprt�__eq__�s
zProcess.__eq__cCs
||kS)Nrp)r�r�rprprt�__ne__�szProcess.__ne__cCs|jdkrt|j�|_|jS)N)r��hashr�)r�rprprt�__hash__�s
zProcess.__hash__cCs|jS)zThe process PID.)r�)r�rprprtr�szProcess.pidccs�|jrdVn�d|_z@|jj�|jj�|jj�trB|jj�|jj�dVWd|jj	�|jj	�|jj	�tr�|jj	�|jj
�d|_XdS)a#Utility context manager which considerably speeds up the
        retrieval of multiple process information at the same time.

        Internally different process info (e.g. name, ppid, uids,
        gids, ...) may be fetched by using the same routine, but
        only one information is returned and the others are discarded.
        When using this context manager the internal routine is
        executed once (in the example below on name()) and the
        other info are cached.

        The cache is cleared when exiting the context manager block.
        The advice is to use this every time you retrieve more than
        one information about the process. If you're lucky, you'll
        get a hell of a speedup.

        >>> import psutil
        >>> p = psutil.Process()
        >>> with p.oneshot():
        ...     p.name()  # collect multiple info
        ...     p.cpu_times()  # return cached value
        ...     p.cpu_percent()  # return cached value
        ...     p.create_time()  # return cached value
        ...
        >>>
        NTF)r�rbZcache_activate�memory_infor}r-�uidsr�Z
oneshot_enterZcache_deactivateZoneshot_exit)r�rprprt�oneshot�s$











zProcess.oneshotc
Cst}|dk	rnt|ttttf�s.tdt|���t|�}||}|rntdt	|�dkrVdnddj
tt|��f��t
�}|pz|}|j��xxp|D]h}y$|dkr�|j}nt||�}	|	�}Wn6ttfk
r�|}Yntk
r�|r�w�YnX|||<q�WWdQRX|S)	a�Utility method returning process information as a
        hashable dictionary.
        If *attrs* is specified it must be a list of strings
        reflecting available Process class' attribute names
        (e.g. ['cpu_times', 'name']) else all public (read
        only) attributes are assumed.
        *ad_value* is the value which gets assigned in case
        AccessDenied or ZombieProcess exception is raised when
        retrieving that particular process information.
        Nzinvalid attrs type %szinvalid attr name%s %sr�srwz, r)�_as_dict_attrnamesr��list�tuple�set�	frozensetr��typer��lenr��map�repr�dictr�r�getattrr0r4�NotImplementedError)
r��attrs�ad_valueZvalid_names�
invalid_namesZretdictZlsr�r~�methrprprt�as_dict�s6



zProcess.as_dictcCsN|j�}|dk	rJ|j�}yt|�}|j�|kr2|SWntk
rHYnXdS)z�Return the parent process as a Process object pre-emptively
        checking whether PID has been reused.
        If no parent is known return None.
        N)r}r�rZr2)r�r}�ctime�parentrprprtr�szProcess.parentcCsJ|jr
dSy|t|j�kStk
r,dStk
rDd|_dSXdS)z�Return whether this process is running.
        It also checks if PID has been reused by another process in
        which case return False.
        FTN)r�rZrr4r2)r�rprprtr�-szProcess.is_runningcCs*tr|jj�S|jp|jj�|_|jSdS)z`The process parent PID.
        On Windows the return value is cached after first call.
        N)r-r�r}r�)r�rprprtr}Es
zProcess.ppidcCs�tr|jdk	r|jS|jj�}trrt|�dkrry|j�}Wntk
rNYn$X|rrtj	j
|d�}|j|�rr|}||_||j_|S)z>The process name. The return value is cached after first call.N�r)r/r�r�r�r-r��cmdliner0r��path�basename�
startswith)r�r�r�Z
extended_namerprprtr�Ws

zProcess.namecs��fdd�}�jdkrzy�jj�}Wn&tk
rJ}z
||d�Sd}~Xn0X|sty||d�}Wntk
rrYnX|�_�jS)z�The process executable as an absolute path.
        May also be an empty string.
        The return value is cached after first call.
        csd�j�}|rRttd�rRttd�rR|d}tjj|�rRtjj|�rRtj|tj�rR|St|t	�r`|�|S)N�access�X_OKr)
r��hasattrr�r��isabs�isfiler�r�r�r0)�fallbackr��exe)r�rprt�guess_itvs
zProcess.exe.<locals>.guess_itN)r�)r�r�r�r0)r�r�r��errrp)r�rtr�qs
zProcess.execCs
|jj�S)z3The command line this process has been called with.)r�r�)r�rprprtr��szProcess.cmdlinecCs$y
|jj�Stk
rtSXdS)z2The process current status as a STATUS_* constant.N)r�r�r4r)r�rprprtr��s
zProcess.statuscCsTtrFtdkrtd��|j�j}ytj|�jStk
rBt|�SXn
|j	j
�SdS)ztThe name of the user that owns the process.
        On UNIX this is calculated by using *real* process uid.
        Nz0requires pwd module shipped with standard python)r-�pwd�ImportErrorr��real�getpwuidZpw_name�KeyError�strr��username)r�Zreal_uidrprprtr��s
zProcess.usernamecCs|jdkr|jj�|_|jS)z�The process creation time as a floating point number
        expressed in seconds since the epoch, in UTC.
        The return value is cached after first call.
        N)r�r�r�)r�rprprtr��s
zProcess.create_timecCs
|jj�S)z6Process current working directory as an absolute path.)r��cwd)r�rprprtr��szProcess.cwdcCs8|dkr|jj�S|j�s(t|j|j��|jj|�dS)z'Get or set process niceness (priority).N)r�Znice_getr�r2rr�Znice_set)r��valuerprprt�nice�s

zProcess.nicecCs
|jj�S)zVReturn process UIDs as a (real, effective, saved)
            namedtuple.
            )r�r�)r�rprprtr��szProcess.uidscCs
|jj�S)zVReturn process GIDs as a (real, effective, saved)
            namedtuple.
            )r��gids)r�rprprtr��szProcess.gidscCs
|jj�S)zVThe terminal associated with this process, if any,
            else None.
            )r��terminal)r�rprprtr��szProcess.terminalcCs
|jj�S)zcReturn the number of file descriptors opened by this
            process (POSIX only).
            )r��num_fds)r�rprprtr��szProcess.num_fds�io_counterscCs
|jj�S)a
Return process I/O statistics as a
            (read_count, write_count, read_bytes, write_bytes)
            namedtuple.
            Those are the number of read/write calls performed and the
            amount of bytes read and written by the process.
            )r�r�)r�rprprtr��szProcess.io_counters�
ionice_getcCs4|dkr"|dk	rtd��|jj�S|jj||�SdS)a�Get or set process I/O niceness (priority).

            On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
            *value* is a number which goes from 0 to 7. The higher the
            value, the lower the I/O priority of the process.

            On Windows only *ioclass* is used and it can be set to 2
            (normal), 1 (low) or 0 (very low).

            Available on Linux and Windows > Vista only.
            Nz$'ioclass' argument must be specified)r�r�r�Z
ionice_set)r�Zioclassr�rprprt�ionice�s

zProcess.ionice�rlimitcCs&|dkr|jj|�S|jj||�SdS)a"Get or set process resource limits as a (soft, hard)
            tuple.

            *resource* is one of the RLIMIT_* constants.
            *limits* is supposed to be a (soft, hard)  tuple.

            See "man prlimit" for further info.
            Available on Linux only.
            N)r�r�)r�ZresourceZlimitsrprprtr�s
zProcess.rlimit�cpu_affinity_getcCsd|dkrtt|jj���S|sLt|jd�r6|jj�}ntttt	dd����}|jj
tt|���dS)a-Get or set process CPU affinity.
            If specified, *cpus* must be a list of CPUs for which you
            want to set the affinity (e.g. [0, 1]).
            If an empty list is passed, all egible CPUs are assumed
            (and set).
            (Windows, Linux and BSD only).
            N�_get_eligible_cpusT)�percpu)r�r�r�r�r�r�r��ranger�rbZcpu_affinity_set)r�Zcpusrprprt�cpu_affinityszProcess.cpu_affinity�cpu_numcCs
|jj�S)aZReturn what CPU this process is currently running on.
            The returned number should be <= psutil.cpu_count()
            and <= len(psutil.cpu_percent(percpu=True)).
            It may be used in conjunction with
            psutil.cpu_percent(percpu=True) to observe the system
            workload distributed across CPUs.
            )r�r�)r�rprprtr�5szProcess.cpu_num�environcCs
|jj�S)z�The environment variables of the process as a dict.  Note: this
            might not reflect changes made after the process started.  )r�r�)r�rprprtr�BszProcess.environcCs
|jj�S)z\Return the number of handles opened by this process
            (Windows only).
            )r��num_handles)r�rprprtr�IszProcess.num_handlescCs
|jj�S)zkReturn the number of voluntary and involuntary context
        switches performed by this process.
        )r��num_ctx_switches)r�rprprtr�OszProcess.num_ctx_switchescCs
|jj�S)z2Return the number of threads used by this process.)r��num_threads)r�rprprtr�UszProcess.num_threads�threadscCs
|jj�S)z�Return threads opened by process as a list of
            (id, user_time, system_time) namedtuples representing
            thread id and thread CPU times (user/system).
            On OpenBSD this method requires root access.
            )r�r�)r�rprprtr�[szProcess.threadsc
Cs<t�}g}|spx^|j�D]R\}}||jkry&t|�}|j�|j�krN|j|�Wqttfk
rhYqXqWn�tj	t
�}x"|j�D]\}}||j|�q�Wt�}|jg}	x�|	�r6|	j�}||kr�q�|j
|�xb||D]V}
y6t|
�}|j�|j�k}|�r|j|�|	j|
�Wq�ttfk
�r.Yq�Xq�Wq�W|S)u(Return the children of this process as a list of Process
        instances, pre-emptively checking whether PID has been reused.
        If *recursive* is True return all the parent descendants.

        Example (A == this process):

         A ─┐
            │
            ├─ B (child) ─┐
            │             └─ X (grandchild) ─┐
            │                                └─ Y (great grandchild)
            ├─ C (child)
            └─ D (child)

        >>> import psutil
        >>> p = psutil.Process()
        >>> p.children()
        B, C, D
        >>> p.children(recursive=True)
        B, X, Y, C, D

        Note that in the example above if process X disappears
        process Y won't be listed as the reference to process A
        is lost.
        )r�r�rrZr��appendr2r4r��defaultdictr�r��pop�add)r��	recursiver{r~rr}ZchildZreverse_ppid_map�seen�stackZ	child_pidZintimerprprt�childrencs>



zProcess.childrencs|dk	o|dk}|dk	r,|dkr,td|��t�p4d��fdd�}|rr|�}|jj�}tj|�|�}|jj�}n<|j}|j}|�}|jj�}|dks�|dkr�||_||_dS|j|j|j	|j	}||}	||_||_y||	d}
Wnt
k
�rdSX|
�}t|d�SdS)	aReturn a float representing the current process CPU
        utilization as a percentage.

        When *interval* is 0.0 or None (default) compares process times
        to system CPU times elapsed since last call, returning
        immediately (non-blocking). That means that the first time
        this is called it will return a meaningful 0.0 value.

        When *interval* is > 0.0 compares process times to system CPU
        times elapsed before and after the interval (blocking).

        In this case is recommended for accuracy that this function
        be called with at least 0.1 seconds between calls.

        A value > 100.0 can be returned in case of processes running
        multiple threads on different CPU cores.

        The returned value is explicitly NOT split evenly between
        all available logical CPUs. This means that a busy loop process
        running on a system with 2 logical CPUs will be reported as
        having 100% CPU utilization instead of 50%.

        Examples:

          >>> import psutil
          >>> p = psutil.Process(os.getpid())
          >>> # blocking
          >>> p.cpu_percent(interval=1)
          2.0
          >>> # non-blocking (percentage since last call)
          >>> p.cpu_percent(interval=None)
          2.9
          >>>
        Ngrz!interval is not positive (got %r)rcs
t��S)N)�_timerrp)�num_cpusrprt�timer�sz"Process.cpu_percent.<locals>.timer�d)r�rer�rbr��sleepr�r��user�system�ZeroDivisionError�round)r��interval�blockingrZst1Zpt1Zst2Zpt2Z
delta_procZ
delta_timeZoverall_cpus_percentZsingle_cpu_percentrp)rrtrc�s:#



zProcess.cpu_percentcCs
|jj�S)a#Return a (user, system, children_user, children_system)
        namedtuple representing the accumulated process time, in
        seconds.
        This is similar to os.times() but per-process.
        On OSX and Windows children_user and children_system are
        always set to 0.
        )r�rb)r�rprprtrbs	zProcess.cpu_timescCs
|jj�S)aReturn a namedtuple with variable fields depending on the
        platform, representing memory information about the process.

        The "portable" fields available on all plaforms are `rss` and `vms`.

        All numbers are expressed in bytes.
        )r�r�)r�rprprtr�s	zProcess.memory_infor�)ZreplacementcCs|j�S)N)r�)r�rprprt�memory_info_exszProcess.memory_info_excCs
|jj�S)a[This method returns the same information as memory_info(),
        plus, on some platform (Linux, OSX, Windows), also provides
        additional metrics (USS, PSS and swap).
        The additional metrics provide a better representation of actual
        process memory usage.

        Namely USS is the memory which is unique to a process and which
        would be freed if the process was terminated right now.

        It does so by passing through the whole process address.
        As such it usually requires higher user privileges than
        memory_info() and is considerably slower.
        )r��memory_full_info)r�rprprtrszProcess.memory_full_info�rsscCs�ttjj�}||kr(td|t|�f��|tjjkr:|jn|j}|�}t	||�}t
pZt�j}|dksptd|��|t
|�dS)a�Compare process memory to total physical system memory and
        calculate process memory utilization as a percentage.
        *memtype* argument is a string that dictates what type of
        process memory you want to compare against (defaults to "rss").
        The list of available strings can be obtained like this:

        >>> psutil.Process().memory_info()._fields
        ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
        z&invalid memtype %r; valid types are %rrz`can't calculate process memory percent because total physical system memory is not positive (%r)r	)r�r|Zpfullmem�_fieldsr�r�Zpmemr�rr��
_TOTAL_PHYMEMr`�total�float)r�ZmemtypeZvalid_typesr�Zmetricsr�Ztotal_phymemrprprt�memory_percent/s

zProcess.memory_percent�memory_mapsTcs�|jj�}|r�i�xZ|D]R}|d}|dd�}ytdd��||��|<Wqtk
rh|�|<YqXqWtj���fdd��D�Stj��fdd�|D�SdS)	a�Return process' mapped memory regions as a list of namedtuples
            whose fields are variable depending on the platform.

            If *grouped* is True the mapped regions with the same 'path'
            are grouped together and the different memory fields are summed.

            If *grouped* is False every mapped region is shown as a single
            entity and the namedtuple will also include the mapped region's
            address space ('addr') and permission set ('perms').
            ��NcSs||S)Nrp)rz�yrprprt�<lambda>`sz%Process.memory_maps.<locals>.<lambda>csg|]}�|f�|���qSrprp)rrr�)�d�ntrprtrudsz'Process.memory_maps.<locals>.<listcomp>csg|]}�|��qSrprp)rrrz)rrprtrugs)r�rr�r�r|Z
pmmap_groupedZ	pmmap_ext)r�Zgrouped�itZtuplr��numsrp)rrrtrNs

zProcess.memory_mapscCs
|jj�S)z�Return files opened by process as a list of
        (path, fd) namedtuples including the absolute file name
        and file descriptor number.
        )r��
open_files)r�rprprtr"iszProcess.open_files�inetcCs|jj|�S)aTReturn socket connections opened by process as a list of
        (fd, family, type, laddr, raddr, status) namedtuples.
        The *kind* parameter filters for connections that match the
        following criteria:

        +------------+----------------------------------------------------+
        | Kind Value | Connections using                                  |
        +------------+----------------------------------------------------+
        | inet       | IPv4 and IPv6                                      |
        | inet4      | IPv4                                               |
        | inet6      | IPv6                                               |
        | tcp        | TCP                                                |
        | tcp4       | TCP over IPv4                                      |
        | tcp6       | TCP over IPv6                                      |
        | udp        | UDP                                                |
        | udp4       | UDP over IPv4                                      |
        | udp6       | UDP over IPv6                                      |
        | unix       | UNIX socket (both UDP and TCP protocols)           |
        | all        | the sum of all the possible families and protocols |
        +------------+----------------------------------------------------+
        )r��connections)r��kindrprprtr$pszProcess.connectionscCs�|jdkst|j��|jdkr(td��ytj|j|�Wn�tk
r�}zj|jtjkr�trzt	|j�rzt
|j|j|j��nd|_
t|j|j��|jtjtjfkr�t|j|j���WYdd}~XnXdS)Nrz�preventing sending signal to process with PID 0 as it would affect every process in the process group of the calling process (os.getpid()) instead of PID 0T)r�AssertionErrorr�r��kill�OSError�errnoZESRCHr+r\r4r�r�r�r2ZEPERMZEACCESr0)r��sigr�rprprt�_send_signal�s
zProcess._send_signalcCs`tr|j|�nL|tjkr&|jj�n6|ttdt��ttdt��fkrT|jj|�nt	d��dS)z�Send a signal *sig* to process pre-emptively checking
        whether PID has been reused (see signal module constants) .
        On Windows only SIGTERM is valid and is treated as an alias
        for kill().
        ZCTRL_C_EVENTZCTRL_BREAK_EVENTzPonly SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals are supported on WindowsN)
r-r+�signal�SIGTERMr�r'r��object�send_signalr�)r�r*rprprtr/�s
zProcess.send_signalcCs tr|jtj�n
|jj�dS)z�Suspend process execution with SIGSTOP pre-emptively checking
        whether PID has been reused.
        On Windows this has the effect ot suspending all process threads.
        N)r-r+r,�SIGSTOPr��suspend)r�rprprtr1�szProcess.suspendcCs tr|jtj�n
|jj�dS)z�Resume process execution with SIGCONT pre-emptively checking
        whether PID has been reused.
        On Windows this has the effect of resuming all process threads.
        N)r-r+r,�SIGCONTr��resume)r�rprprtr3�szProcess.resumecCs tr|jtj�n
|jj�dS)z�Terminate the process with SIGTERM pre-emptively checking
        whether PID has been reused.
        On Windows this is an alias for kill().
        N)r-r+r,r-r�r')r�rprprt�	terminate�szProcess.terminatecCs tr|jtj�n
|jj�dS)zjKill the current process with SIGKILL pre-emptively checking
        whether PID has been reused.
        N)r-r+r,�SIGKILLr�r')r�rprprtr'�szProcess.killcCs&|dk	r|dkrtd��|jj|�S)a�Wait for process to terminate and, if process is a children
        of os.getpid(), also return its exit code, else None.

        If the process is already terminated immediately return None
        instead of raising NoSuchProcess.

        If *timeout* (in seconds) is specified and process is still
        alive raise TimeoutExpired.

        To wait for multiple Process(es) use psutil.wait_procs().
        Nrz"timeout must be a positive integer)r�r��wait)r��timeoutrprprtr6�szProcess.wait)N)F)NN)N)NN)N)N)F)N)r)T)r#)N)Cr�r��__qualname__�__doc__r�r�r��__repr__r�r�r��propertyr�
contextlib�contextmanagerr�r�r�r�rr}r�r�r�r�r�r�r�r�r-r�r�r�r�r�r|rZr�r�r�r�r�r�r/r�r�r�r�r�rrcrbr�rrrrrr"r$r+r/r1r3r4r'r6rprprprtrZ3s�

/>
,'	
	



E
\



csJeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zd�fd
d�	Z	�Z
S)r[azA more convenient interface to stdlib subprocess.Popen class.
    It starts a sub process and deals with it exactly as when using
    subprocess.Popen class but in addition also provides all the
    properties and methods of psutil.Process class as a unified
    interface:

      >>> import psutil
      >>> from subprocess import PIPE
      >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
      >>> p.name()
      'python'
      >>> p.uids()
      user(real=1000, effective=1000, saved=1000)
      >>> p.username()
      'giampaolo'
      >>> p.communicate()
      ('hi
', None)
      >>> p.terminate()
      >>> p.wait(timeout=2)
      0
      >>>

    For method names common to both classes such as kill(), terminate()
    and wait(), psutil.Process implementation takes precedence.

    Unlike subprocess.Popen this class pre-emptively checks whether PID
    has been reused on send_signal(), terminate() and kill() so that
    you don't accidentally terminate another process, fixing
    http://bugs.python.org/issue6973.

    For a complete documentation refer to:
    http://docs.python.org/library/subprocess.html
    cOs$tj||�|_|j|jjdd�dS)NT)r�)�
subprocessr[�_Popen__subprocr�r)r�r�r�rprprtr�szPopen.__init__cCstttt�ttj���S)N)�sortedr��dirr[r>)r�rprprt�__dir__"sz
Popen.__dir__cCst|jd�r|jj�|S)N�	__enter__)r�r?rC)r�rprprtrC%s
zPopen.__enter__c
Os^t|jd�r|jj||�S|jr*|jj�|jr:|jj�z|jrL|jj�Wd|j�XdS)N�__exit__)r�r?rD�stdout�close�stderr�stdinr6)r�r�r�rprprtrD*s

zPopen.__exit__cCs^ytj||�Stk
rXytj|j|�Stk
rRtd|jj|f��YnXYnXdS)Nz!%s instance has no attribute '%s')r.�__getattribute__r�r?r�r�)r�r�rprprtrI:szPopen.__getattribute__Ncs0|jjdk	r|jjStt|�j|�}||j_|S)N)r?�
returncode�superr[r6)r�r7r~)r�rprtr6Ds
z
Popen.wait)N)r�r�r8r9r�rBrCrDrIr6�
__classcell__rprp)r�rtr[�s!
cCs$g|]}|jd�r|dkr|�qS)�_r/r1r3r4r'r6r�r�r�rr�rr�)
r/r1r3r4r'r6r�r�r�rr�rr�)r�)rrrzrprprtruNscCstj�S)z&Return a list of current running PIDs.)r|r]rprprprtr]YscCs0|dkrdS|dkr"tr"|t�kStj|�SdS)z�Return True if given PID exists in the current process list.
    This is faster than doing "pid in psutil.pids()" and
    should be preferred.
    rFN)r-r]r|r\)rrprprtr\^s

c
#s@��fdd�}dd�}tt��}ttj��}||}||}x|D]}||�qBWx�tttj��ttj|�j���D]�\}}	yJ|	dkr�||�Vn2|	j	�r��dk	r�|	j
��d�|	_|	Vn
||�VWqvtk
r�||�Yqvt
k
�r6|	dk�r0|tk�r0yt|VWntk
�r,YnXn�YqvXqvWdS)aReturn a generator yielding a Process instance for all
    running processes.

    Every new Process instance is only created once and then cached
    into an internal table which is updated every time this is used.

    Cached Process instances are checked for identity so that you're
    safe in case a PID has been reused by another process, in which
    case the cached instance is updated.

    The sorting order in which processes are yielded is based on
    their PIDs.

    *attrs* and *ad_value* have the same meaning as in
    Process.as_dict(). If *attrs* is specified as_dict() is called
    and the resulting dict is stored as a 'info' attribute attached
    to returned Process instance.
    If *attrs* is an empty list it will retrieve all process info
    (slow).
    cs.t|�}�dk	r |j��d�|_|t|j<|S)N)r�r�)rZr�r��_pmapr)rr�)r�r�rprtr�s

zprocess_iter.<locals>.addcSstj|d�dS)N)rNr)rrprprt�remove�szprocess_iter.<locals>.removeN)r�r�)r�r]rN�keysr@r�r�r��fromkeysr�r�r�r2r0r�)
r�r�rrO�a�bZnew_pidsZ	gone_pidsrr�rp)r�r�rtr^ss8

c	s��fdd�}|dk	r0|dkr0d|}t|��t��t|�}�dk	r\t��r\tdt��|dk	rnt�|}xt|r�|dk	r�|dkr�PxP|D]H}dt|�}|dk	r�t|t�|�}|dkr�P|||�q�|||�q�W|�}qpW|�r
x|D]}||d�q�W|�}t��t|�fS)a,Convenience function which waits for a list of processes to
    terminate.

    Return a (gone, alive) tuple indicating which processes
    are gone and which ones are still alive.

    The gone ones will have a new *returncode* attribute indicating
    process exit status (may be None).

    *callback* is a function which gets called every time a process
    terminates (a Process instance is passed as callback argument).

    Function will return as soon as all processes terminate or when
    *timeout* occurs.
    Differently from Process.wait() it will not raise TimeoutExpired if
    *timeout* occurs.

    Typical use case is:

     - send SIGTERM to a list of processes
     - give them some time to terminate
     - send SIGKILL to those ones which are still alive

    Example:

    >>> def on_terminate(proc):
    ...     print("process {} terminated".format(proc))
    ...
    >>> for p in procs:
    ...    p.terminate()
    ...
    >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
    >>> for p in alive:
    ...     p.kill()
    cs\y|j|d�}Wntk
r$Yn4X|dk	s8|j�rX||_�j|��dk	rX�|�dS)N)r7)r6r3r�rJr)r�r7rJ)�callback�gonerprt�
check_gone�s
zwait_procs.<locals>.check_goneNrz*timeout must be a positive integer, got %szcallback %r is not a callableg�?)r�r�r	r�rr��minr�)	Zprocsr7rTrVr��aliveZdeadliner�Zmax_timeoutrp)rTrUrtr_�s6$


TcCs.|rtj�}ntj�}|dk	r*|dkr*d}|S)azReturn the number of logical CPUs in the system (same as
    os.cpu_count() in Python 3.4).

    If *logical* is False return the number of physical cores only
    (e.g. hyper thread CPUs are excluded).

    Return None if undetermined.

    The return value is cached after first call.
    If desired cache can be cleared like this:

    >>> psutil.cpu_count.cache_clear()
    Nr)r|Zcpu_count_logicalZcpu_count_physical)Zlogicalr~rprprtres
FcCs|stj�Stj�SdS)a�Return system-wide CPU times as a namedtuple.
    Every CPU time represents the seconds the CPU has spent in the
    given mode. The namedtuple's fields availability varies depending on the
    platform:

     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
     - steal (Linux >= 2.6.11)
     - guest (Linux >= 2.6.24)
     - guest_nice (Linux >= 3.2.0)

    When *percpu* is True return a list of namedtuples for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.
    N)r|rbZ
per_cpu_times)r�rprprtrb-s)r�cCs0t|�}tr,|t|dd�8}|t|dd�8}|S)zWGiven a cpu_time() ntuple calculates the total CPU time
    (including idle time).
    ZguestrZ
guest_nice)�sumr)r�)�timesZtotrprprt�
_cpu_tot_timeXs
	r[cCs&t|�}||j8}|t|dd�8}|S)zlGiven a cpu_time() ntuple calculates the busy CPU time.
    We do so by subtracting all idle CPU times.
    Ziowaitr)r[Zidler�)rZZbusyrprprt�_cpu_busy_timeks
r\cCs�|dk	o|dk}|dk	r,|dkr,td|��dd�}|sp|rNt�}tj|�nt}|dkr`t�}t�a||t�Sg}|r�tdd�}tj|�nt}|dkr�tdd�}tdd�ax&t|t�D]\}}|j|||��q�W|SdS)	a�Return a float representing the current system-wide CPU
    utilization as a percentage.

    When *interval* is > 0.0 compares system CPU times elapsed before
    and after the interval (blocking).

    When *interval* is 0.0 or None compares system CPU times elapsed
    since last call or module import, returning immediately (non
    blocking). That means the first time this is called it will
    return a meaningless 0.0 value which you should ignore.
    In this case is recommended for accuracy that this function be
    called with at least 0.1 seconds between calls.

    When *percpu* is True returns a list of floats representing the
    utilization as a percentage for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.

    Examples:

      >>> # blocking, system-wide
      >>> psutil.cpu_percent(interval=1)
      2.0
      >>>
      >>> # blocking, per-cpu
      >>> psutil.cpu_percent(interval=1, percpu=True)
      [2.0, 1.0]
      >>>
      >>> # non-blocking (percentage since last call)
      >>> psutil.cpu_percent(interval=None)
      2.9
      >>>
    Ngrz!interval is not positive (got %r)c	Sspt|�}t|�}t|�}t|�}||kr,dS||}||}y||d}Wntk
r`dSXt|d�SdS)Ngr	r)r[r\r
r)	�t1�t2Zt1_allZt1_busyZt2_allZt2_busyZ
busy_delta�	all_deltaZ	busy_percrprprt�	calculate�szcpu_percent.<locals>.calculateT)r�)r�rbr�r
�_last_cpu_times�_last_per_cpu_times�zipr�)rr�rr`r]r~�tot1r^rprprtrc{s0%



cCs�|dk	o|dk}|dk	r,|dkr,td|��dd�}|sp|rNt�}tj|�nt}|dkr`t�}t�a||t�Sg}|r�tdd�}tj|�nt}|dkr�tdd�}tdd�ax&t|t�D]\}}|j|||��q�W|SdS)	a�Same as cpu_percent() but provides utilization percentages
    for each specific CPU time as is returned by cpu_times().
    For instance, on Linux we'll get:

      >>> cpu_times_percent()
      cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
                 irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
      >>>

    *interval* and *percpu* arguments have the same meaning as in
    cpu_percent().
    Ngrz!interval is not positive (got %r)cSs�g}t|�t|�}xz|jD]p}t||�t||�}yd||}Wntk
r\d}YnXt|d�}|dkrvd}n|dkr�d}|j|�qWtj|�S)Nr	grgY@)r[rr�r
rr�r|Z	scputimes)r]r^r!r_ZfieldZfield_deltaZ
field_percrprprtr`�s


z$cpu_times_percent.<locals>.calculateT)r�)r�rbr�r
�_last_cpu_times_2�_last_per_cpu_times_2rcr�)rr�rr`r]r~rdr^rprprtrd�s0



cCstj�S)zReturn CPU statistics.)r|rfrprprprtrf/s�cpu_freqc
Cs�tj�}|r|Stt|��}|dkr(dS|dkr8|dSd\}}}x*|D]"}||j7}||j7}||j7}qHW||}||}||}	tj|||	�SdS)a9Return CPU frequency as a nameduple including current,
        min and max frequency expressed in Mhz.

        If *percpu* is True and the system supports per-cpu frequency
        retrieval (Linux only) a list of frequencies is returned for
        each CPU. If not a list with one element is returned.
        rNr�)rhrhrh)	r|rgrr��currentrW�maxrZscpufreq)
r�r~rZcurrsZminsZmaxsZcpuriZmin_Zmax_rprprtrg6s"



cCstj�}|ja|S)a�Return statistics about system memory usage as a namedtuple
    including the following fields, expressed in bytes:

     - total:
       total physical memory available.

     - available:
       the memory that can be given instantly to processes without the
       system going into swap.
       This is calculated by summing different memory values depending
       on the platform and it is supposed to be used to monitor actual
       memory usage in a cross platform fashion.

     - percent:
       the percentage usage calculated as (total - available) / total * 100

     - used:
        memory used, calculated differently depending on the platform and
        designed for informational purposes only:
        OSX: active + inactive + wired
        BSD: active + wired + cached
        LINUX: total - free

     - free:
       memory not being used at all (zeroed) that is readily available;
       note that this doesn't reflect the actual memory available
       (use 'available' instead)

    Platform-specific fields:

     - active (UNIX):
       memory currently in use or very recently used, and so it is in RAM.

     - inactive (UNIX):
       memory that is marked as not used.

     - buffers (BSD, Linux):
       cache for things like file system metadata.

     - cached (BSD, OSX):
       cache for various things.

     - wired (OSX, BSD):
       memory that is marked to always stay in RAM. It is never moved to disk.

     - shared (BSD):
       memory that may be simultaneously accessed by multiple processes.

    The sum of 'used' and 'available' does not necessarily equal total.
    On Windows 'available' and 'free' are the same.
    )r|r`rr)r~rprprtr`Zs5cCstj�S)a�Return system swap memory statistics as a namedtuple including
    the following fields:

     - total:   total swap memory in bytes
     - used:    used swap memory in bytes
     - free:    free swap memory in bytes
     - percent: the percentage usage
     - sin:     no. of bytes the system has swapped in from disk (cumulative)
     - sout:    no. of bytes the system has swapped out from disk (cumulative)

    'sin' and 'sout' on Windows are meaningless and always set to 0.
    )r|rarprprprtra�s
cCs
tj|�S)z�Return disk usage statistics about the given *path* as a
    namedtuple including total, used and free space expressed in bytes
    plus the percentage usage.
    )r|rm)r�rprprtrm�scCs
tj|�S)a3Return mounted partitions as a list of
    (device, mountpoint, fstype, opts) namedtuple.
    'opts' field is a raw string separated by commas indicating mount
    options which may vary depending on the platform.

    If *all* parameter is False return physical devices only and ignore
    all others.
    )r|rl)�allrprprtrl�s	cCs|tj�}|s|riSdS|r&t|d�}ttdtj�}|r^x |j�D]\}}||�||<qBW|S|dd�t|j��D��SdS)a�Return system disk I/O statistics as a namedtuple including
    the following fields:

     - read_count:  number of reads
     - write_count: number of writes
     - read_bytes:  number of bytes read
     - write_bytes: number of bytes written
     - read_time:   time spent reading from disk (in ms)
     - write_time:  time spent writing to disk (in ms)

    Platform specific:

     - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
     - read_merged_count (Linux): number of merged reads
     - write_merged_count (Linux): number of merged writes

    If *perdisk* is True return the same information for every
    physical disk installed on the system as a dictionary
    with partition names as the keys and the namedtuple
    described above as the values.

    If *nowrap* is True it detects and adjust the numbers which overflow
    and wrap (restart from 0) and add "old value" to "new value" so that
    the returned numbers will always be increasing or remain the same,
    but never decrease.
    "disk_io_counters.cache_clear()" can be used to invalidate the
    cache.

    On recent Windows versions 'diskperf -y' command may need to be
    executed first otherwise this function won't find any disk.
    Nzpsutil.disk_io_counters�sdiskiocSsg|]}t|��qSrp)rY)rrrzrprprtru�sz$disk_io_counters.<locals>.<listcomp>)	r|rk�
_wrap_numbersr�rrlr�rc�values)Zperdisk�nowrap�rawdictrZdisk�fieldsrprprtrk�s 
zpsutil.disk_io_counterszClears nowrap argument cachecCsrtj�}|s|riSdS|r&t|d�}|rRx"|j�D]\}}tj|�||<q4W|Stjdd�t|j��D��SdS)abReturn network I/O statistics as a namedtuple including
    the following fields:

     - bytes_sent:   number of bytes sent
     - bytes_recv:   number of bytes received
     - packets_sent: number of packets sent
     - packets_recv: number of packets received
     - errin:        total number of errors while receiving
     - errout:       total number of errors while sending
     - dropin:       total number of incoming packets which were dropped
     - dropout:      total number of outgoing packets which were dropped
                     (always 0 on OSX and BSD)

    If *pernic* is True return the same information for every
    network interface installed on the system as a dictionary
    with network interface names as the keys and the namedtuple
    described above as the values.

    If *nowrap* is True it detects and adjust the numbers which overflow
    and wrap (restart from 0) and add "old value" to "new value" so that
    the returned numbers will always be increasing or remain the same,
    but never decrease.
    "disk_io_counters.cache_clear()" can be used to invalidate the
    cache.
    Nzpsutil.net_io_counterscSsg|]}t|��qSrp)rY)rrrzrprprtrusz#net_io_counters.<locals>.<listcomp>)r|rgrmr�rZsnetiorcrn)ZpernicrorpZnicrqrprprtrg�s
zpsutil.net_io_countersr#cCs
tj|�S)a�Return system-wide socket connections as a list of
    (fd, family, type, laddr, raddr, status, pid) namedtuples.
    In case of limited privileges 'fd' and 'pid' may be set to -1
    and None respectively.
    The *kind* parameter filters for connections that fit the
    following criteria:

    +------------+----------------------------------------------------+
    | Kind Value | Connections using                                  |
    +------------+----------------------------------------------------+
    | inet       | IPv4 and IPv6                                      |
    | inet4      | IPv4                                               |
    | inet6      | IPv6                                               |
    | tcp        | TCP                                                |
    | tcp4       | TCP over IPv4                                      |
    | tcp6       | TCP over IPv6                                      |
    | udp        | UDP                                                |
    | udp4       | UDP over IPv4                                      |
    | udp6       | UDP over IPv6                                      |
    | unix       | UNIX socket (both UDP and TCP protocols)           |
    | all        | the sum of all the possible families and protocols |
    +------------+----------------------------------------------------+

    On OSX this function requires root privileges.
    )r|rh)r%rprprtrh"scCstjdk}|rddl}tj�}|jdd�d�tjt�}x�|D]�\}}}}}}	|r�y|j	|�}WnBt
k
r�tr�|dkr�tj}nt
td	�r�tj|kr�tj}YnX|tjkr�tr�d
nd}
x|j|
�dkr�|d
|
7}q�W||jtj|||||	��q>Wt|�S)a*Return the addresses associated to each NIC (network interface
    card) installed on the system as a dictionary whose keys are the
    NIC names and value is a list of namedtuples for each address
    assigned to the NIC. Each namedtuple includes 5 fields:

     - family: can be either socket.AF_INET, socket.AF_INET6 or
               psutil.AF_LINK, which refers to a MAC address.
     - address: is the primary address and it is always set.
     - netmask: and 'broadcast' and 'ptp' may be None.
     - ptp: stands for "point to point" and references the
            destination address on a point to point interface
            (typically a VPN).
     - broadcast: and *ptp* are mutually exclusive.

    Note: you can have more than one address of the same family
    associated with each interface.
    r�rNcSs|dS)Nrrp)rzrprprtrUsznet_if_addrs.<locals>.<lambda>)�keyrrW�:�-�z%s00)rrr���)�sysrU�socketr|ri�sortr�r�r�Z
AddressFamilyr�r/rWr�r-�countr�rZsnicr�)Z	has_enumsryZrawlistr~r�ZfamZaddr�maskZ	broadcastZptpZ	separatorrprprtri?s,




 cCstj�S)aReturn information about each NIC (network interface card)
    installed on the system as a dictionary whose keys are the
    NIC names and value is a namedtuple with the following fields:

     - isup: whether the interface is up (bool)
     - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
               NIC_DUPLEX_UNKNOWN
     - speed: the NIC speed expressed in mega bits (MB); if it can't
              be determined (e.g. 'localhost') it will be set to 0.
     - mtu: the maximum transmission unit expressed in bytes.
    )r|rjrprprprtrjos�sensors_temperaturesc
s��fdd�}tjt�}tj�}x�|j�D]t\}}xj|r�|jd�\}}}}	||�}||�}||	�}	|rp|	rp|}	n|	r~|r~|	}||jtj	||||	��q2Wq(Wt
|�S)a<Return hardware temperatures. Each entry is a namedtuple
        representing a certain hardware sensor (it may be a CPU, an
        hard disk or something else, depending on the OS and its
        configuration).
        All temperatures are expressed in celsius unless *fahrenheit*
        is set to True.
        cs(|dk	r$�r t|�dddS|SdS)N�	rv� )r)�n)�
fahrenheitrprt�convert�sz%sensors_temperatures.<locals>.convertr)r�r�r�r|r}r�rr�rZshwtempr�)
r�r�r~rpr�rnZlabelriZhighZcriticalrp)r�rtr}�s 


�sensors_fanscCstj�S)z�Return fans speed. Each entry is a namedtuple
        representing a certain hardware sensor.
        All speed are expressed in RPM (rounds per minute).
        )r|r�rprprprtr��s�sensors_batterycCstj�S)a�Return battery information. If no battery is installed
        returns None.

         - percent: battery power left as a percentage.
         - secsleft: a rough approximation of how many seconds are left
                     before the battery runs out of power. May be
                     POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
         - power_plugged: True if the AC power cable is connected.
        )r|r�rprprprtr��s
cCstj�S)zAReturn the system boot time expressed in seconds since the epoch.)r|rorprprprtro�scCstj�S)a�Return users currently connected on the system as a list of
    namedtuples including the following fields.

     - user: the name of the user
     - terminal: the tty or pseudo-tty associated with the user, if any.
     - host: the host name associated with the entry, if any.
     - started: the creation time as a floating point number expressed in
       seconds since the epoch.
    )r|rnrprprprtrn�s
cCstj�S)zjReturn a generator yielding a WindowsService instance for all
        Windows services installed.
        )r|�win_service_iterrprprprtr��sr�cCs
tj|�S)zjGet a Windows service by *name*.
        Raise NoSuchProcess if no service with such name exists.
        )r|�win_service_get)r�rprprtr��sr�c
Cs�tjj�}d}ddddddg}tr6|jd�|jd	�t|d��xrt|dd�D�]`}|jdr�tjj|jd�}|j�|kr�|j	d�}q�|j	d�}nd}t
j	dt
jt|jd���}y|j
�}Wntk
r�d}YnXto�d|k�r�|jd�d}|jd�rt|jdjd��pd}|jd�rBt|jdjd��pDd}|jd�rdt|jdd��pfd}	t||dd�|jd|	|||jjd	d��p�d|||jdj��p�df	�qRWdS)zNList info of all currently running processes emulating ps aux
    output.
    z'%-10s %5s %4s %7s %7s %-13s %5s %7s  %srrr�rbr�r�r�r��USER�PID�%MEM�VSZ�RSS�TTY�START�TIME�COMMANDrw)r�r�z%H:%Mz%b%dz%M:%S�\ri�?N�
)	r�r�r�r�r�r�r�r�r�)r�ZdateZtodayr-r��printr^r�r�r�r�Z	localtimerYr�r1r/�splitrq�vmsrr�get�strip)
Z	today_dayZtemplr��pr�Zcputimerr�rZmemprprprt�test�sP






r�r�__main__)NN)NN)T)F)NF)NF)F)F)FT)FT)r#)F)�r9Z
__future__rr�r<r�r)r�r�r,r>rxr��	tracebackr�r�rwrrrrrrmZ_compatr	r
rr�rr
rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/�_exceptionsr0r1r2r3r4ZPROCFS_PATHr5r|r6r7r8r9ZHAS_PRLIMITrFr:r;r<r=r>r?r@rArBrCrDrEZRLIMIT_MSGQUEUEr�ZRLIMIT_NICEZ
RLIMIT_RTPRIOZ
RLIMIT_RTTIMEZRLIMIT_SIGPENDINGrGZ_psutil_windowsrHrIrJrKrLrMrNrOrPrQrRrSrTr��platform�__all__�extendZ__extra__all__�
__author__rVr�r�rUrWrYrXrr�rrq�replaceZcextr�r�r�r�rxr{r�r�r�r.rZr[r�rAr�r]r\rNr^r_rerbra�	Exception�	print_excrbr[r\rcrerfrdrfrgr�r`rarmrlrk�partial�cache_clearrgrhrirjr}r�r�rornr�r�r�rsrzr�rprprprt�<module>s�





	&
LU
F
]



a
O

;

.
'
0
 



0
__pycache__/__init__.cpython-36.opt-1.pyc000064400000172423150466730540014123 0ustar003

��JZ�K�u@sZ	dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
yddlZWnek
r�dZYnXddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ddlm,Z,ddlm-Z-ddlm.Z.dd lm/Z/dd!lm0Z0dd"lm1Z1dd#lm2Z2dd$lm3Z3dd%lm4Z4dd&lm5Z5dd'lm6Z6dd(lm7Z7dd)lm8Z8dd*lm9Z9dd+lm:Z:dd,lm;Z;dd-lm<Z<dd.lm=Z=dd/lm>Z>dd0lm?Z?dd1l@mAZAdd2l@mBZBdd3l@mCZCdd4l@mDZDdd5l@mEZEe9�rpd6ZFdd7lmGZHdd8lGmIZIdd9lGmJZJdd:lGmKZKdd;lGmLZLeHjM�rVdd<lNmOZOdd=lNmPZPdd>lNmQZQdd?lNmRZRdd@lNmSZSddAlNmTZTddBlNmUZUddClNmVZVddDlNmWZWddElNmXZXddFlNmYZYddGlNmZZZddHlmNZNy
eNj[Z[Wne\k
�r�YnXy
eNj]Z]Wne\k
�rYnXy
eNj^Z^Wne\k
�r(YnXy
eNj_Z_Wne\k
�rJYnXy
eNj`Z`Wne\k
�rlYnXn�e?�r�ddIlmaZHddJlbmcZcddKlbmdZdddLlbmeZeddMlbmfZfddNlbmgZgddOlbmhZhddPlamiZin~e<�r�ddQlmjZHnje7�rddRlmkZHnVe>�r0ddSlmlZHddTllmmZmddUllmnZnd6ZFn&e6�rHddVlmoZHd6ZFnepdWejq��dXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidhdjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}d~dd�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�d�gEZrerjseHjt�d�Zud�Zvewd�d��evjxd��D��ZyeHjzZzej{Z{ej|Z|da}e~ed�ej�Ze�evj�d�d���e~eHj�d�d�k�r�d�e~eHj�d��Z�e�eHj�d���r�e�d�d�j�d�d��e�eHj�j��D��evf7Z�ne�d�ev7Z�e�d�e~eHj�d�d��7Z�e�d�7Z�ee���e�eHd���r�eHj�Z�nd�d��Z�d�d��Z�d�d��Z�Gd�d��d�e��Z�Gd�d��d�e��Z�e�d�d��e�e��D��Z�d�d��Z�d�d��Z�iZ�d�d�d��Z�d�d�d��Z�d�d�d��Z�d�d�d��Z�y
e��a�Wn"e�k
�r�da�e
j��YnXye�d�d��a�Wn"e�k
�r�da�e
j��YnXd�d��Z�d�d„Z�d�d�d��Z�t�a�t�a�d�d�d��Z�d�d��Z�e�eHdƃ�r d�d�dƄZ�erj�dƃd�d��Z�d�d��Z�d�d��Z�d�d�d��Z�d�d�d��Z�ej�ej�d̓e�_�d�e�j�_d�d�d��Z�ej�ej�dЃe�_�d�e�j�_d�d�d��Z�d�d��Z�d�d��Z�e�eHdՃ�r�d�d�dՄZ�erj�dՃe�eHd׃�r�d�dׄZ�erj�d׃e�eHdك�r�d�dلZ�erj�dكd�d��Z�d�d��Z�e?�	r"d�dބZ�d�d�Z�d�d�Z�[[[[ejydd�k�	rF[�[�e�d�k�	rVe��dS)�a0psutil is a cross-platform library for retrieving information on
running processes and system utilization (CPU, memory, disks, network,
sensors) in Python. Supported platforms:

 - Linux
 - Windows
 - OSX
 - FreeBSD
 - OpenBSD
 - NetBSD
 - Sun Solaris
 - AIX

Works with Python versions from 2.6 to 3.X.
�)�divisionN�)�_common)�deprecated_method)�memoize)�memoize_when_activated)�wrap_numbers)�callable)�long)�PY3)�STATUS_DEAD)�STATUS_DISK_SLEEP)�STATUS_IDLE)�
STATUS_LOCKED)�STATUS_RUNNING)�STATUS_SLEEPING)�STATUS_STOPPED)�STATUS_TRACING_STOP)�STATUS_WAITING)�
STATUS_WAKING)�
STATUS_ZOMBIE)�
CONN_CLOSE)�CONN_CLOSE_WAIT)�CONN_CLOSING)�CONN_ESTABLISHED)�CONN_FIN_WAIT1)�CONN_FIN_WAIT2)�
CONN_LAST_ACK)�CONN_LISTEN)�	CONN_NONE)�
CONN_SYN_RECV)�
CONN_SYN_SENT)�CONN_TIME_WAIT)�NIC_DUPLEX_FULL)�NIC_DUPLEX_HALF)�NIC_DUPLEX_UNKNOWN)�AIX)�BSD)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�AccessDenied)�Error)�
NoSuchProcess)�TimeoutExpired)�
ZombieProcessz/proc)�_pslinux)�IOPRIO_CLASS_BE)�IOPRIO_CLASS_IDLE)�IOPRIO_CLASS_NONE)�IOPRIO_CLASS_RT)�
RLIM_INFINITY)�	RLIMIT_AS)�RLIMIT_CORE)�
RLIMIT_CPU)�RLIMIT_DATA)�RLIMIT_FSIZE)�RLIMIT_LOCKS)�RLIMIT_MEMLOCK)�
RLIMIT_NOFILE)�RLIMIT_NPROC)�
RLIMIT_RSS)�RLIMIT_STACK)�
_psutil_linux)�
_pswindows)�ABOVE_NORMAL_PRIORITY_CLASS)�BELOW_NORMAL_PRIORITY_CLASS)�HIGH_PRIORITY_CLASS)�IDLE_PRIORITY_CLASS)�NORMAL_PRIORITY_CLASS)�REALTIME_PRIORITY_CLASS)�CONN_DELETE_TCB)�_psosx)�_psbsd)�_pssunos)�
CONN_BOUND)�	CONN_IDLE)�_psaixzplatform %s is not supportedr1r2r4r0r3�version_info�__version__rrrr
rrrrrrrrr!r rrr"rrrrrr�AF_LINKr#r$r%�POWER_TIME_UNKNOWN�POWER_TIME_UNLIMITEDr'r(r)r*r+r,r-r.r/r&�Process�Popen�
pid_exists�pids�process_iter�
wait_procs�virtual_memory�swap_memory�	cpu_times�cpu_percent�cpu_times_percent�	cpu_count�	cpu_stats�net_io_counters�net_connections�net_if_addrs�net_if_stats�disk_io_counters�disk_partitions�
disk_usage�users�	boot_timezGiampaolo Rodola'z5.4.3cCsg|]}t|��qS�)�int)�.0�numrprp� /usr/lib64/python3.6/__init__.py�
<listcomp>�sru�.Z	monotonic��versionzOversion conflict: %r C extension module was built for another version of psutil�__file__z (%s instead of %s)cCsg|]}|�qSrprp)rr�xrprprtru�sz (different than %s)z;; you may try to 'pip uninstall psutil', manually remove %sz%the existing psutil install directoryz1 or clean the virtual env somehow, then reinstall�ppid_mapc
CsPi}xFt�D]<}ytj|�}|j�}Wnttfk
r>YqX|||<qW|S)z{Return a {pid: ppid, ...} dict for all running processes in
        one shot. Used to speed up Process.children().
        )r]�_psplatformrZ�ppidr2r0)�ret�pid�procr}rprprt�	_ppid_maps
r�cstj���fdd��}|S)zpDecorator which raises NoSuchProcess in case a process is no
    longer running or its PID has been reused.
    cs&|j�st|j|j���|f|�|�S)N)�
is_runningr2r�_name)�self�args�kwargs)�funrprt�wrappersz'_assert_pid_not_reused.<locals>.wrapper)�	functools�wraps)r�r�rp)r�rt�_assert_pid_not_reusedsr�cCs8tj�}t||�}|dkr"d}nd}tjj|�j|�S)z(Format seconds in a human readable form.�<�z%H:%M:%Sz%Y-%m-%d %H:%M:%Sii�Q)�timerq�datetime�
fromtimestamp�strftime)ZsecsZnowZsecs_agoZfmtrprprt�_pprint_secs#sr�c@s�eZdZdZdwdd�Zdxdd�Zdd	�ZeZd
d�Zdd
�Z	dd�Z
edd��Ze
jdd��Zdydd�Zdd�Zdd�Zedd��Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zdzd*d+�Zer�ed,d-��Zd.d/�Zd0d1�Z d2d3�Z!e"e#j$d4��rd5d6�Z%e"e#j$d7��rd{d8d9�Z&e"e#j$d:��r4d|d;d<�Z'e"e#j$d=��rLd}d>d?�Z(e"e#j$d@��rbdAdB�Z)e"e#j$dC��rxdDdE�Z*e+�r�dFdG�Z,dHdI�Z-dJdK�Z.e"e#j$dL��r�dMdN�Z/e0d~dOdP��Z1ddQdR�Z2edSdT��Z3edUdV��Z4e5dWdX�dYdZ��Z6d[d\�Z7d�d^d_�Z8e"e#j$d`��rd�dbdc�Z9ddde�Z:d�dgdh�Z;e�r8didj�Z<e0dkdl��Z=e0dmdn��Z>e0dodp��Z?e0dqdr��Z@e0dsdt��ZAd�dudv�ZBdS)�rZa'Represents an OS process with the given PID.
    If PID is omitted current process PID (os.getpid()) is used.
    Raise NoSuchProcess if PID does not exist.

    Note that most of the methods of this class do not make sure
    the PID of the process being queried has been reused over time.
    That means you might end up retrieving an information referring
    to another process in case the original one this instance
    refers to is gone in the meantime.

    The only exceptions for which process identity is pre-emptively
    checked and guaranteed are:

     - parent()
     - children()
     - nice() (set)
     - ionice() (set)
     - rlimit() (set)
     - cpu_affinity (set)
     - suspend()
     - resume()
     - send_signal()
     - terminate()
     - kill()

    To prevent this problem for all other methods you can:
     - use is_running() before querying the process
     - if you're continuously iterating over a set of Process
       instances use process_iter() which pre-emptively checks
     process identity for every yielded instance
    NcCs|j|�dS)N)�_init)r�rrprprt�__init__TszProcess.__init__FcCs|dkrtj�}n6tr4t|ttf�r4td|��|dkrHtd|��||_d|_	d|_
d|_d|_d|_
d|_d|_tj|�|_d|_d|_y|j�WnXtk
r�YnFtk
r�Yn4tk
r�|s�d|}t|d|��nd|_YnX|j|jf|_dS)Nzpid must be an integer (got %r)rz'pid must be a positive integer (got %s)Fzno process found with pid %sT)�os�getpid�_PY3�
isinstancerqr
�	TypeError�
ValueError�_pidr��_exe�_create_time�_gone�_hash�_oneshot_inctx�_ppidr|rZ�_proc�_last_sys_cpu_times�_last_proc_cpu_times�create_timer0r4r2r�_ident)r�r�_ignore_nsp�msgrprprtr�Ws<
z
Process._initcCs�ytj�}Wntk
r$i}YnX|j|d<y$|j�|d<|jrRt|j�|d<WnHtk
rpd|d<Yn.tk
r�d|d<Ynt	k
r�YnXd|j
j|j
jdj
d	d
�|j�D��fS)Nr�nameZstartedZzombie�statusZ
terminatedz	%s.%s(%s)z, cSsg|]\}}d||f�qS)z%s=%rrp)rr�k�vrprprtru�sz#Process.__str__.<locals>.<listcomp>)�collections�OrderedDict�AttributeErrorrr�r�r�r4r2r0�	__class__�
__module__�__name__�join�items)r��inforprprt�__str__�s&

zProcess.__str__cCst|t�stS|j|jkS)N)r�rZ�NotImplementedr�)r��otherrprprt�__eq__�s
zProcess.__eq__cCs
||kS)Nrp)r�r�rprprt�__ne__�szProcess.__ne__cCs|jdkrt|j�|_|jS)N)r��hashr�)r�rprprt�__hash__�s
zProcess.__hash__cCs|jS)zThe process PID.)r�)r�rprprtr�szProcess.pidccs�|jrdVn�d|_z@|jj�|jj�|jj�trB|jj�|jj�dVWd|jj	�|jj	�|jj	�tr�|jj	�|jj
�d|_XdS)a#Utility context manager which considerably speeds up the
        retrieval of multiple process information at the same time.

        Internally different process info (e.g. name, ppid, uids,
        gids, ...) may be fetched by using the same routine, but
        only one information is returned and the others are discarded.
        When using this context manager the internal routine is
        executed once (in the example below on name()) and the
        other info are cached.

        The cache is cleared when exiting the context manager block.
        The advice is to use this every time you retrieve more than
        one information about the process. If you're lucky, you'll
        get a hell of a speedup.

        >>> import psutil
        >>> p = psutil.Process()
        >>> with p.oneshot():
        ...     p.name()  # collect multiple info
        ...     p.cpu_times()  # return cached value
        ...     p.cpu_percent()  # return cached value
        ...     p.create_time()  # return cached value
        ...
        >>>
        NTF)r�rbZcache_activate�memory_infor}r-�uidsr�Z
oneshot_enterZcache_deactivateZoneshot_exit)r�rprprt�oneshot�s$











zProcess.oneshotc
Cst}|dk	rnt|ttttf�s.tdt|���t|�}||}|rntdt	|�dkrVdnddj
tt|��f��t
�}|pz|}|j��xxp|D]h}y$|dkr�|j}nt||�}	|	�}Wn6ttfk
r�|}Yntk
r�|r�w�YnX|||<q�WWdQRX|S)	a�Utility method returning process information as a
        hashable dictionary.
        If *attrs* is specified it must be a list of strings
        reflecting available Process class' attribute names
        (e.g. ['cpu_times', 'name']) else all public (read
        only) attributes are assumed.
        *ad_value* is the value which gets assigned in case
        AccessDenied or ZombieProcess exception is raised when
        retrieving that particular process information.
        Nzinvalid attrs type %szinvalid attr name%s %sr�srwz, r)�_as_dict_attrnamesr��list�tuple�set�	frozensetr��typer��lenr��map�repr�dictr�r�getattrr0r4�NotImplementedError)
r��attrs�ad_valueZvalid_names�
invalid_namesZretdictZlsr�r~�methrprprt�as_dict�s6



zProcess.as_dictcCsN|j�}|dk	rJ|j�}yt|�}|j�|kr2|SWntk
rHYnXdS)z�Return the parent process as a Process object pre-emptively
        checking whether PID has been reused.
        If no parent is known return None.
        N)r}r�rZr2)r�r}�ctime�parentrprprtr�szProcess.parentcCsJ|jr
dSy|t|j�kStk
r,dStk
rDd|_dSXdS)z�Return whether this process is running.
        It also checks if PID has been reused by another process in
        which case return False.
        FTN)r�rZrr4r2)r�rprprtr�-szProcess.is_runningcCs*tr|jj�S|jp|jj�|_|jSdS)z`The process parent PID.
        On Windows the return value is cached after first call.
        N)r-r�r}r�)r�rprprtr}Es
zProcess.ppidcCs�tr|jdk	r|jS|jj�}trrt|�dkrry|j�}Wntk
rNYn$X|rrtj	j
|d�}|j|�rr|}||_||j_|S)z>The process name. The return value is cached after first call.N�r)r/r�r�r�r-r��cmdliner0r��path�basename�
startswith)r�r�r�Z
extended_namerprprtr�Ws

zProcess.namecs��fdd�}�jdkrzy�jj�}Wn&tk
rJ}z
||d�Sd}~Xn0X|sty||d�}Wntk
rrYnX|�_�jS)z�The process executable as an absolute path.
        May also be an empty string.
        The return value is cached after first call.
        csd�j�}|rRttd�rRttd�rR|d}tjj|�rRtjj|�rRtj|tj�rR|St|t	�r`|�|S)N�access�X_OKr)
r��hasattrr�r��isabs�isfiler�r�r�r0)�fallbackr��exe)r�rprt�guess_itvs
zProcess.exe.<locals>.guess_itN)r�)r�r�r�r0)r�r�r��errrp)r�rtr�qs
zProcess.execCs
|jj�S)z3The command line this process has been called with.)r�r�)r�rprprtr��szProcess.cmdlinecCs$y
|jj�Stk
rtSXdS)z2The process current status as a STATUS_* constant.N)r�r�r4r)r�rprprtr��s
zProcess.statuscCsTtrFtdkrtd��|j�j}ytj|�jStk
rBt|�SXn
|j	j
�SdS)ztThe name of the user that owns the process.
        On UNIX this is calculated by using *real* process uid.
        Nz0requires pwd module shipped with standard python)r-�pwd�ImportErrorr��real�getpwuidZpw_name�KeyError�strr��username)r�Zreal_uidrprprtr��s
zProcess.usernamecCs|jdkr|jj�|_|jS)z�The process creation time as a floating point number
        expressed in seconds since the epoch, in UTC.
        The return value is cached after first call.
        N)r�r�r�)r�rprprtr��s
zProcess.create_timecCs
|jj�S)z6Process current working directory as an absolute path.)r��cwd)r�rprprtr��szProcess.cwdcCs8|dkr|jj�S|j�s(t|j|j��|jj|�dS)z'Get or set process niceness (priority).N)r�Znice_getr�r2rr�Znice_set)r��valuerprprt�nice�s

zProcess.nicecCs
|jj�S)zVReturn process UIDs as a (real, effective, saved)
            namedtuple.
            )r�r�)r�rprprtr��szProcess.uidscCs
|jj�S)zVReturn process GIDs as a (real, effective, saved)
            namedtuple.
            )r��gids)r�rprprtr��szProcess.gidscCs
|jj�S)zVThe terminal associated with this process, if any,
            else None.
            )r��terminal)r�rprprtr��szProcess.terminalcCs
|jj�S)zcReturn the number of file descriptors opened by this
            process (POSIX only).
            )r��num_fds)r�rprprtr��szProcess.num_fds�io_counterscCs
|jj�S)a
Return process I/O statistics as a
            (read_count, write_count, read_bytes, write_bytes)
            namedtuple.
            Those are the number of read/write calls performed and the
            amount of bytes read and written by the process.
            )r�r�)r�rprprtr��szProcess.io_counters�
ionice_getcCs4|dkr"|dk	rtd��|jj�S|jj||�SdS)a�Get or set process I/O niceness (priority).

            On Linux *ioclass* is one of the IOPRIO_CLASS_* constants.
            *value* is a number which goes from 0 to 7. The higher the
            value, the lower the I/O priority of the process.

            On Windows only *ioclass* is used and it can be set to 2
            (normal), 1 (low) or 0 (very low).

            Available on Linux and Windows > Vista only.
            Nz$'ioclass' argument must be specified)r�r�r�Z
ionice_set)r�Zioclassr�rprprt�ionice�s

zProcess.ionice�rlimitcCs&|dkr|jj|�S|jj||�SdS)a"Get or set process resource limits as a (soft, hard)
            tuple.

            *resource* is one of the RLIMIT_* constants.
            *limits* is supposed to be a (soft, hard)  tuple.

            See "man prlimit" for further info.
            Available on Linux only.
            N)r�r�)r�ZresourceZlimitsrprprtr�s
zProcess.rlimit�cpu_affinity_getcCsd|dkrtt|jj���S|sLt|jd�r6|jj�}ntttt	dd����}|jj
tt|���dS)a-Get or set process CPU affinity.
            If specified, *cpus* must be a list of CPUs for which you
            want to set the affinity (e.g. [0, 1]).
            If an empty list is passed, all egible CPUs are assumed
            (and set).
            (Windows, Linux and BSD only).
            N�_get_eligible_cpusT)�percpu)r�r�r�r�r�r�r��ranger�rbZcpu_affinity_set)r�Zcpusrprprt�cpu_affinityszProcess.cpu_affinity�cpu_numcCs
|jj�S)aZReturn what CPU this process is currently running on.
            The returned number should be <= psutil.cpu_count()
            and <= len(psutil.cpu_percent(percpu=True)).
            It may be used in conjunction with
            psutil.cpu_percent(percpu=True) to observe the system
            workload distributed across CPUs.
            )r�r�)r�rprprtr�5szProcess.cpu_num�environcCs
|jj�S)z�The environment variables of the process as a dict.  Note: this
            might not reflect changes made after the process started.  )r�r�)r�rprprtr�BszProcess.environcCs
|jj�S)z\Return the number of handles opened by this process
            (Windows only).
            )r��num_handles)r�rprprtr�IszProcess.num_handlescCs
|jj�S)zkReturn the number of voluntary and involuntary context
        switches performed by this process.
        )r��num_ctx_switches)r�rprprtr�OszProcess.num_ctx_switchescCs
|jj�S)z2Return the number of threads used by this process.)r��num_threads)r�rprprtr�UszProcess.num_threads�threadscCs
|jj�S)z�Return threads opened by process as a list of
            (id, user_time, system_time) namedtuples representing
            thread id and thread CPU times (user/system).
            On OpenBSD this method requires root access.
            )r�r�)r�rprprtr�[szProcess.threadsc
Cs<t�}g}|spx^|j�D]R\}}||jkry&t|�}|j�|j�krN|j|�Wqttfk
rhYqXqWn�tj	t
�}x"|j�D]\}}||j|�q�Wt�}|jg}	x�|	�r6|	j�}||kr�q�|j
|�xb||D]V}
y6t|
�}|j�|j�k}|�r|j|�|	j|
�Wq�ttfk
�r.Yq�Xq�Wq�W|S)u(Return the children of this process as a list of Process
        instances, pre-emptively checking whether PID has been reused.
        If *recursive* is True return all the parent descendants.

        Example (A == this process):

         A ─┐
            │
            ├─ B (child) ─┐
            │             └─ X (grandchild) ─┐
            │                                └─ Y (great grandchild)
            ├─ C (child)
            └─ D (child)

        >>> import psutil
        >>> p = psutil.Process()
        >>> p.children()
        B, C, D
        >>> p.children(recursive=True)
        B, X, Y, C, D

        Note that in the example above if process X disappears
        process Y won't be listed as the reference to process A
        is lost.
        )r�r�rrZr��appendr2r4r��defaultdictr�r��pop�add)r��	recursiver{r~rr}ZchildZreverse_ppid_map�seen�stackZ	child_pidZintimerprprt�childrencs>



zProcess.childrencs|dk	o|dk}|dk	r,|dkr,td|��t�p4d��fdd�}|rr|�}|jj�}tj|�|�}|jj�}n<|j}|j}|�}|jj�}|dks�|dkr�||_||_dS|j|j|j	|j	}||}	||_||_y||	d}
Wnt
k
�rdSX|
�}t|d�SdS)	aReturn a float representing the current process CPU
        utilization as a percentage.

        When *interval* is 0.0 or None (default) compares process times
        to system CPU times elapsed since last call, returning
        immediately (non-blocking). That means that the first time
        this is called it will return a meaningful 0.0 value.

        When *interval* is > 0.0 compares process times to system CPU
        times elapsed before and after the interval (blocking).

        In this case is recommended for accuracy that this function
        be called with at least 0.1 seconds between calls.

        A value > 100.0 can be returned in case of processes running
        multiple threads on different CPU cores.

        The returned value is explicitly NOT split evenly between
        all available logical CPUs. This means that a busy loop process
        running on a system with 2 logical CPUs will be reported as
        having 100% CPU utilization instead of 50%.

        Examples:

          >>> import psutil
          >>> p = psutil.Process(os.getpid())
          >>> # blocking
          >>> p.cpu_percent(interval=1)
          2.0
          >>> # non-blocking (percentage since last call)
          >>> p.cpu_percent(interval=None)
          2.9
          >>>
        Ngrz!interval is not positive (got %r)rcs
t��S)N)�_timerrp)�num_cpusrprt�timer�sz"Process.cpu_percent.<locals>.timer�d)r�rer�rbr��sleepr�r��user�system�ZeroDivisionError�round)r��interval�blockingrZst1Zpt1Zst2Zpt2Z
delta_procZ
delta_timeZoverall_cpus_percentZsingle_cpu_percentrp)rrtrc�s:#



zProcess.cpu_percentcCs
|jj�S)a#Return a (user, system, children_user, children_system)
        namedtuple representing the accumulated process time, in
        seconds.
        This is similar to os.times() but per-process.
        On OSX and Windows children_user and children_system are
        always set to 0.
        )r�rb)r�rprprtrbs	zProcess.cpu_timescCs
|jj�S)aReturn a namedtuple with variable fields depending on the
        platform, representing memory information about the process.

        The "portable" fields available on all plaforms are `rss` and `vms`.

        All numbers are expressed in bytes.
        )r�r�)r�rprprtr�s	zProcess.memory_infor�)ZreplacementcCs|j�S)N)r�)r�rprprt�memory_info_exszProcess.memory_info_excCs
|jj�S)a[This method returns the same information as memory_info(),
        plus, on some platform (Linux, OSX, Windows), also provides
        additional metrics (USS, PSS and swap).
        The additional metrics provide a better representation of actual
        process memory usage.

        Namely USS is the memory which is unique to a process and which
        would be freed if the process was terminated right now.

        It does so by passing through the whole process address.
        As such it usually requires higher user privileges than
        memory_info() and is considerably slower.
        )r��memory_full_info)r�rprprtrszProcess.memory_full_info�rsscCs�ttjj�}||kr(td|t|�f��|tjjkr:|jn|j}|�}t	||�}t
pZt�j}|dksptd|��|t
|�dS)a�Compare process memory to total physical system memory and
        calculate process memory utilization as a percentage.
        *memtype* argument is a string that dictates what type of
        process memory you want to compare against (defaults to "rss").
        The list of available strings can be obtained like this:

        >>> psutil.Process().memory_info()._fields
        ('rss', 'vms', 'shared', 'text', 'lib', 'data', 'dirty', 'uss', 'pss')
        z&invalid memtype %r; valid types are %rrz`can't calculate process memory percent because total physical system memory is not positive (%r)r	)r�r|Zpfullmem�_fieldsr�r�Zpmemr�rr��
_TOTAL_PHYMEMr`�total�float)r�ZmemtypeZvalid_typesr�Zmetricsr�Ztotal_phymemrprprt�memory_percent/s

zProcess.memory_percent�memory_mapsTcs�|jj�}|r�i�xZ|D]R}|d}|dd�}ytdd��||��|<Wqtk
rh|�|<YqXqWtj���fdd��D�Stj��fdd�|D�SdS)	a�Return process' mapped memory regions as a list of namedtuples
            whose fields are variable depending on the platform.

            If *grouped* is True the mapped regions with the same 'path'
            are grouped together and the different memory fields are summed.

            If *grouped* is False every mapped region is shown as a single
            entity and the namedtuple will also include the mapped region's
            address space ('addr') and permission set ('perms').
            ��NcSs||S)Nrp)rz�yrprprt�<lambda>`sz%Process.memory_maps.<locals>.<lambda>csg|]}�|f�|���qSrprp)rrr�)�d�ntrprtrudsz'Process.memory_maps.<locals>.<listcomp>csg|]}�|��qSrprp)rrrz)rrprtrugs)r�rr�r�r|Z
pmmap_groupedZ	pmmap_ext)r�Zgrouped�itZtuplr��numsrp)rrrtrNs

zProcess.memory_mapscCs
|jj�S)z�Return files opened by process as a list of
        (path, fd) namedtuples including the absolute file name
        and file descriptor number.
        )r��
open_files)r�rprprtr"iszProcess.open_files�inetcCs|jj|�S)aTReturn socket connections opened by process as a list of
        (fd, family, type, laddr, raddr, status) namedtuples.
        The *kind* parameter filters for connections that match the
        following criteria:

        +------------+----------------------------------------------------+
        | Kind Value | Connections using                                  |
        +------------+----------------------------------------------------+
        | inet       | IPv4 and IPv6                                      |
        | inet4      | IPv4                                               |
        | inet6      | IPv6                                               |
        | tcp        | TCP                                                |
        | tcp4       | TCP over IPv4                                      |
        | tcp6       | TCP over IPv6                                      |
        | udp        | UDP                                                |
        | udp4       | UDP over IPv4                                      |
        | udp6       | UDP over IPv6                                      |
        | unix       | UNIX socket (both UDP and TCP protocols)           |
        | all        | the sum of all the possible families and protocols |
        +------------+----------------------------------------------------+
        )r��connections)r��kindrprprtr$pszProcess.connectionscCs�|jdkrtd��ytj|j|�Wn�tk
r�}zj|jtjkrxtrdt|j�rdt	|j|j
|j��nd|_t
|j|j
��|jtjtjfkr�t|j|j
���WYdd}~XnXdS)Nrz�preventing sending signal to process with PID 0 as it would affect every process in the process group of the calling process (os.getpid()) instead of PID 0T)rr�r��kill�OSError�errnoZESRCHr+r\r4r�r�r�r2ZEPERMZEACCESr0)r��sigr�rprprt�_send_signal�s
zProcess._send_signalcCs`tr|j|�nL|tjkr&|jj�n6|ttdt��ttdt��fkrT|jj|�nt	d��dS)z�Send a signal *sig* to process pre-emptively checking
        whether PID has been reused (see signal module constants) .
        On Windows only SIGTERM is valid and is treated as an alias
        for kill().
        ZCTRL_C_EVENTZCTRL_BREAK_EVENTzPonly SIGTERM, CTRL_C_EVENT and CTRL_BREAK_EVENT signals are supported on WindowsN)
r-r*�signal�SIGTERMr�r&r��object�send_signalr�)r�r)rprprtr.�s
zProcess.send_signalcCs tr|jtj�n
|jj�dS)z�Suspend process execution with SIGSTOP pre-emptively checking
        whether PID has been reused.
        On Windows this has the effect ot suspending all process threads.
        N)r-r*r+�SIGSTOPr��suspend)r�rprprtr0�szProcess.suspendcCs tr|jtj�n
|jj�dS)z�Resume process execution with SIGCONT pre-emptively checking
        whether PID has been reused.
        On Windows this has the effect of resuming all process threads.
        N)r-r*r+�SIGCONTr��resume)r�rprprtr2�szProcess.resumecCs tr|jtj�n
|jj�dS)z�Terminate the process with SIGTERM pre-emptively checking
        whether PID has been reused.
        On Windows this is an alias for kill().
        N)r-r*r+r,r�r&)r�rprprt�	terminate�szProcess.terminatecCs tr|jtj�n
|jj�dS)zjKill the current process with SIGKILL pre-emptively checking
        whether PID has been reused.
        N)r-r*r+�SIGKILLr�r&)r�rprprtr&�szProcess.killcCs&|dk	r|dkrtd��|jj|�S)a�Wait for process to terminate and, if process is a children
        of os.getpid(), also return its exit code, else None.

        If the process is already terminated immediately return None
        instead of raising NoSuchProcess.

        If *timeout* (in seconds) is specified and process is still
        alive raise TimeoutExpired.

        To wait for multiple Process(es) use psutil.wait_procs().
        Nrz"timeout must be a positive integer)r�r��wait)r��timeoutrprprtr5�szProcess.wait)N)F)NN)N)NN)N)N)F)N)r)T)r#)N)Cr�r��__qualname__�__doc__r�r�r��__repr__r�r�r��propertyr�
contextlib�contextmanagerr�r�r�r�rr}r�r�r�r�r�r�r�r�r-r�r�r�r�r�r|rZr�r�r�r�r�r�r/r�r�r�r�r�rrcrbr�rrrrrr"r$r*r.r0r2r3r&r5rprprprtrZ3s�

/>
,'	
	



E
\



csJeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zd�fd
d�	Z	�Z
S)r[azA more convenient interface to stdlib subprocess.Popen class.
    It starts a sub process and deals with it exactly as when using
    subprocess.Popen class but in addition also provides all the
    properties and methods of psutil.Process class as a unified
    interface:

      >>> import psutil
      >>> from subprocess import PIPE
      >>> p = psutil.Popen(["python", "-c", "print 'hi'"], stdout=PIPE)
      >>> p.name()
      'python'
      >>> p.uids()
      user(real=1000, effective=1000, saved=1000)
      >>> p.username()
      'giampaolo'
      >>> p.communicate()
      ('hi
', None)
      >>> p.terminate()
      >>> p.wait(timeout=2)
      0
      >>>

    For method names common to both classes such as kill(), terminate()
    and wait(), psutil.Process implementation takes precedence.

    Unlike subprocess.Popen this class pre-emptively checks whether PID
    has been reused on send_signal(), terminate() and kill() so that
    you don't accidentally terminate another process, fixing
    http://bugs.python.org/issue6973.

    For a complete documentation refer to:
    http://docs.python.org/library/subprocess.html
    cOs$tj||�|_|j|jjdd�dS)NT)r�)�
subprocessr[�_Popen__subprocr�r)r�r�r�rprprtr�szPopen.__init__cCstttt�ttj���S)N)�sortedr��dirr[r=)r�rprprt�__dir__"sz
Popen.__dir__cCst|jd�r|jj�|S)N�	__enter__)r�r>rB)r�rprprtrB%s
zPopen.__enter__c
Os^t|jd�r|jj||�S|jr*|jj�|jr:|jj�z|jrL|jj�Wd|j�XdS)N�__exit__)r�r>rC�stdout�close�stderr�stdinr5)r�r�r�rprprtrC*s

zPopen.__exit__cCs^ytj||�Stk
rXytj|j|�Stk
rRtd|jj|f��YnXYnXdS)Nz!%s instance has no attribute '%s')r-�__getattribute__r�r>r�r�)r�r�rprprtrH:szPopen.__getattribute__Ncs0|jjdk	r|jjStt|�j|�}||j_|S)N)r>�
returncode�superr[r5)r�r6r~)r�rprtr5Ds
z
Popen.wait)N)r�r�r7r8r�rArBrCrHr5�
__classcell__rprp)r�rtr[�s!
cCs$g|]}|jd�r|dkr|�qS)�_r.r0r2r3r&r5r�r�r�rr�rr�)
r.r0r2r3r&r5r�r�r�rr�rr�)r�)rrrzrprprtruNscCstj�S)z&Return a list of current running PIDs.)r|r]rprprprtr]YscCs0|dkrdS|dkr"tr"|t�kStj|�SdS)z�Return True if given PID exists in the current process list.
    This is faster than doing "pid in psutil.pids()" and
    should be preferred.
    rFN)r-r]r|r\)rrprprtr\^s

c
#s@��fdd�}dd�}tt��}ttj��}||}||}x|D]}||�qBWx�tttj��ttj|�j���D]�\}}	yJ|	dkr�||�Vn2|	j	�r��dk	r�|	j
��d�|	_|	Vn
||�VWqvtk
r�||�Yqvt
k
�r6|	dk�r0|tk�r0yt|VWntk
�r,YnXn�YqvXqvWdS)aReturn a generator yielding a Process instance for all
    running processes.

    Every new Process instance is only created once and then cached
    into an internal table which is updated every time this is used.

    Cached Process instances are checked for identity so that you're
    safe in case a PID has been reused by another process, in which
    case the cached instance is updated.

    The sorting order in which processes are yielded is based on
    their PIDs.

    *attrs* and *ad_value* have the same meaning as in
    Process.as_dict(). If *attrs* is specified as_dict() is called
    and the resulting dict is stored as a 'info' attribute attached
    to returned Process instance.
    If *attrs* is an empty list it will retrieve all process info
    (slow).
    cs.t|�}�dk	r |j��d�|_|t|j<|S)N)r�r�)rZr�r��_pmapr)rr�)r�r�rprtr�s

zprocess_iter.<locals>.addcSstj|d�dS)N)rMr)rrprprt�remove�szprocess_iter.<locals>.removeN)r�r�)r�r]rM�keysr?r�r�r��fromkeysr�r�r�r2r0r�)
r�r�rrN�a�bZnew_pidsZ	gone_pidsrr�rp)r�r�rtr^ss8

c	s��fdd�}|dk	r0|dkr0d|}t|��t��t|�}�dk	r\t��r\tdt��|dk	rnt�|}xt|r�|dk	r�|dkr�PxP|D]H}dt|�}|dk	r�t|t�|�}|dkr�P|||�q�|||�q�W|�}qpW|�r
x|D]}||d�q�W|�}t��t|�fS)a,Convenience function which waits for a list of processes to
    terminate.

    Return a (gone, alive) tuple indicating which processes
    are gone and which ones are still alive.

    The gone ones will have a new *returncode* attribute indicating
    process exit status (may be None).

    *callback* is a function which gets called every time a process
    terminates (a Process instance is passed as callback argument).

    Function will return as soon as all processes terminate or when
    *timeout* occurs.
    Differently from Process.wait() it will not raise TimeoutExpired if
    *timeout* occurs.

    Typical use case is:

     - send SIGTERM to a list of processes
     - give them some time to terminate
     - send SIGKILL to those ones which are still alive

    Example:

    >>> def on_terminate(proc):
    ...     print("process {} terminated".format(proc))
    ...
    >>> for p in procs:
    ...    p.terminate()
    ...
    >>> gone, alive = wait_procs(procs, timeout=3, callback=on_terminate)
    >>> for p in alive:
    ...     p.kill()
    cs\y|j|d�}Wntk
r$Yn4X|dk	s8|j�rX||_�j|��dk	rX�|�dS)N)r6)r5r3r�rIr)r�r6rI)�callback�gonerprt�
check_gone�s
zwait_procs.<locals>.check_goneNrz*timeout must be a positive integer, got %szcallback %r is not a callableg�?)r�r�r	r�rr��minr�)	Zprocsr6rSrUr��aliveZdeadliner�Zmax_timeoutrp)rSrTrtr_�s6$


TcCs.|rtj�}ntj�}|dk	r*|dkr*d}|S)azReturn the number of logical CPUs in the system (same as
    os.cpu_count() in Python 3.4).

    If *logical* is False return the number of physical cores only
    (e.g. hyper thread CPUs are excluded).

    Return None if undetermined.

    The return value is cached after first call.
    If desired cache can be cleared like this:

    >>> psutil.cpu_count.cache_clear()
    Nr)r|Zcpu_count_logicalZcpu_count_physical)Zlogicalr~rprprtres
FcCs|stj�Stj�SdS)a�Return system-wide CPU times as a namedtuple.
    Every CPU time represents the seconds the CPU has spent in the
    given mode. The namedtuple's fields availability varies depending on the
    platform:

     - user
     - system
     - idle
     - nice (UNIX)
     - iowait (Linux)
     - irq (Linux, FreeBSD)
     - softirq (Linux)
     - steal (Linux >= 2.6.11)
     - guest (Linux >= 2.6.24)
     - guest_nice (Linux >= 3.2.0)

    When *percpu* is True return a list of namedtuples for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.
    N)r|rbZ
per_cpu_times)r�rprprtrb-s)r�cCs0t|�}tr,|t|dd�8}|t|dd�8}|S)zWGiven a cpu_time() ntuple calculates the total CPU time
    (including idle time).
    ZguestrZ
guest_nice)�sumr)r�)�timesZtotrprprt�
_cpu_tot_timeXs
	rZcCs&t|�}||j8}|t|dd�8}|S)zlGiven a cpu_time() ntuple calculates the busy CPU time.
    We do so by subtracting all idle CPU times.
    Ziowaitr)rZZidler�)rYZbusyrprprt�_cpu_busy_timeks
r[cCs�|dk	o|dk}|dk	r,|dkr,td|��dd�}|sp|rNt�}tj|�nt}|dkr`t�}t�a||t�Sg}|r�tdd�}tj|�nt}|dkr�tdd�}tdd�ax&t|t�D]\}}|j|||��q�W|SdS)	a�Return a float representing the current system-wide CPU
    utilization as a percentage.

    When *interval* is > 0.0 compares system CPU times elapsed before
    and after the interval (blocking).

    When *interval* is 0.0 or None compares system CPU times elapsed
    since last call or module import, returning immediately (non
    blocking). That means the first time this is called it will
    return a meaningless 0.0 value which you should ignore.
    In this case is recommended for accuracy that this function be
    called with at least 0.1 seconds between calls.

    When *percpu* is True returns a list of floats representing the
    utilization as a percentage for each CPU.
    First element of the list refers to first CPU, second element
    to second CPU and so on.
    The order of the list is consistent across calls.

    Examples:

      >>> # blocking, system-wide
      >>> psutil.cpu_percent(interval=1)
      2.0
      >>>
      >>> # blocking, per-cpu
      >>> psutil.cpu_percent(interval=1, percpu=True)
      [2.0, 1.0]
      >>>
      >>> # non-blocking (percentage since last call)
      >>> psutil.cpu_percent(interval=None)
      2.9
      >>>
    Ngrz!interval is not positive (got %r)c	Sspt|�}t|�}t|�}t|�}||kr,dS||}||}y||d}Wntk
r`dSXt|d�SdS)Ngr	r)rZr[r
r)	�t1�t2Zt1_allZt1_busyZt2_allZt2_busyZ
busy_delta�	all_deltaZ	busy_percrprprt�	calculate�szcpu_percent.<locals>.calculateT)r�)r�rbr�r
�_last_cpu_times�_last_per_cpu_times�zipr�)rr�rr_r\r~�tot1r]rprprtrc{s0%



cCs�|dk	o|dk}|dk	r,|dkr,td|��dd�}|sp|rNt�}tj|�nt}|dkr`t�}t�a||t�Sg}|r�tdd�}tj|�nt}|dkr�tdd�}tdd�ax&t|t�D]\}}|j|||��q�W|SdS)	a�Same as cpu_percent() but provides utilization percentages
    for each specific CPU time as is returned by cpu_times().
    For instance, on Linux we'll get:

      >>> cpu_times_percent()
      cpupercent(user=4.8, nice=0.0, system=4.8, idle=90.5, iowait=0.0,
                 irq=0.0, softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
      >>>

    *interval* and *percpu* arguments have the same meaning as in
    cpu_percent().
    Ngrz!interval is not positive (got %r)cSs�g}t|�t|�}xz|jD]p}t||�t||�}yd||}Wntk
r\d}YnXt|d�}|dkrvd}n|dkr�d}|j|�qWtj|�S)Nr	grgY@)rZrr�r
rr�r|Z	scputimes)r\r]r!r^ZfieldZfield_deltaZ
field_percrprprtr_�s


z$cpu_times_percent.<locals>.calculateT)r�)r�rbr�r
�_last_cpu_times_2�_last_per_cpu_times_2rbr�)rr�rr_r\r~rcr]rprprtrd�s0



cCstj�S)zReturn CPU statistics.)r|rfrprprprtrf/s�cpu_freqc
Cs�tj�}|r|Stt|��}|dkr(dS|dkr8|dSd\}}}x*|D]"}||j7}||j7}||j7}qHW||}||}||}	tj|||	�SdS)a9Return CPU frequency as a nameduple including current,
        min and max frequency expressed in Mhz.

        If *percpu* is True and the system supports per-cpu frequency
        retrieval (Linux only) a list of frequencies is returned for
        each CPU. If not a list with one element is returned.
        rNr�)rgrgrg)	r|rfrr��currentrV�maxrZscpufreq)
r�r~rZcurrsZminsZmaxsZcpurhZmin_Zmax_rprprtrf6s"



cCstj�}|ja|S)a�Return statistics about system memory usage as a namedtuple
    including the following fields, expressed in bytes:

     - total:
       total physical memory available.

     - available:
       the memory that can be given instantly to processes without the
       system going into swap.
       This is calculated by summing different memory values depending
       on the platform and it is supposed to be used to monitor actual
       memory usage in a cross platform fashion.

     - percent:
       the percentage usage calculated as (total - available) / total * 100

     - used:
        memory used, calculated differently depending on the platform and
        designed for informational purposes only:
        OSX: active + inactive + wired
        BSD: active + wired + cached
        LINUX: total - free

     - free:
       memory not being used at all (zeroed) that is readily available;
       note that this doesn't reflect the actual memory available
       (use 'available' instead)

    Platform-specific fields:

     - active (UNIX):
       memory currently in use or very recently used, and so it is in RAM.

     - inactive (UNIX):
       memory that is marked as not used.

     - buffers (BSD, Linux):
       cache for things like file system metadata.

     - cached (BSD, OSX):
       cache for various things.

     - wired (OSX, BSD):
       memory that is marked to always stay in RAM. It is never moved to disk.

     - shared (BSD):
       memory that may be simultaneously accessed by multiple processes.

    The sum of 'used' and 'available' does not necessarily equal total.
    On Windows 'available' and 'free' are the same.
    )r|r`rr)r~rprprtr`Zs5cCstj�S)a�Return system swap memory statistics as a namedtuple including
    the following fields:

     - total:   total swap memory in bytes
     - used:    used swap memory in bytes
     - free:    free swap memory in bytes
     - percent: the percentage usage
     - sin:     no. of bytes the system has swapped in from disk (cumulative)
     - sout:    no. of bytes the system has swapped out from disk (cumulative)

    'sin' and 'sout' on Windows are meaningless and always set to 0.
    )r|rarprprprtra�s
cCs
tj|�S)z�Return disk usage statistics about the given *path* as a
    namedtuple including total, used and free space expressed in bytes
    plus the percentage usage.
    )r|rm)r�rprprtrm�scCs
tj|�S)a3Return mounted partitions as a list of
    (device, mountpoint, fstype, opts) namedtuple.
    'opts' field is a raw string separated by commas indicating mount
    options which may vary depending on the platform.

    If *all* parameter is False return physical devices only and ignore
    all others.
    )r|rl)�allrprprtrl�s	cCs|tj�}|s|riSdS|r&t|d�}ttdtj�}|r^x |j�D]\}}||�||<qBW|S|dd�t|j��D��SdS)a�Return system disk I/O statistics as a namedtuple including
    the following fields:

     - read_count:  number of reads
     - write_count: number of writes
     - read_bytes:  number of bytes read
     - write_bytes: number of bytes written
     - read_time:   time spent reading from disk (in ms)
     - write_time:  time spent writing to disk (in ms)

    Platform specific:

     - busy_time: (Linux, FreeBSD) time spent doing actual I/Os (in ms)
     - read_merged_count (Linux): number of merged reads
     - write_merged_count (Linux): number of merged writes

    If *perdisk* is True return the same information for every
    physical disk installed on the system as a dictionary
    with partition names as the keys and the namedtuple
    described above as the values.

    If *nowrap* is True it detects and adjust the numbers which overflow
    and wrap (restart from 0) and add "old value" to "new value" so that
    the returned numbers will always be increasing or remain the same,
    but never decrease.
    "disk_io_counters.cache_clear()" can be used to invalidate the
    cache.

    On recent Windows versions 'diskperf -y' command may need to be
    executed first otherwise this function won't find any disk.
    Nzpsutil.disk_io_counters�sdiskiocSsg|]}t|��qSrp)rX)rrrzrprprtru�sz$disk_io_counters.<locals>.<listcomp>)	r|rk�
_wrap_numbersr�rrkr�rb�values)Zperdisk�nowrap�rawdictrZdisk�fieldsrprprtrk�s 
zpsutil.disk_io_counterszClears nowrap argument cachecCsrtj�}|s|riSdS|r&t|d�}|rRx"|j�D]\}}tj|�||<q4W|Stjdd�t|j��D��SdS)abReturn network I/O statistics as a namedtuple including
    the following fields:

     - bytes_sent:   number of bytes sent
     - bytes_recv:   number of bytes received
     - packets_sent: number of packets sent
     - packets_recv: number of packets received
     - errin:        total number of errors while receiving
     - errout:       total number of errors while sending
     - dropin:       total number of incoming packets which were dropped
     - dropout:      total number of outgoing packets which were dropped
                     (always 0 on OSX and BSD)

    If *pernic* is True return the same information for every
    network interface installed on the system as a dictionary
    with network interface names as the keys and the namedtuple
    described above as the values.

    If *nowrap* is True it detects and adjust the numbers which overflow
    and wrap (restart from 0) and add "old value" to "new value" so that
    the returned numbers will always be increasing or remain the same,
    but never decrease.
    "disk_io_counters.cache_clear()" can be used to invalidate the
    cache.
    Nzpsutil.net_io_counterscSsg|]}t|��qSrp)rX)rrrzrprprtrusz#net_io_counters.<locals>.<listcomp>)r|rgrlr�rZsnetiorbrm)ZpernicrnroZnicrprprprtrg�s
zpsutil.net_io_countersr#cCs
tj|�S)a�Return system-wide socket connections as a list of
    (fd, family, type, laddr, raddr, status, pid) namedtuples.
    In case of limited privileges 'fd' and 'pid' may be set to -1
    and None respectively.
    The *kind* parameter filters for connections that fit the
    following criteria:

    +------------+----------------------------------------------------+
    | Kind Value | Connections using                                  |
    +------------+----------------------------------------------------+
    | inet       | IPv4 and IPv6                                      |
    | inet4      | IPv4                                               |
    | inet6      | IPv6                                               |
    | tcp        | TCP                                                |
    | tcp4       | TCP over IPv4                                      |
    | tcp6       | TCP over IPv6                                      |
    | udp        | UDP                                                |
    | udp4       | UDP over IPv4                                      |
    | udp6       | UDP over IPv6                                      |
    | unix       | UNIX socket (both UDP and TCP protocols)           |
    | all        | the sum of all the possible families and protocols |
    +------------+----------------------------------------------------+

    On OSX this function requires root privileges.
    )r|rh)r%rprprtrh"scCstjdk}|rddl}tj�}|jdd�d�tjt�}x�|D]�\}}}}}}	|r�y|j	|�}WnBt
k
r�tr�|dkr�tj}nt
td	�r�tj|kr�tj}YnX|tjkr�tr�d
nd}
x|j|
�dkr�|d
|
7}q�W||jtj|||||	��q>Wt|�S)a*Return the addresses associated to each NIC (network interface
    card) installed on the system as a dictionary whose keys are the
    NIC names and value is a list of namedtuples for each address
    assigned to the NIC. Each namedtuple includes 5 fields:

     - family: can be either socket.AF_INET, socket.AF_INET6 or
               psutil.AF_LINK, which refers to a MAC address.
     - address: is the primary address and it is always set.
     - netmask: and 'broadcast' and 'ptp' may be None.
     - ptp: stands for "point to point" and references the
            destination address on a point to point interface
            (typically a VPN).
     - broadcast: and *ptp* are mutually exclusive.

    Note: you can have more than one address of the same family
    associated with each interface.
    r�rNcSs|dS)Nrrp)rzrprprtrUsznet_if_addrs.<locals>.<lambda>)�keyrrW�:�-�z%s00)rrq���)�sysrU�socketr|ri�sortr�r�r�Z
AddressFamilyr�r/rWr�r-�countr�rZsnicr�)Z	has_enumsrxZrawlistr~r�ZfamZaddr�maskZ	broadcastZptpZ	separatorrprprtri?s,




 cCstj�S)aReturn information about each NIC (network interface card)
    installed on the system as a dictionary whose keys are the
    NIC names and value is a namedtuple with the following fields:

     - isup: whether the interface is up (bool)
     - duplex: can be either NIC_DUPLEX_FULL, NIC_DUPLEX_HALF or
               NIC_DUPLEX_UNKNOWN
     - speed: the NIC speed expressed in mega bits (MB); if it can't
              be determined (e.g. 'localhost') it will be set to 0.
     - mtu: the maximum transmission unit expressed in bytes.
    )r|rjrprprprtrjos�sensors_temperaturesc
s��fdd�}tjt�}tj�}x�|j�D]t\}}xj|r�|jd�\}}}}	||�}||�}||	�}	|rp|	rp|}	n|	r~|r~|	}||jtj	||||	��q2Wq(Wt
|�S)a<Return hardware temperatures. Each entry is a namedtuple
        representing a certain hardware sensor (it may be a CPU, an
        hard disk or something else, depending on the OS and its
        configuration).
        All temperatures are expressed in celsius unless *fahrenheit*
        is set to True.
        cs(|dk	r$�r t|�dddS|SdS)N�	ru� )r)�n)�
fahrenheitrprt�convert�sz%sensors_temperatures.<locals>.convertr)r�r�r�r|r|r�rr�rZshwtempr�)
r�r�r~ror�rmZlabelrhZhighZcriticalrp)r�rtr|�s 


�sensors_fanscCstj�S)z�Return fans speed. Each entry is a namedtuple
        representing a certain hardware sensor.
        All speed are expressed in RPM (rounds per minute).
        )r|r�rprprprtr��s�sensors_batterycCstj�S)a�Return battery information. If no battery is installed
        returns None.

         - percent: battery power left as a percentage.
         - secsleft: a rough approximation of how many seconds are left
                     before the battery runs out of power. May be
                     POWER_TIME_UNLIMITED or POWER_TIME_UNLIMITED.
         - power_plugged: True if the AC power cable is connected.
        )r|r�rprprprtr��s
cCstj�S)zAReturn the system boot time expressed in seconds since the epoch.)r|rorprprprtro�scCstj�S)a�Return users currently connected on the system as a list of
    namedtuples including the following fields.

     - user: the name of the user
     - terminal: the tty or pseudo-tty associated with the user, if any.
     - host: the host name associated with the entry, if any.
     - started: the creation time as a floating point number expressed in
       seconds since the epoch.
    )r|rnrprprprtrn�s
cCstj�S)zjReturn a generator yielding a WindowsService instance for all
        Windows services installed.
        )r|�win_service_iterrprprprtr��sr�cCs
tj|�S)zjGet a Windows service by *name*.
        Raise NoSuchProcess if no service with such name exists.
        )r|�win_service_get)r�rprprtr��sr�c
Cs�tjj�}d}ddddddg}tr6|jd�|jd	�t|d��xrt|dd�D�]`}|jdr�tjj|jd�}|j�|kr�|j	d�}q�|j	d�}nd}t
j	dt
jt|jd���}y|j
�}Wntk
r�d}YnXto�d|k�r�|jd�d}|jd�rt|jdjd��pd}|jd�rBt|jdjd��pDd}|jd�rdt|jdd��pfd}	t||dd�|jd|	|||jjd	d��p�d|||jdj��p�df	�qRWdS)zNList info of all currently running processes emulating ps aux
    output.
    z'%-10s %5s %4s %7s %7s %-13s %5s %7s  %srrr�rbr�r�r�r��USER�PID�%MEM�VSZ�RSS�TTY�START�TIME�COMMANDrw)r�r�z%H:%Mz%b%dz%M:%S�\ri�?N�
)	r�r�r�r�r�r�r�r�r�)r�ZdateZtodayr-r��printr^r�r�r�r�Z	localtimerXr�r1r/�splitrq�vmsrr�get�strip)
Z	today_dayZtemplr��pr�Zcputimerr�rZmemprprprt�test�sP






r�r�__main__)NN)NN)T)F)NF)NF)F)F)FT)FT)r#)F)�r8Z
__future__rr�r;r�r(r�r�r+r=rwr��	tracebackr�r�rwrrrrrrlZ_compatr	r
rr�rr
rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/�_exceptionsr0r1r2r3r4ZPROCFS_PATHr5r|r6r7r8r9ZHAS_PRLIMITrFr:r;r<r=r>r?r@rArBrCrDrEZRLIMIT_MSGQUEUEr�ZRLIMIT_NICEZ
RLIMIT_RTPRIOZ
RLIMIT_RTTIMEZRLIMIT_SIGPENDINGrGZ_psutil_windowsrHrIrJrKrLrMrNrOrPrQrRrSrTr��platform�__all__�extendZ__extra__all__�
__author__rVr�r�rUrWrYrXrr�rrq�replaceZcextr�r�r�r�rxr{r�r�r�r-rZr[r�r@r�r]r\rMr^r_rerbr`�	Exception�	print_excrarZr[rcrdrerdrfrfr�r`rarmrlrk�partial�cache_clearrgrhrirjr|r�r�rornr�r�r�rsrzr�rprprprt�<module>s�





	&
LU
F
]



a
O

;

.
'
0
 



0
__pycache__/_psposix.cpython-36.opt-1.pyc000064400000007054150466730540014225 0ustar003

��JZ��@s�dZddlZddlZddlZddlZddlZddlmZddlmZddlm	Z	ddl
mZddl
mZdd	l
mZd
ddd
gZdd
�Zddd�Zdd�Zedd
��ZdS)z%Routines common to all posix systems.�N�)�memoize)�
sdiskusage)�
usage_percent)�PY3)�unicode)�TimeoutExpired�
pid_exists�wait_pid�
disk_usage�get_terminal_mapcCsl|dkrdSytj|d�WnFtk
rb}z*|jtjkr>dS|jtjkrNdS|�WYdd}~XnXdSdS)z6Check whether pid exists in the current process table.rTFN)�os�kill�OSError�errnoZESRCHZEPERM)�pid�err�r� /usr/lib64/python3.6/_psposix.pyr	sc	s�����fdd�}ttdtj���dk	rB�fdd�}����n�fdd�}d}x�y|�\}}Wnftk
r�}zJ|jtjkr�||�}wTn,|jtjkr�xt��r�||�}q�dSq�Wn�WYdd}~XqTX|d	kr�||�}qTtj|�r�tj	|�Stj
|��rtj|�Std
|��qTWdS)aIWait for process with pid 'pid' to terminate and return its
    exit status code as an integer.

    If pid is not a children of os.getpid() (current process) just
    waits until the process disappears and return None.

    If pid does not exist at all return None immediately.

    Raise TimeoutExpired on timeout expired.
    cs8�dk	r ���kr t���d��tj|�t|dd�S)N)r�name�g{�G�z�?)r�timeZsleep�min)�delay)r�	proc_name�stop_at�timeout�timerrr�
check_timeout?s


zwait_pid.<locals>.check_timeoutZ	monotonicNcstj�tj�S)N)r
�waitpid�WNOHANGr)rrr�waitcallHszwait_pid.<locals>.waitcallcstj�d�S)Nr)r
rr)rrrr!Lsg-C��6?rzunknown process exit status %r)
�getattrrrrZEINTRZECHILDr	r
�WIFSIGNALED�WTERMSIG�	WIFEXITED�WEXITSTATUS�
ValueError)	rrrrr!rZretpidZstatusrr)rrrrrrr
4s8



cCs�trtj|�}ndytj|�}WnTtk
rrt|t�rly|jtj��}Wntk
r^YnXtj|�}n�YnX|j	|j
}|j|j
}|j|j
}||}||}t
||dd�}t||||d�S)a.Return disk usage associated with path.
    Note: UNIX usually reserves 5% disk space which is not accessible
    by user. In this function "total" and "used" values reflect the
    total and used disk space whereas "free" and "percent" represent
    the "free" and "used percent" user disk space.
    r)Z_round)�total�usedZfreeZpercent)rr
�statvfs�UnicodeEncodeError�
isinstancer�encode�sys�getfilesystemencoding�f_blocks�f_frsize�f_bfree�f_bavailrr)�path�str(Z
avail_to_rootZ
avail_to_userr)Z
total_userZusage_percent_userrrrrws(
cCspi}tjd�tjd�}xR|D]J}y||tj|�j<Wqtk
rf}z|jtjkrV�WYdd}~XqXqW|S)zMGet a map of device-id -> path as a dict.
    Used by Process.terminal()
    z	/dev/tty*z
/dev/pts/*N)�globr
�stat�st_rdevrr�ENOENT)�retZlsrrrrrr�s
)NN)�__doc__rr6r
r.rZ_commonrrrZ_compatrr�_exceptionsr�__all__r	r
rrrrrr�<module>s 
C1__pycache__/_psosx.cpython-36.pyc000064400000034312150466730540012732 0ustar003

��JZ=C�@s�dZddlZddlZddlZddlZddlmZddlmZddl	m
Z
ddl	mZddl	mZ
dd	l	mZdd
l
mZddl
mZddl
mZdd
l
mZddl
mZddl
mZddl
mZddl
mZddlmZddlmZddlmZgZejd�ZejZe
j e
j!e
j"e
j#e
j$e
j%e
j&e
j'e
j(e
j)e
j*e
j+e
j,e
j-e
j.e
j/e
j0e
j1e
j2e
j3e
j4e
j5e
j6e
j7iZ8e
j9e
j:e
j;e
j<e
j=e
j>e
j?e
j@e
jAe
jBiZCeDdddddddddddd�ZEeDddddddddd �ZFed!d"d#d$d%g�ZGed&d'd(d)d*d+d,d-d.g�ZHed/d0d1d2d3g�ZIed4eIjJda�ZKed6d7�ZLed8d9d:jMeLjJ��ZNd;d<�ZOd=d>�ZPd?d@�ZQdAdB�ZRdCdD�ZSdEdF�ZTdGdH�ZUdIdJ�ZVejWZWe
jXZXdbdLdM�ZYdNdO�ZZe
j[Z[ej\Z\dcdQdR�Z]dSdT�Z^dUdV�Z_dWdX�Z`dYdZ�ZaejbZbd[d\�Zcejdd]d^��ZeGd_d`�d`ef�ZgdS)dzOSX platform implementation.�N)�AF_INET)�
namedtuple�)�_common)�_psposix)�_psutil_osx)�
_psutil_posix)�AF_INET6)�	conn_tmap)�
isfile_strict)�memoize_when_activated)�parse_environ_block)�sockfam_to_enum)�socktype_to_enum)�
usage_percent)�AccessDenied)�
NoSuchProcess)�
ZombieProcess�SC_PAGE_SIZE��������	�
)�ppid�ruid�euid�suid�rgid�egid�sgid�ttynr�ctime�status�name)�cpuutime�cpustime�rss�vms�pfaults�pageins�
numthreads�volctxsw�	scputimes�user�nice�system�idle�svmem�totalZ	available�percent�used�free�active�inactive�wired�pmemr+r,r-r.�pfullmem�uss�
pmmap_groupedz7path rss private swapped dirtied ref_count shadow_depth�	pmmap_extzaddr perms � c	CsNtj�\}}}}}||}|||}t|||dd�}t||||||||�S)z&System virtual memory as a namedtuple.r)�_round)�cextZvirtual_memrr6)r7r;r<r=r:Zavailr9r8�rF�/usr/lib64/python3.6/_psosx.py�virtual_memoryxsrHcCs4tj�\}}}}}t||dd�}tj||||||�S)z=Swap system memory as a (total, used, free, sin, sout) tuple.r)rD)rEZswap_memrrZsswap)r7r9r:ZsinZsoutr8rFrFrG�swap_memory�srIcCstj�\}}}}t||||�S)z(Return system CPU times as a namedtuple.)rE�	cpu_timesr1)r2r3r4r5rFrFrGrJ�srJcCs>g}x4tj�D](}|\}}}}t||||�}|j|�qW|S)z(Return system CPU times as a named tuple)rE�
per_cpu_timesr1�append)�retZcpu_tr2r3r4r5�itemrFrFrGrK�srKcCstj�S)z0Return the number of logical CPUs in the system.)rE�cpu_count_logicalrFrFrFrGrO�srOcCstj�S)z1Return the number of physical CPUs in the system.)rEZcpu_count_physrFrFrFrG�cpu_count_physical�srPcCs"tj�\}}}}}tj||||�S)N)rE�	cpu_statsrZ	scpustats)Zctx_switchesZ
interruptsZsoft_interruptsZsyscallsZtrapsrFrFrGrQ�srQcCstj�\}}}tj|||�gS)z�Return CPU frequency.
    On OSX per-cpu frequency is not supported.
    Also, the returned frequency never changes, see:
    https://arstechnica.com/civis/viewtopic.php?f=19&t=465002
    )rE�cpu_freqrZscpufreq)ZcurrZmin_Zmax_rFrFrGrR�srRFc	Csrg}tj�}x`|D]X}|\}}}}|dkr.d}|sPtjj|�stjj|�rPqtj||||�}|j|�qW|S)z8Return mounted disk partitions as a list of namedtuples.Znone�)	rE�disk_partitions�os�path�isabs�existsrZ	sdiskpartrL)	�all�retlistZ
partitions�	partitionZdeviceZ
mountpointZfstypeZopts�ntuplerFrFrGrT�s
rTcCsbytj�\}}}Wntk
r&dSX|dk}|r<tj}n|dkrLtj}n|d}tj|||�S)z Return battery information.
    Nr�<���)rE�sensors_battery�NotImplementedErrorrZPOWER_TIME_UNLIMITEDZPOWER_TIME_UNKNOWNZsbattery)r8ZminsleftZ
power_pluggedZsecsleftrFrFrGr_�sr_�inetc
Csrg}xht�D]^}yt|�j|�}Wntk
r8wYqX|rx*|D]"}t|�|g}|jtj|��qDWqW|S)z System-wide network connections.)�pids�Process�connectionsr�listrLrZsconn)�kindrM�pidZcons�crFrFrG�net_connections�s
ricCsjt�j�}i}xV|D]N}tj|�}tj|�}tj|�\}}ttd�rNtj|�}tj	||||�||<qW|S)z)Get NIC stats (isup, duplex, speed, mtu).�	NicDuplex)
�net_io_counters�keys�
cext_posixZ
net_if_mtuZnet_if_flagsZnet_if_duplex_speed�hasattrrrjZ	snicstats)�namesrMr(ZmtuZisupZduplexZspeedrFrFrG�net_if_statss





rpcCstj�S)z:The system boot time expressed in seconds since the epoch.)rE�	boot_timerFrFrFrGrqsrqc	Cs`g}tj�}xN|D]F}|\}}}}}|dkr.q|s4qtj||p@d|pFd||�}|j|�qW|S)z:Return currently connected users as a list of namedtuples.�~N)rE�usersrZsuserrL)	rZ�rawlistrNr2ZttyZhostnameZtstamprg�ntrFrFrGrss
rscCs`tj�}d|kr\ytd�j�|jd�Wn0tk
r>Yntk
rZ|jd�YnX|S)Nr)rErbrc�create_timerLrr)ZlsrFrFrGrb0srbcstj���fdd��}|S)z`Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    csty�|f|�|�Stk
rn}zB|jtjkr<t|j|j��|jtjtjfkr\t|j|j���WYdd}~XnXdS)N)	�OSError�errno�ESRCHrrg�_nameZEPERMZEACCESr)�self�args�kwargs�err)�funrFrG�wrapperGsz wrap_exceptions.<locals>.wrapper)�	functools�wraps)rr�rF)rrG�wrap_exceptionsCs
r�ccs�y
dVWn�ttfk
r�}zrt|t�s6|jtjkr�y|j�}Wntk
rZ|�Yq�X|tjkrzt	|j
|j|j��q�t
|j
|j��n�WYdd}~XnXdS)z�There are some poor C APIs which incorrectly raise ESRCH when
    the process is still alive or it's a zombie, or even RuntimeError
    (those who don't set errno). This is here in order to solve:
    https://github.com/giampaolo/psutil/issues/1044
    N)rw�RuntimeError�
isinstancerxryr'rr�
STATUS_ZOMBIErrgrz�_ppidr)�procr~r'rFrFrG�catch_zombieTs


r�c@sneZdZdZdddgZdd�Zedd��Zed	d
��Zdd�Z	d
d�Z
edd��Zedd��Z
edd��Zedd��Zedd��Zedd��Zedd��Zedd��Zedd ��Zed!d"��Zed#d$��Zed%d&��Zed'd(��Zed)d*��Zed+d,��Zed-d.��ZedAd0d1��Zed2d3��ZedBd5d6��Zed7d8��Zed9d:��Z ed;d<��Z!ed=d>��Z"ed?d@��Z#d4S)Crcz1Wrapper class around underlying C implementation.rgrzr�cCs||_d|_d|_dS)N)rgrzr�)r{rgrFrFrG�__init__sszProcess.__init__cCs$tj|j�}t|�tt�ks t�|S)N)rEZproc_kinfo_oneshotrg�len�kinfo_proc_map�AssertionError)r{rMrFrFrG�_get_kinfo_procxszProcess._get_kinfo_procc
Cs8t|��tj|j�}WdQRXt|�tt�ks4t�|S)N)r�rEZproc_pidtaskinfo_oneshotrgr��pidtaskinfo_mapr�)r{rMrFrFrG�_get_pidtaskinfos
zProcess._get_pidtaskinfocCs|jj�|jj�dS)N)r�Zcache_activater�)r{rFrFrG�
oneshot_enter�s
zProcess.oneshot_entercCs|jj�|jj�dS)N)r�Zcache_deactivater�)r{rFrFrG�oneshot_exit�s
zProcess.oneshot_exitcCs(|j�td}|dk	r|Stj|j�S)Nr()r�r�rEZ	proc_namerg)r{r(rFrFrGr(�szProcess.namec	Cs t|��tj|j�SQRXdS)N)r�rEZproc_exerg)r{rFrFrG�exe�s
zProcess.exec	Cs t|��tj|j�SQRXdS)N)r�rEZproc_cmdlinerg)r{rFrFrG�cmdline�s
zProcess.cmdlinec
Cs$t|��ttj|j��SQRXdS)N)r�r
rEZproc_environrg)r{rFrFrG�environ�s
zProcess.environcCs|j�td|_|jS)Nr)r�r�r�)r{rFrFrGr�szProcess.ppidc	Cs t|��tj|j�SQRXdS)N)r�rEZproc_cwdrg)r{rFrFrG�cwd�s
zProcess.cwdcCs.|j�}tj|td|td|td�S)Nrr r!)r�r�puidsr�)r{�rawtuplerFrFrG�uids�s


zProcess.uidscCs.|j�}tj|td|td|td�S)Nr"r#r$)r�rr�r�)r{r�rFrFrG�gids�s


zProcess.gidscCs:|j�td}tj�}y||Stk
r4dSXdS)Nr%)r�r�rZget_terminal_map�KeyError)r{Ztty_nrZtmaprFrFrG�terminal�szProcess.terminalcCs6|j�}t|td|td|td|td�S)Nr+r,r-r.)r�r>r�)r{r�rFrFrG�memory_info�s


zProcess.memory_infocCs"|j�}tj|j�}t||f�S)N)r�rEZproc_memory_ussrgr?)r{Z	basic_memr@rFrFrG�memory_full_info�szProcess.memory_full_infocCs(|j�}tj|td|tddd�S)Nr)r*g)r�rZ	pcputimesr�)r{r�rFrFrGrJ�s


zProcess.cpu_timescCs|j�tdS)Nr&)r�r�)r{rFrFrGrv�szProcess.create_timecCs|j�td}tj|d�S)Nr0r)r�r�rZpctxsw)r{ZvolrFrFrG�num_ctx_switches�szProcess.num_ctx_switchescCs|j�tdS)Nr/)r�r�)r{rFrFrG�num_threads�szProcess.num_threadscCsf|jdkrgSg}t|��tj|j�}WdQRXx.|D]&\}}t|�r8tj||�}|j|�q8W|S)Nr)rgr�rEZproc_open_filesrrZ	popenfilerL)r{�filesrtrV�fdr\rFrFrG�
open_files�s

zProcess.open_filesracCs�|tkr(td|djdd�tD��f��t|\}}t|��tj|j||�}WdQRXg}xz|D]r}|\}}}	}
}}t|}t|�}t	|	�}	|t
tfkr�|
r�tj
|
�}
|r�tj
|�}tj|||	|
||�}
|j|
�qbW|S)Nz+invalid %r kind argument; choose between %sz, cSsg|]}t|��qSrF)�repr)�.0�xrFrFrG�
<listcomp>sz'Process.connections.<locals>.<listcomp>)r
�
ValueError�joinr�rEZproc_connectionsrg�TCP_STATUSESrrrr	rZaddrZpconnrL)r{rfZfamilies�typesrtrMrNr�Zfam�typeZladdrZraddrr'rurFrFrGrd�s(



zProcess.connectionsc	Cs.|jdkrdSt|��tj|j�SQRXdS)Nr)rgr�rEZproc_num_fds)r{rFrFrG�num_fdss

zProcess.num_fdsNcCstj|j||j�S)N)rZwait_pidrgrz)r{ZtimeoutrFrFrG�waitszProcess.waitc	Cs t|��tj|j�SQRXdS)N)r�rm�getpriorityrg)r{rFrFrG�nice_gets
zProcess.nice_getc
Cs"t|��tj|j|�SQRXdS)N)r�rm�setpriorityrg)r{�valuerFrFrG�nice_set#s
zProcess.nice_setcCs|j�td}tj|d�S)Nr'�?)r�r��
PROC_STATUSES�get)r{�coderFrFrGr'(szProcess.statuscCsTt|��tj|j�}WdQRXg}x*|D]"\}}}tj|||�}|j|�q*W|S)N)r�rEZproc_threadsrgrZpthreadrL)r{rtrZZ	thread_id�utimeZstimer\rFrFrG�threads.s
zProcess.threadsc	Cs t|��tj|j�SQRXdS)N)r�rEZproc_memory_mapsrg)r{rFrFrG�memory_maps8s
zProcess.memory_maps)ra)N)$�__name__�
__module__�__qualname__�__doc__�	__slots__r�rr�r�r�r�r�r(r�r�r�rr�r�r�r�r�r�rJrvr�r�r�rdr�r�r�r�r'r�r�rFrFrFrGrcnsB
	
	

rc)r@)F)ra)hr��
contextlibrxr�rUZsocketr�collectionsrrSrrrrErrmr	r
rrr
rrr�_exceptionsrrrZ__extra__all__�sysconfZPAGESIZEZAF_LINKZTCPS_ESTABLISHEDZCONN_ESTABLISHEDZ
TCPS_SYN_SENTZ
CONN_SYN_SENTZTCPS_SYN_RECEIVEDZ
CONN_SYN_RECVZTCPS_FIN_WAIT_1ZCONN_FIN_WAIT1ZTCPS_FIN_WAIT_2ZCONN_FIN_WAIT2ZTCPS_TIME_WAITZCONN_TIME_WAITZTCPS_CLOSEDZ
CONN_CLOSEZTCPS_CLOSE_WAITZCONN_CLOSE_WAITZ
TCPS_LAST_ACKZ
CONN_LAST_ACKZTCPS_LISTENZCONN_LISTENZTCPS_CLOSINGZCONN_CLOSINGZPSUTIL_CONN_NONEZ	CONN_NONEr�ZSIDLZSTATUS_IDLEZSRUNZSTATUS_RUNNINGZSSLEEPZSTATUS_SLEEPINGZSSTOPZSTATUS_STOPPEDZSZOMBr�r��dictr�r�r1r6r>�_fieldsr?rAr�rBrHrIrJrKrOrPrQrRZ
disk_usageZdisk_io_countersrTr_rkZnet_if_addrsrirprqrsrbZ
pid_existsr��contextmanagerr��objectrcrFrFrFrG�<module>s�





_psaix.py000064400000045660150466730540006426 0ustar00# Copyright (c) 2009, Giampaolo Rodola'
# Copyright (c) 2017, Arnon Yaari
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""AIX platform implementation."""

import errno
import glob
import os
import re
import subprocess
import sys
from collections import namedtuple
from socket import AF_INET

from . import _common
from . import _psposix
from . import _psutil_aix as cext
from . import _psutil_posix as cext_posix
from ._common import AF_INET6
from ._common import memoize_when_activated
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import sockfam_to_enum
from ._common import socktype_to_enum
from ._common import usage_percent
from ._compat import PY3
from ._exceptions import AccessDenied
from ._exceptions import NoSuchProcess
from ._exceptions import ZombieProcess


__extra__all__ = ["PROCFS_PATH"]


# =====================================================================
# --- globals
# =====================================================================


HAS_THREADS = hasattr(cext, "proc_threads")

PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
AF_LINK = cext_posix.AF_LINK

PROC_STATUSES = {
    cext.SIDL: _common.STATUS_IDLE,
    cext.SZOMB: _common.STATUS_ZOMBIE,
    cext.SACTIVE: _common.STATUS_RUNNING,
    cext.SSWAP: _common.STATUS_RUNNING,      # TODO what status is this?
    cext.SSTOP: _common.STATUS_STOPPED,
}

TCP_STATUSES = {
    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
    cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
    cext.TCPS_CLOSED: _common.CONN_CLOSE,
    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
    cext.TCPS_LISTEN: _common.CONN_LISTEN,
    cext.TCPS_CLOSING: _common.CONN_CLOSING,
    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}

proc_info_map = dict(
    ppid=0,
    rss=1,
    vms=2,
    create_time=3,
    nice=4,
    num_threads=5,
    status=6,
    ttynr=7)


# =====================================================================
# --- named tuples
# =====================================================================


# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms'])
# psutil.Process.memory_full_info()
pfullmem = pmem
# psutil.Process.cpu_times()
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
# psutil.virtual_memory()
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss', 'anon', 'locked'])
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
    'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))


# =====================================================================
# --- utils
# =====================================================================


def get_procfs_path():
    """Return updated psutil.PROCFS_PATH constant."""
    return sys.modules['psutil'].PROCFS_PATH


# =====================================================================
# --- memory
# =====================================================================


def virtual_memory():
    total, avail, free, pinned, inuse = cext.virtual_mem()
    percent = usage_percent((total - avail), total, _round=1)
    return svmem(total, avail, percent, inuse, free)


def swap_memory():
    """Swap system memory as a (total, used, free, sin, sout) tuple."""
    total, free, sin, sout = cext.swap_mem()
    used = total - free
    percent = usage_percent(used, total, _round=1)
    return _common.sswap(total, used, free, percent, sin, sout)


# =====================================================================
# --- CPU
# =====================================================================


def cpu_times():
    """Return system-wide CPU times as a named tuple"""
    ret = cext.per_cpu_times()
    return scputimes(*[sum(x) for x in zip(*ret)])


def per_cpu_times():
    """Return system per-CPU times as a list of named tuples"""
    ret = cext.per_cpu_times()
    return [scputimes(*x) for x in ret]


def cpu_count_logical():
    """Return the number of logical CPUs in the system."""
    try:
        return os.sysconf("SC_NPROCESSORS_ONLN")
    except ValueError:
        # mimic os.cpu_count() behavior
        return None


def cpu_count_physical():
    cmd = "lsdev -Cc processor"
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if PY3:
        stdout, stderr = [x.decode(sys.stdout.encoding)
                          for x in (stdout, stderr)]
    if p.returncode != 0:
        raise RuntimeError("%r command error\n%s" % (cmd, stderr))
    processors = stdout.strip().splitlines()
    return len(processors) or None


def cpu_stats():
    """Return various CPU stats as a named tuple."""
    ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats()
    return _common.scpustats(
        ctx_switches, interrupts, soft_interrupts, syscalls)


# =====================================================================
# --- disks
# =====================================================================


disk_io_counters = cext.disk_io_counters
disk_usage = _psposix.disk_usage


def disk_partitions(all=False):
    """Return system disk partitions."""
    # TODO - the filtering logic should be better checked so that
    # it tries to reflect 'df' as much as possible
    retlist = []
    partitions = cext.disk_partitions()
    for partition in partitions:
        device, mountpoint, fstype, opts = partition
        if device == 'none':
            device = ''
        if not all:
            # Differently from, say, Linux, we don't have a list of
            # common fs types so the best we can do, AFAIK, is to
            # filter by filesystem having a total size > 0.
            if not disk_usage(mountpoint).total:
                continue
        ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
        retlist.append(ntuple)
    return retlist


# =====================================================================
# --- network
# =====================================================================


net_if_addrs = cext_posix.net_if_addrs
net_io_counters = cext.net_io_counters


def net_connections(kind, _pid=-1):
    """Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    """
    cmap = _common.conn_tmap
    if kind not in cmap:
        raise ValueError("invalid %r kind argument; choose between %s"
                         % (kind, ', '.join([repr(x) for x in cmap])))
    families, types = _common.conn_tmap[kind]
    rawlist = cext.net_connections(_pid)
    ret = set()
    for item in rawlist:
        fd, fam, type_, laddr, raddr, status, pid = item
        if fam not in families:
            continue
        if type_ not in types:
            continue
        status = TCP_STATUSES[status]
        if fam in (AF_INET, AF_INET6):
            if laddr:
                laddr = _common.addr(*laddr)
            if raddr:
                raddr = _common.addr(*raddr)
        fam = sockfam_to_enum(fam)
        type_ = socktype_to_enum(type_)
        if _pid == -1:
            nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid)
        else:
            nt = _common.pconn(fd, fam, type_, laddr, raddr, status)
        ret.add(nt)
    return list(ret)


def net_if_stats():
    """Get NIC stats (isup, duplex, speed, mtu)."""
    duplex_map = {"Full": NIC_DUPLEX_FULL,
                  "Half": NIC_DUPLEX_HALF}
    names = set([x[0] for x in net_if_addrs()])
    ret = {}
    for name in names:
        isup, mtu = cext.net_if_stats(name)

        # try to get speed and duplex
        # TODO: rewrite this in C (entstat forks, so use truss -f to follow.
        # looks like it is using an undocumented ioctl?)
        duplex = ""
        speed = 0
        p = subprocess.Popen(["/usr/bin/entstat", "-d", name],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if PY3:
            stdout, stderr = [x.decode(sys.stdout.encoding)
                              for x in (stdout, stderr)]
        if p.returncode == 0:
            re_result = re.search("Running: (\d+) Mbps.*?(\w+) Duplex", stdout)
            if re_result is not None:
                speed = int(re_result.group(1))
                duplex = re_result.group(2)

        duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN)
        ret[name] = _common.snicstats(isup, duplex, speed, mtu)
    return ret


# =====================================================================
# --- other system functions
# =====================================================================


def boot_time():
    """The system boot time expressed in seconds since the epoch."""
    return cext.boot_time()


def users():
    """Return currently connected users as a list of namedtuples."""
    retlist = []
    rawlist = cext.users()
    localhost = (':0.0', ':0')
    for item in rawlist:
        user, tty, hostname, tstamp, user_process, pid = item
        # note: the underlying C function includes entries about
        # system boot, run level and others.  We might want
        # to use them in the future.
        if not user_process:
            continue
        if hostname in localhost:
            hostname = 'localhost'
        nt = _common.suser(user, tty, hostname, tstamp, pid)
        retlist.append(nt)
    return retlist


# =====================================================================
# --- processes
# =====================================================================


def pids():
    """Returns a list of PIDs currently running on the system."""
    return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]


def pid_exists(pid):
    """Check for the existence of a unix pid."""
    return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo"))


def wrap_exceptions(fun):
    """Call callable into a try/except clause and translate ENOENT,
    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
    """

    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except EnvironmentError as err:
            # support for private module import
            if (NoSuchProcess is None or AccessDenied is None or
                    ZombieProcess is None):
                raise
            # ENOENT (no such file or directory) gets raised on open().
            # ESRCH (no such process) can get raised on read() if
            # process is gone in meantime.
            if err.errno in (errno.ENOENT, errno.ESRCH):
                if not pid_exists(self.pid):
                    raise NoSuchProcess(self.pid, self._name)
                else:
                    raise ZombieProcess(self.pid, self._name, self._ppid)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
    return wrapper


class Process(object):
    """Wrapper class around underlying C implementation."""

    __slots__ = ["pid", "_name", "_ppid", "_procfs_path"]

    def __init__(self, pid):
        self.pid = pid
        self._name = None
        self._ppid = None
        self._procfs_path = get_procfs_path()

    def oneshot_enter(self):
        self._proc_name_and_args.cache_activate()
        self._proc_basic_info.cache_activate()
        self._proc_cred.cache_activate()

    def oneshot_exit(self):
        self._proc_name_and_args.cache_deactivate()
        self._proc_basic_info.cache_deactivate()
        self._proc_cred.cache_deactivate()

    @memoize_when_activated
    def _proc_name_and_args(self):
        return cext.proc_name_and_args(self.pid, self._procfs_path)

    @memoize_when_activated
    def _proc_basic_info(self):
        return cext.proc_basic_info(self.pid, self._procfs_path)

    @memoize_when_activated
    def _proc_cred(self):
        return cext.proc_cred(self.pid, self._procfs_path)

    @wrap_exceptions
    def name(self):
        if self.pid == 0:
            return "swapper"
        # note: this is limited to 15 characters
        return self._proc_name_and_args()[0].rstrip("\x00")

    @wrap_exceptions
    def exe(self):
        # there is no way to get executable path in AIX other than to guess,
        # and guessing is more complex than what's in the wrapping class
        exe = self.cmdline()[0]
        if os.path.sep in exe:
            # relative or absolute path
            if not os.path.isabs(exe):
                # if cwd has changed, we're out of luck - this may be wrong!
                exe = os.path.abspath(os.path.join(self.cwd(), exe))
            if (os.path.isabs(exe) and
               os.path.isfile(exe) and
               os.access(exe, os.X_OK)):
                return exe
            # not found, move to search in PATH using basename only
            exe = os.path.basename(exe)
        # search for exe name PATH
        for path in os.environ["PATH"].split(":"):
            possible_exe = os.path.abspath(os.path.join(path, exe))
            if (os.path.isfile(possible_exe) and
               os.access(possible_exe, os.X_OK)):
                return possible_exe
        return ''

    @wrap_exceptions
    def cmdline(self):
        return self._proc_name_and_args()[1].split(' ')

    @wrap_exceptions
    def create_time(self):
        return self._proc_basic_info()[proc_info_map['create_time']]

    @wrap_exceptions
    def num_threads(self):
        return self._proc_basic_info()[proc_info_map['num_threads']]

    if HAS_THREADS:
        @wrap_exceptions
        def threads(self):
            rawlist = cext.proc_threads(self.pid)
            retlist = []
            for thread_id, utime, stime in rawlist:
                ntuple = _common.pthread(thread_id, utime, stime)
                retlist.append(ntuple)
            # The underlying C implementation retrieves all OS threads
            # and filters them by PID.  At this point we can't tell whether
            # an empty list means there were no connections for process or
            # process is no longer active so we force NSP in case the PID
            # is no longer there.
            if not retlist:
                # will raise NSP if process is gone
                os.stat('%s/%s' % (self._procfs_path, self.pid))
            return retlist

    @wrap_exceptions
    def connections(self, kind='inet'):
        ret = net_connections(kind, _pid=self.pid)
        # The underlying C implementation retrieves all OS connections
        # and filters them by PID.  At this point we can't tell whether
        # an empty list means there were no connections for process or
        # process is no longer active so we force NSP in case the PID
        # is no longer there.
        if not ret:
            # will raise NSP if process is gone
            os.stat('%s/%s' % (self._procfs_path, self.pid))
        return ret

    @wrap_exceptions
    def nice_get(self):
        return cext_posix.getpriority(self.pid)

    @wrap_exceptions
    def nice_set(self, value):
        return cext_posix.setpriority(self.pid, value)

    @wrap_exceptions
    def ppid(self):
        self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
        return self._ppid

    @wrap_exceptions
    def uids(self):
        real, effective, saved, _, _, _ = self._proc_cred()
        return _common.puids(real, effective, saved)

    @wrap_exceptions
    def gids(self):
        _, _, _, real, effective, saved = self._proc_cred()
        return _common.puids(real, effective, saved)

    @wrap_exceptions
    def cpu_times(self):
        cpu_times = cext.proc_cpu_times(self.pid, self._procfs_path)
        return _common.pcputimes(*cpu_times)

    @wrap_exceptions
    def terminal(self):
        ttydev = self._proc_basic_info()[proc_info_map['ttynr']]
        # convert from 64-bit dev_t to 32-bit dev_t and then map the device
        ttydev = (((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF))
        # try to match rdev of /dev/pts/* files ttydev
        for dev in glob.glob("/dev/**/*"):
            if os.stat(dev).st_rdev == ttydev:
                return dev
        return None

    @wrap_exceptions
    def cwd(self):
        procfs_path = self._procfs_path
        try:
            result = os.readlink("%s/%s/cwd" % (procfs_path, self.pid))
            return result.rstrip('/')
        except OSError as err:
            if err.errno == errno.ENOENT:
                os.stat("%s/%s" % (procfs_path, self.pid))  # raise NSP or AD
                return None
            raise

    @wrap_exceptions
    def memory_info(self):
        ret = self._proc_basic_info()
        rss = ret[proc_info_map['rss']] * 1024
        vms = ret[proc_info_map['vms']] * 1024
        return pmem(rss, vms)

    memory_full_info = memory_info

    @wrap_exceptions
    def status(self):
        code = self._proc_basic_info()[proc_info_map['status']]
        # XXX is '?' legit? (we're not supposed to return it anyway)
        return PROC_STATUSES.get(code, '?')

    def open_files(self):
        # TODO rewrite without using procfiles (stat /proc/pid/fd/* and then
        # find matching name of the inode)
        p = subprocess.Popen(["/usr/bin/procfiles", "-n", str(self.pid)],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if PY3:
            stdout, stderr = [x.decode(sys.stdout.encoding)
                              for x in (stdout, stderr)]
        if "no such process" in stderr.lower():
            raise NoSuchProcess(self.pid, self._name)
        procfiles = re.findall("(\d+): S_IFREG.*\s*.*name:(.*)\n", stdout)
        retlist = []
        for fd, path in procfiles:
            path = path.strip()
            if path.startswith("//"):
                path = path[1:]
            if path.lower() == "cannot be retrieved":
                continue
            retlist.append(_common.popenfile(path, int(fd)))
        return retlist

    @wrap_exceptions
    def num_fds(self):
        if self.pid == 0:       # no /proc/0/fd
            return 0
        return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))

    @wrap_exceptions
    def num_ctx_switches(self):
        return _common.pctxsw(
            *cext.proc_num_ctx_switches(self.pid))

    @wrap_exceptions
    def wait(self, timeout=None):
        return _psposix.wait_pid(self.pid, timeout, self._name)

    @wrap_exceptions
    def io_counters(self):
        try:
            rc, wc, rb, wb = cext.proc_io_counters(self.pid)
        except OSError:
            # if process is terminated, proc_io_counters returns OSError
            # instead of NSP
            if not pid_exists(self.pid):
                raise NoSuchProcess(self.pid, self._name)
            raise
        return _common.pio(rc, wc, rb, wb)
_pssunos.py000064400000062062150466730540007007 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Sun OS Solaris platform implementation."""

import errno
import os
import socket
import subprocess
import sys
from collections import namedtuple
from socket import AF_INET

from . import _common
from . import _psposix
from . import _psutil_posix as cext_posix
from . import _psutil_sunos as cext
from ._common import AF_INET6
from ._common import isfile_strict
from ._common import memoize_when_activated
from ._common import sockfam_to_enum
from ._common import socktype_to_enum
from ._common import usage_percent
from ._compat import b
from ._compat import PY3
from ._exceptions import AccessDenied
from ._exceptions import NoSuchProcess
from ._exceptions import ZombieProcess


__extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"]


# =====================================================================
# --- globals
# =====================================================================


PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
AF_LINK = cext_posix.AF_LINK
IS_64_BIT = sys.maxsize > 2**32

CONN_IDLE = "IDLE"
CONN_BOUND = "BOUND"

PROC_STATUSES = {
    cext.SSLEEP: _common.STATUS_SLEEPING,
    cext.SRUN: _common.STATUS_RUNNING,
    cext.SZOMB: _common.STATUS_ZOMBIE,
    cext.SSTOP: _common.STATUS_STOPPED,
    cext.SIDL: _common.STATUS_IDLE,
    cext.SONPROC: _common.STATUS_RUNNING,  # same as run
    cext.SWAIT: _common.STATUS_WAITING,
}

TCP_STATUSES = {
    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
    cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
    cext.TCPS_CLOSED: _common.CONN_CLOSE,
    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
    cext.TCPS_LISTEN: _common.CONN_LISTEN,
    cext.TCPS_CLOSING: _common.CONN_CLOSING,
    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
    cext.TCPS_IDLE: CONN_IDLE,  # sunos specific
    cext.TCPS_BOUND: CONN_BOUND,  # sunos specific
}

proc_info_map = dict(
    ppid=0,
    rss=1,
    vms=2,
    create_time=3,
    nice=4,
    num_threads=5,
    status=6,
    ttynr=7)


# =====================================================================
# --- named tuples
# =====================================================================


# psutil.cpu_times()
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
# psutil.cpu_times(percpu=True)
pcputimes = namedtuple('pcputimes',
                       ['user', 'system', 'children_user', 'children_system'])
# psutil.virtual_memory()
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms'])
pfullmem = pmem
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple('pmmap_grouped',
                           ['path', 'rss', 'anonymous', 'locked'])
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
    'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))


# =====================================================================
# --- utils
# =====================================================================


def get_procfs_path():
    """Return updated psutil.PROCFS_PATH constant."""
    return sys.modules['psutil'].PROCFS_PATH


# =====================================================================
# --- memory
# =====================================================================


def virtual_memory():
    """Report virtual memory metrics."""
    # we could have done this with kstat, but IMHO this is good enough
    total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
    # note: there's no difference on Solaris
    free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE
    used = total - free
    percent = usage_percent(used, total, _round=1)
    return svmem(total, avail, percent, used, free)


def swap_memory():
    """Report swap memory metrics."""
    sin, sout = cext.swap_mem()
    # XXX
    # we are supposed to get total/free by doing so:
    # http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/
    #     usr/src/cmd/swap/swap.c
    # ...nevertheless I can't manage to obtain the same numbers as 'swap'
    # cmdline utility, so let's parse its output (sigh!)
    p = subprocess.Popen(['/usr/bin/env', 'PATH=/usr/sbin:/sbin:%s' %
                          os.environ['PATH'], 'swap', '-l'],
                         stdout=subprocess.PIPE)
    stdout, stderr = p.communicate()
    if PY3:
        stdout = stdout.decode(sys.stdout.encoding)
    if p.returncode != 0:
        raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode)

    lines = stdout.strip().split('\n')[1:]
    if not lines:
        raise RuntimeError('no swap device(s) configured')
    total = free = 0
    for line in lines:
        line = line.split()
        t, f = line[-2:]
        total += int(int(t) * 512)
        free += int(int(f) * 512)
    used = total - free
    percent = usage_percent(used, total, _round=1)
    return _common.sswap(total, used, free, percent,
                         sin * PAGE_SIZE, sout * PAGE_SIZE)


# =====================================================================
# --- CPU
# =====================================================================


def cpu_times():
    """Return system-wide CPU times as a named tuple"""
    ret = cext.per_cpu_times()
    return scputimes(*[sum(x) for x in zip(*ret)])


def per_cpu_times():
    """Return system per-CPU times as a list of named tuples"""
    ret = cext.per_cpu_times()
    return [scputimes(*x) for x in ret]


def cpu_count_logical():
    """Return the number of logical CPUs in the system."""
    try:
        return os.sysconf("SC_NPROCESSORS_ONLN")
    except ValueError:
        # mimic os.cpu_count() behavior
        return None


def cpu_count_physical():
    """Return the number of physical CPUs in the system."""
    return cext.cpu_count_phys()


def cpu_stats():
    """Return various CPU stats as a named tuple."""
    ctx_switches, interrupts, syscalls, traps = cext.cpu_stats()
    soft_interrupts = 0
    return _common.scpustats(ctx_switches, interrupts, soft_interrupts,
                             syscalls)


# =====================================================================
# --- disks
# =====================================================================


disk_io_counters = cext.disk_io_counters
disk_usage = _psposix.disk_usage


def disk_partitions(all=False):
    """Return system disk partitions."""
    # TODO - the filtering logic should be better checked so that
    # it tries to reflect 'df' as much as possible
    retlist = []
    partitions = cext.disk_partitions()
    for partition in partitions:
        device, mountpoint, fstype, opts = partition
        if device == 'none':
            device = ''
        if not all:
            # Differently from, say, Linux, we don't have a list of
            # common fs types so the best we can do, AFAIK, is to
            # filter by filesystem having a total size > 0.
            if not disk_usage(mountpoint).total:
                continue
        ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
        retlist.append(ntuple)
    return retlist


# =====================================================================
# --- network
# =====================================================================


net_io_counters = cext.net_io_counters
net_if_addrs = cext_posix.net_if_addrs


def net_connections(kind, _pid=-1):
    """Return socket connections.  If pid == -1 return system-wide
    connections (as opposed to connections opened by one process only).
    Only INET sockets are returned (UNIX are not).
    """
    cmap = _common.conn_tmap.copy()
    if _pid == -1:
        cmap.pop('unix', 0)
    if kind not in cmap:
        raise ValueError("invalid %r kind argument; choose between %s"
                         % (kind, ', '.join([repr(x) for x in cmap])))
    families, types = _common.conn_tmap[kind]
    rawlist = cext.net_connections(_pid)
    ret = set()
    for item in rawlist:
        fd, fam, type_, laddr, raddr, status, pid = item
        if fam not in families:
            continue
        if type_ not in types:
            continue
        if fam in (AF_INET, AF_INET6):
            if laddr:
                laddr = _common.addr(*laddr)
            if raddr:
                raddr = _common.addr(*raddr)
        status = TCP_STATUSES[status]
        fam = sockfam_to_enum(fam)
        type_ = socktype_to_enum(type_)
        if _pid == -1:
            nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid)
        else:
            nt = _common.pconn(fd, fam, type_, laddr, raddr, status)
        ret.add(nt)
    return list(ret)


def net_if_stats():
    """Get NIC stats (isup, duplex, speed, mtu)."""
    ret = cext.net_if_stats()
    for name, items in ret.items():
        isup, duplex, speed, mtu = items
        if hasattr(_common, 'NicDuplex'):
            duplex = _common.NicDuplex(duplex)
        ret[name] = _common.snicstats(isup, duplex, speed, mtu)
    return ret


# =====================================================================
# --- other system functions
# =====================================================================


def boot_time():
    """The system boot time expressed in seconds since the epoch."""
    return cext.boot_time()


def users():
    """Return currently connected users as a list of namedtuples."""
    retlist = []
    rawlist = cext.users()
    localhost = (':0.0', ':0')
    for item in rawlist:
        user, tty, hostname, tstamp, user_process, pid = item
        # note: the underlying C function includes entries about
        # system boot, run level and others.  We might want
        # to use them in the future.
        if not user_process:
            continue
        if hostname in localhost:
            hostname = 'localhost'
        nt = _common.suser(user, tty, hostname, tstamp, pid)
        retlist.append(nt)
    return retlist


# =====================================================================
# --- processes
# =====================================================================


def pids():
    """Returns a list of PIDs currently running on the system."""
    return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]


def pid_exists(pid):
    """Check for the existence of a unix pid."""
    return _psposix.pid_exists(pid)


def wrap_exceptions(fun):
    """Call callable into a try/except clause and translate ENOENT,
    EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
    """

    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except EnvironmentError as err:
            if self.pid == 0:
                if 0 in pids():
                    raise AccessDenied(self.pid, self._name)
                else:
                    raise
            # ENOENT (no such file or directory) gets raised on open().
            # ESRCH (no such process) can get raised on read() if
            # process is gone in meantime.
            if err.errno in (errno.ENOENT, errno.ESRCH):
                if not pid_exists(self.pid):
                    raise NoSuchProcess(self.pid, self._name)
                else:
                    raise ZombieProcess(self.pid, self._name, self._ppid)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
    return wrapper


class Process(object):
    """Wrapper class around underlying C implementation."""

    __slots__ = ["pid", "_name", "_ppid", "_procfs_path"]

    def __init__(self, pid):
        self.pid = pid
        self._name = None
        self._ppid = None
        self._procfs_path = get_procfs_path()

    def oneshot_enter(self):
        self._proc_name_and_args.cache_activate()
        self._proc_basic_info.cache_activate()
        self._proc_cred.cache_activate()

    def oneshot_exit(self):
        self._proc_name_and_args.cache_deactivate()
        self._proc_basic_info.cache_deactivate()
        self._proc_cred.cache_deactivate()

    @memoize_when_activated
    def _proc_name_and_args(self):
        return cext.proc_name_and_args(self.pid, self._procfs_path)

    @memoize_when_activated
    def _proc_basic_info(self):
        ret = cext.proc_basic_info(self.pid, self._procfs_path)
        assert len(ret) == len(proc_info_map)
        return ret

    @memoize_when_activated
    def _proc_cred(self):
        return cext.proc_cred(self.pid, self._procfs_path)

    @wrap_exceptions
    def name(self):
        # note: max len == 15
        return self._proc_name_and_args()[0]

    @wrap_exceptions
    def exe(self):
        try:
            return os.readlink(
                "%s/%s/path/a.out" % (self._procfs_path, self.pid))
        except OSError:
            pass    # continue and guess the exe name from the cmdline
        # Will be guessed later from cmdline but we want to explicitly
        # invoke cmdline here in order to get an AccessDenied
        # exception if the user has not enough privileges.
        self.cmdline()
        return ""

    @wrap_exceptions
    def cmdline(self):
        return self._proc_name_and_args()[1].split(' ')

    @wrap_exceptions
    def environ(self):
        return cext.proc_environ(self.pid, self._procfs_path)

    @wrap_exceptions
    def create_time(self):
        return self._proc_basic_info()[proc_info_map['create_time']]

    @wrap_exceptions
    def num_threads(self):
        return self._proc_basic_info()[proc_info_map['num_threads']]

    @wrap_exceptions
    def nice_get(self):
        # Note #1: for some reason getpriority(3) return ESRCH (no such
        # process) for certain low-pid processes, no matter what (even
        # as root).
        # The process actually exists though, as it has a name,
        # creation time, etc.
        # The best thing we can do here appears to be raising AD.
        # Note: tested on Solaris 11; on Open Solaris 5 everything is
        # fine.
        #
        # Note #2: we also can get niceness from /proc/pid/psinfo
        # but it's wrong, see:
        # https://github.com/giampaolo/psutil/issues/1082
        try:
            return cext_posix.getpriority(self.pid)
        except EnvironmentError as err:
            # 48 is 'operation not supported' but errno does not expose
            # it. It occurs for low system pids.
            if err.errno in (errno.ENOENT, errno.ESRCH, 48):
                if pid_exists(self.pid):
                    raise AccessDenied(self.pid, self._name)
            raise

    @wrap_exceptions
    def nice_set(self, value):
        if self.pid in (2, 3):
            # Special case PIDs: internally setpriority(3) return ESRCH
            # (no such process), no matter what.
            # The process actually exists though, as it has a name,
            # creation time, etc.
            raise AccessDenied(self.pid, self._name)
        return cext_posix.setpriority(self.pid, value)

    @wrap_exceptions
    def ppid(self):
        self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
        return self._ppid

    @wrap_exceptions
    def uids(self):
        real, effective, saved, _, _, _ = self._proc_cred()
        return _common.puids(real, effective, saved)

    @wrap_exceptions
    def gids(self):
        _, _, _, real, effective, saved = self._proc_cred()
        return _common.puids(real, effective, saved)

    @wrap_exceptions
    def cpu_times(self):
        try:
            times = cext.proc_cpu_times(self.pid, self._procfs_path)
        except OSError as err:
            if err.errno == errno.EOVERFLOW and not IS_64_BIT:
                # We may get here if we attempt to query a 64bit process
                # with a 32bit python.
                # Error originates from read() and also tools like "cat"
                # fail in the same way (!).
                # Since there simply is no way to determine CPU times we
                # return 0.0 as a fallback. See:
                # https://github.com/giampaolo/psutil/issues/857
                times = (0.0, 0.0, 0.0, 0.0)
            else:
                raise
        return _common.pcputimes(*times)

    @wrap_exceptions
    def cpu_num(self):
        return cext.proc_cpu_num(self.pid, self._procfs_path)

    @wrap_exceptions
    def terminal(self):
        procfs_path = self._procfs_path
        hit_enoent = False
        tty = wrap_exceptions(
            self._proc_basic_info()[proc_info_map['ttynr']])
        if tty != cext.PRNODEV:
            for x in (0, 1, 2, 255):
                try:
                    return os.readlink(
                        '%s/%d/path/%d' % (procfs_path, self.pid, x))
                except OSError as err:
                    if err.errno == errno.ENOENT:
                        hit_enoent = True
                        continue
                    raise
        if hit_enoent:
            # raise NSP if the process disappeared on us
            os.stat('%s/%s' % (procfs_path, self.pid))

    @wrap_exceptions
    def cwd(self):
        # /proc/PID/path/cwd may not be resolved by readlink() even if
        # it exists (ls shows it). If that's the case and the process
        # is still alive return None (we can return None also on BSD).
        # Reference: http://goo.gl/55XgO
        procfs_path = self._procfs_path
        try:
            return os.readlink("%s/%s/path/cwd" % (procfs_path, self.pid))
        except OSError as err:
            if err.errno == errno.ENOENT:
                os.stat("%s/%s" % (procfs_path, self.pid))  # raise NSP or AD
                return None
            raise

    @wrap_exceptions
    def memory_info(self):
        ret = self._proc_basic_info()
        rss = ret[proc_info_map['rss']] * 1024
        vms = ret[proc_info_map['vms']] * 1024
        return pmem(rss, vms)

    memory_full_info = memory_info

    @wrap_exceptions
    def status(self):
        code = self._proc_basic_info()[proc_info_map['status']]
        # XXX is '?' legit? (we're not supposed to return it anyway)
        return PROC_STATUSES.get(code, '?')

    @wrap_exceptions
    def threads(self):
        procfs_path = self._procfs_path
        ret = []
        tids = os.listdir('%s/%d/lwp' % (procfs_path, self.pid))
        hit_enoent = False
        for tid in tids:
            tid = int(tid)
            try:
                utime, stime = cext.query_process_thread(
                    self.pid, tid, procfs_path)
            except EnvironmentError as err:
                if err.errno == errno.EOVERFLOW and not IS_64_BIT:
                    # We may get here if we attempt to query a 64bit process
                    # with a 32bit python.
                    # Error originates from read() and also tools like "cat"
                    # fail in the same way (!).
                    # Since there simply is no way to determine CPU times we
                    # return 0.0 as a fallback. See:
                    # https://github.com/giampaolo/psutil/issues/857
                    continue
                # ENOENT == thread gone in meantime
                if err.errno == errno.ENOENT:
                    hit_enoent = True
                    continue
                raise
            else:
                nt = _common.pthread(tid, utime, stime)
                ret.append(nt)
        if hit_enoent:
            # raise NSP if the process disappeared on us
            os.stat('%s/%s' % (procfs_path, self.pid))
        return ret

    @wrap_exceptions
    def open_files(self):
        retlist = []
        hit_enoent = False
        procfs_path = self._procfs_path
        pathdir = '%s/%d/path' % (procfs_path, self.pid)
        for fd in os.listdir('%s/%d/fd' % (procfs_path, self.pid)):
            path = os.path.join(pathdir, fd)
            if os.path.islink(path):
                try:
                    file = os.readlink(path)
                except OSError as err:
                    # ENOENT == file which is gone in the meantime
                    if err.errno == errno.ENOENT:
                        hit_enoent = True
                        continue
                    raise
                else:
                    if isfile_strict(file):
                        retlist.append(_common.popenfile(file, int(fd)))
        if hit_enoent:
            # raise NSP if the process disappeared on us
            os.stat('%s/%s' % (procfs_path, self.pid))
        return retlist

    def _get_unix_sockets(self, pid):
        """Get UNIX sockets used by process by parsing 'pfiles' output."""
        # TODO: rewrite this in C (...but the damn netstat source code
        # does not include this part! Argh!!)
        cmd = "pfiles %s" % pid
        p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if PY3:
            stdout, stderr = [x.decode(sys.stdout.encoding)
                              for x in (stdout, stderr)]
        if p.returncode != 0:
            if 'permission denied' in stderr.lower():
                raise AccessDenied(self.pid, self._name)
            if 'no such process' in stderr.lower():
                raise NoSuchProcess(self.pid, self._name)
            raise RuntimeError("%r command error\n%s" % (cmd, stderr))

        lines = stdout.split('\n')[2:]
        for i, line in enumerate(lines):
            line = line.lstrip()
            if line.startswith('sockname: AF_UNIX'):
                path = line.split(' ', 2)[2]
                type = lines[i - 2].strip()
                if type == 'SOCK_STREAM':
                    type = socket.SOCK_STREAM
                elif type == 'SOCK_DGRAM':
                    type = socket.SOCK_DGRAM
                else:
                    type = -1
                yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)

    @wrap_exceptions
    def connections(self, kind='inet'):
        ret = net_connections(kind, _pid=self.pid)
        # The underlying C implementation retrieves all OS connections
        # and filters them by PID.  At this point we can't tell whether
        # an empty list means there were no connections for process or
        # process is no longer active so we force NSP in case the PID
        # is no longer there.
        if not ret:
            # will raise NSP if process is gone
            os.stat('%s/%s' % (self._procfs_path, self.pid))

        # UNIX sockets
        if kind in ('all', 'unix'):
            ret.extend([_common.pconn(*conn) for conn in
                        self._get_unix_sockets(self.pid)])
        return ret

    nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked')
    nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked')

    @wrap_exceptions
    def memory_maps(self):
        def toaddr(start, end):
            return '%s-%s' % (hex(start)[2:].strip('L'),
                              hex(end)[2:].strip('L'))

        procfs_path = self._procfs_path
        retlist = []
        try:
            rawlist = cext.proc_memory_maps(self.pid, procfs_path)
        except OSError as err:
            if err.errno == errno.EOVERFLOW and not IS_64_BIT:
                # We may get here if we attempt to query a 64bit process
                # with a 32bit python.
                # Error originates from read() and also tools like "cat"
                # fail in the same way (!).
                # Since there simply is no way to determine CPU times we
                # return 0.0 as a fallback. See:
                # https://github.com/giampaolo/psutil/issues/857
                return []
            else:
                raise
        hit_enoent = False
        for item in rawlist:
            addr, addrsize, perm, name, rss, anon, locked = item
            addr = toaddr(addr, addrsize)
            if not name.startswith('['):
                try:
                    name = os.readlink(
                        '%s/%s/path/%s' % (procfs_path, self.pid, name))
                except OSError as err:
                    if err.errno == errno.ENOENT:
                        # sometimes the link may not be resolved by
                        # readlink() even if it exists (ls shows it).
                        # If that's the case we just return the
                        # unresolved link path.
                        # This seems an incosistency with /proc similar
                        # to: http://goo.gl/55XgO
                        name = '%s/%s/path/%s' % (procfs_path, self.pid, name)
                        hit_enoent = True
                    else:
                        raise
            retlist.append((addr, perm, name, rss, anon, locked))
        if hit_enoent:
            # raise NSP if the process disappeared on us
            os.stat('%s/%s' % (procfs_path, self.pid))
        return retlist

    @wrap_exceptions
    def num_fds(self):
        return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))

    @wrap_exceptions
    def num_ctx_switches(self):
        return _common.pctxsw(
            *cext.proc_num_ctx_switches(self.pid, self._procfs_path))

    @wrap_exceptions
    def wait(self, timeout=None):
        return _psposix.wait_pid(self.pid, timeout, self._name)
_psbsd.py000064400000073044150466730540006412 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""FreeBSD, OpenBSD and NetBSD platforms implementation."""

import contextlib
import errno
import functools
import os
import xml.etree.ElementTree as ET
from collections import namedtuple
from socket import AF_INET

from . import _common
from . import _psposix
from . import _psutil_bsd as cext
from . import _psutil_posix as cext_posix
from ._common import AF_INET6
from ._common import conn_tmap
from ._common import FREEBSD
from ._common import memoize
from ._common import memoize_when_activated
from ._common import NETBSD
from ._common import OPENBSD
from ._common import sockfam_to_enum
from ._common import socktype_to_enum
from ._common import usage_percent
from ._compat import which
from ._exceptions import AccessDenied
from ._exceptions import NoSuchProcess
from ._exceptions import ZombieProcess

__extra__all__ = []


# =====================================================================
# --- globals
# =====================================================================


if FREEBSD:
    PROC_STATUSES = {
        cext.SIDL: _common.STATUS_IDLE,
        cext.SRUN: _common.STATUS_RUNNING,
        cext.SSLEEP: _common.STATUS_SLEEPING,
        cext.SSTOP: _common.STATUS_STOPPED,
        cext.SZOMB: _common.STATUS_ZOMBIE,
        cext.SWAIT: _common.STATUS_WAITING,
        cext.SLOCK: _common.STATUS_LOCKED,
    }
elif OPENBSD or NETBSD:
    PROC_STATUSES = {
        cext.SIDL: _common.STATUS_IDLE,
        cext.SSLEEP: _common.STATUS_SLEEPING,
        cext.SSTOP: _common.STATUS_STOPPED,
        # According to /usr/include/sys/proc.h SZOMB is unused.
        # test_zombie_process() shows that SDEAD is the right
        # equivalent. Also it appears there's no equivalent of
        # psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE.
        # cext.SZOMB: _common.STATUS_ZOMBIE,
        cext.SDEAD: _common.STATUS_ZOMBIE,
        cext.SZOMB: _common.STATUS_ZOMBIE,
        # From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt
        # OpenBSD has SRUN and SONPROC: SRUN indicates that a process
        # is runnable but *not* yet running, i.e. is on a run queue.
        # SONPROC indicates that the process is actually executing on
        # a CPU, i.e. it is no longer on a run queue.
        # As such we'll map SRUN to STATUS_WAKING and SONPROC to
        # STATUS_RUNNING
        cext.SRUN: _common.STATUS_WAKING,
        cext.SONPROC: _common.STATUS_RUNNING,
    }
elif NETBSD:
    PROC_STATUSES = {
        cext.SIDL: _common.STATUS_IDLE,
        cext.SACTIVE: _common.STATUS_RUNNING,
        cext.SDYING: _common.STATUS_ZOMBIE,
        cext.SSTOP: _common.STATUS_STOPPED,
        cext.SZOMB: _common.STATUS_ZOMBIE,
        cext.SDEAD: _common.STATUS_DEAD,
        cext.SSUSPENDED: _common.STATUS_SUSPENDED,  # unique to NetBSD
    }

TCP_STATUSES = {
    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
    cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
    cext.TCPS_CLOSED: _common.CONN_CLOSE,
    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
    cext.TCPS_LISTEN: _common.CONN_LISTEN,
    cext.TCPS_CLOSING: _common.CONN_CLOSING,
    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}

if NETBSD:
    PAGESIZE = os.sysconf("SC_PAGESIZE")
else:
    PAGESIZE = os.sysconf("SC_PAGE_SIZE")
AF_LINK = cext_posix.AF_LINK

kinfo_proc_map = dict(
    ppid=0,
    status=1,
    real_uid=2,
    effective_uid=3,
    saved_uid=4,
    real_gid=5,
    effective_gid=6,
    saved_gid=7,
    ttynr=8,
    create_time=9,
    ctx_switches_vol=10,
    ctx_switches_unvol=11,
    read_io_count=12,
    write_io_count=13,
    user_time=14,
    sys_time=15,
    ch_user_time=16,
    ch_sys_time=17,
    rss=18,
    vms=19,
    memtext=20,
    memdata=21,
    memstack=22,
    cpunum=23,
    name=24,
)


# =====================================================================
# --- named tuples
# =====================================================================


# psutil.virtual_memory()
svmem = namedtuple(
    'svmem', ['total', 'available', 'percent', 'used', 'free',
              'active', 'inactive', 'buffers', 'cached', 'shared', 'wired'])
# psutil.cpu_times()
scputimes = namedtuple(
    'scputimes', ['user', 'nice', 'system', 'idle', 'irq'])
# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms', 'text', 'data', 'stack'])
# psutil.Process.memory_full_info()
pfullmem = pmem
# psutil.Process.cpu_times()
pcputimes = namedtuple('pcputimes',
                       ['user', 'system', 'children_user', 'children_system'])
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple(
    'pmmap_grouped', 'path rss, private, ref_count, shadow_count')
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
    'pmmap_ext', 'addr, perms path rss, private, ref_count, shadow_count')
# psutil.disk_io_counters()
if FREEBSD:
    sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
                                     'read_bytes', 'write_bytes',
                                     'read_time', 'write_time',
                                     'busy_time'])
else:
    sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
                                     'read_bytes', 'write_bytes'])


# =====================================================================
# --- memory
# =====================================================================


def virtual_memory():
    """System virtual memory as a namedtuple."""
    mem = cext.virtual_mem()
    total, free, active, inactive, wired, cached, buffers, shared = mem
    if NETBSD:
        # On NetBSD buffers and shared mem is determined via /proc.
        # The C ext set them to 0.
        with open('/proc/meminfo', 'rb') as f:
            for line in f:
                if line.startswith(b'Buffers:'):
                    buffers = int(line.split()[1]) * 1024
                elif line.startswith(b'MemShared:'):
                    shared = int(line.split()[1]) * 1024
    avail = inactive + cached + free
    used = active + wired + cached
    percent = usage_percent((total - avail), total, _round=1)
    return svmem(total, avail, percent, used, free,
                 active, inactive, buffers, cached, shared, wired)


def swap_memory():
    """System swap memory as (total, used, free, sin, sout) namedtuple."""
    total, used, free, sin, sout = cext.swap_mem()
    percent = usage_percent(used, total, _round=1)
    return _common.sswap(total, used, free, percent, sin, sout)


# =====================================================================
# --- CPU
# =====================================================================


def cpu_times():
    """Return system per-CPU times as a namedtuple"""
    user, nice, system, idle, irq = cext.cpu_times()
    return scputimes(user, nice, system, idle, irq)


if hasattr(cext, "per_cpu_times"):
    def per_cpu_times():
        """Return system CPU times as a namedtuple"""
        ret = []
        for cpu_t in cext.per_cpu_times():
            user, nice, system, idle, irq = cpu_t
            item = scputimes(user, nice, system, idle, irq)
            ret.append(item)
        return ret
else:
    # XXX
    # Ok, this is very dirty.
    # On FreeBSD < 8 we cannot gather per-cpu information, see:
    # https://github.com/giampaolo/psutil/issues/226
    # If num cpus > 1, on first call we return single cpu times to avoid a
    # crash at psutil import time.
    # Next calls will fail with NotImplementedError
    def per_cpu_times():
        """Return system CPU times as a namedtuple"""
        if cpu_count_logical() == 1:
            return [cpu_times()]
        if per_cpu_times.__called__:
            raise NotImplementedError("supported only starting from FreeBSD 8")
        per_cpu_times.__called__ = True
        return [cpu_times()]

    per_cpu_times.__called__ = False


def cpu_count_logical():
    """Return the number of logical CPUs in the system."""
    return cext.cpu_count_logical()


if OPENBSD or NETBSD:
    def cpu_count_physical():
        # OpenBSD and NetBSD do not implement this.
        return 1 if cpu_count_logical() == 1 else None
else:
    def cpu_count_physical():
        """Return the number of physical CPUs in the system."""
        # From the C module we'll get an XML string similar to this:
        # http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html
        # We may get None in case "sysctl kern.sched.topology_spec"
        # is not supported on this BSD version, in which case we'll mimic
        # os.cpu_count() and return None.
        ret = None
        s = cext.cpu_count_phys()
        if s is not None:
            # get rid of padding chars appended at the end of the string
            index = s.rfind("</groups>")
            if index != -1:
                s = s[:index + 9]
                root = ET.fromstring(s)
                try:
                    ret = len(root.findall('group/children/group/cpu')) or None
                finally:
                    # needed otherwise it will memleak
                    root.clear()
        if not ret:
            # If logical CPUs are 1 it's obvious we'll have only 1
            # physical CPU.
            if cpu_count_logical() == 1:
                return 1
        return ret


def cpu_stats():
    """Return various CPU stats as a named tuple."""
    if FREEBSD:
        # Note: the C ext is returning some metrics we are not exposing:
        # traps.
        ctxsw, intrs, soft_intrs, syscalls, traps = cext.cpu_stats()
    elif NETBSD:
        # XXX
        # Note about intrs: the C extension returns 0. intrs
        # can be determined via /proc/stat; it has the same value as
        # soft_intrs thought so the kernel is faking it (?).
        #
        # Note about syscalls: the C extension always sets it to 0 (?).
        #
        # Note: the C ext is returning some metrics we are not exposing:
        # traps, faults and forks.
        ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \
            cext.cpu_stats()
        with open('/proc/stat', 'rb') as f:
            for line in f:
                if line.startswith(b'intr'):
                    intrs = int(line.split()[1])
    elif OPENBSD:
        # Note: the C ext is returning some metrics we are not exposing:
        # traps, faults and forks.
        ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \
            cext.cpu_stats()
    return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls)


# =====================================================================
# --- disks
# =====================================================================


def disk_partitions(all=False):
    """Return mounted disk partitions as a list of namedtuples.
    'all' argument is ignored, see:
    https://github.com/giampaolo/psutil/issues/906
    """
    retlist = []
    partitions = cext.disk_partitions()
    for partition in partitions:
        device, mountpoint, fstype, opts = partition
        ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
        retlist.append(ntuple)
    return retlist


disk_usage = _psposix.disk_usage
disk_io_counters = cext.disk_io_counters


# =====================================================================
# --- network
# =====================================================================


net_io_counters = cext.net_io_counters
net_if_addrs = cext_posix.net_if_addrs


def net_if_stats():
    """Get NIC stats (isup, duplex, speed, mtu)."""
    names = net_io_counters().keys()
    ret = {}
    for name in names:
        mtu = cext_posix.net_if_mtu(name)
        isup = cext_posix.net_if_flags(name)
        duplex, speed = cext_posix.net_if_duplex_speed(name)
        if hasattr(_common, 'NicDuplex'):
            duplex = _common.NicDuplex(duplex)
        ret[name] = _common.snicstats(isup, duplex, speed, mtu)
    return ret


def net_connections(kind):
    """System-wide network connections."""
    if OPENBSD:
        ret = []
        for pid in pids():
            try:
                cons = Process(pid).connections(kind)
            except (NoSuchProcess, ZombieProcess):
                continue
            else:
                for conn in cons:
                    conn = list(conn)
                    conn.append(pid)
                    ret.append(_common.sconn(*conn))
        return ret

    if kind not in _common.conn_tmap:
        raise ValueError("invalid %r kind argument; choose between %s"
                         % (kind, ', '.join([repr(x) for x in conn_tmap])))
    families, types = conn_tmap[kind]
    ret = set()
    if NETBSD:
        rawlist = cext.net_connections(-1)
    else:
        rawlist = cext.net_connections()
    for item in rawlist:
        fd, fam, type, laddr, raddr, status, pid = item
        # TODO: apply filter at C level
        if fam in families and type in types:
            try:
                status = TCP_STATUSES[status]
            except KeyError:
                # XXX: Not sure why this happens. I saw this occurring
                # with IPv6 sockets opened by 'vim'. Those sockets
                # have a very short lifetime so maybe the kernel
                # can't initialize their status?
                status = TCP_STATUSES[cext.PSUTIL_CONN_NONE]
            if fam in (AF_INET, AF_INET6):
                if laddr:
                    laddr = _common.addr(*laddr)
                if raddr:
                    raddr = _common.addr(*raddr)
            fam = sockfam_to_enum(fam)
            type = socktype_to_enum(type)
            nt = _common.sconn(fd, fam, type, laddr, raddr, status, pid)
            ret.add(nt)
    return list(ret)


# =====================================================================
#  --- sensors
# =====================================================================


if FREEBSD:

    def sensors_battery():
        """Return battery info."""
        try:
            percent, minsleft, power_plugged = cext.sensors_battery()
        except NotImplementedError:
            # See: https://github.com/giampaolo/psutil/issues/1074
            return None
        power_plugged = power_plugged == 1
        if power_plugged:
            secsleft = _common.POWER_TIME_UNLIMITED
        elif minsleft == -1:
            secsleft = _common.POWER_TIME_UNKNOWN
        else:
            secsleft = minsleft * 60
        return _common.sbattery(percent, secsleft, power_plugged)


# =====================================================================
#  --- other system functions
# =====================================================================


def boot_time():
    """The system boot time expressed in seconds since the epoch."""
    return cext.boot_time()


def users():
    """Return currently connected users as a list of namedtuples."""
    retlist = []
    rawlist = cext.users()
    for item in rawlist:
        user, tty, hostname, tstamp, pid = item
        if pid == -1:
            assert OPENBSD
            pid = None
        if tty == '~':
            continue  # reboot or shutdown
        nt = _common.suser(user, tty or None, hostname, tstamp, pid)
        retlist.append(nt)
    return retlist


# =====================================================================
# --- processes
# =====================================================================


@memoize
def _pid_0_exists():
    try:
        Process(0).name()
    except NoSuchProcess:
        return False
    except AccessDenied:
        return True
    else:
        return True


def pids():
    """Returns a list of PIDs currently running on the system."""
    ret = cext.pids()
    if OPENBSD and (0 not in ret) and _pid_0_exists():
        # On OpenBSD the kernel does not return PID 0 (neither does
        # ps) but it's actually querable (Process(0) will succeed).
        ret.insert(0, 0)
    return ret


if OPENBSD or NETBSD:
    def pid_exists(pid):
        """Return True if pid exists."""
        exists = _psposix.pid_exists(pid)
        if not exists:
            # We do this because _psposix.pid_exists() lies in case of
            # zombie processes.
            return pid in pids()
        else:
            return True
else:
    pid_exists = _psposix.pid_exists


def wrap_exceptions(fun):
    """Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            if self.pid == 0:
                if 0 in pids():
                    raise AccessDenied(self.pid, self._name)
                else:
                    raise
            if err.errno == errno.ESRCH:
                if not pid_exists(self.pid):
                    raise NoSuchProcess(self.pid, self._name)
                else:
                    raise ZombieProcess(self.pid, self._name, self._ppid)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
    return wrapper


@contextlib.contextmanager
def wrap_exceptions_procfs(inst):
    """Same as above, for routines relying on reading /proc fs."""
    try:
        yield
    except EnvironmentError as err:
        # ENOENT (no such file or directory) gets raised on open().
        # ESRCH (no such process) can get raised on read() if
        # process is gone in meantime.
        if err.errno in (errno.ENOENT, errno.ESRCH):
            if not pid_exists(inst.pid):
                raise NoSuchProcess(inst.pid, inst._name)
            else:
                raise ZombieProcess(inst.pid, inst._name, inst._ppid)
        if err.errno in (errno.EPERM, errno.EACCES):
            raise AccessDenied(inst.pid, inst._name)
        raise


class Process(object):
    """Wrapper class around underlying C implementation."""

    __slots__ = ["pid", "_name", "_ppid"]

    def __init__(self, pid):
        self.pid = pid
        self._name = None
        self._ppid = None

    @memoize_when_activated
    def oneshot(self):
        """Retrieves multiple process info in one shot as a raw tuple."""
        ret = cext.proc_oneshot_info(self.pid)
        assert len(ret) == len(kinfo_proc_map)
        return ret

    def oneshot_enter(self):
        self.oneshot.cache_activate()

    def oneshot_exit(self):
        self.oneshot.cache_deactivate()

    @wrap_exceptions
    def name(self):
        name = self.oneshot()[kinfo_proc_map['name']]
        return name if name is not None else cext.proc_name(self.pid)

    @wrap_exceptions
    def exe(self):
        if FREEBSD:
            return cext.proc_exe(self.pid)
        elif NETBSD:
            if self.pid == 0:
                # /proc/0 dir exists but /proc/0/exe doesn't
                return ""
            with wrap_exceptions_procfs(self):
                return os.readlink("/proc/%s/exe" % self.pid)
        else:
            # OpenBSD: exe cannot be determined; references:
            # https://chromium.googlesource.com/chromium/src/base/+/
            #     master/base_paths_posix.cc
            # We try our best guess by using which against the first
            # cmdline arg (may return None).
            cmdline = self.cmdline()
            if cmdline:
                return which(cmdline[0])
            else:
                return ""

    @wrap_exceptions
    def cmdline(self):
        if OPENBSD and self.pid == 0:
            return []  # ...else it crashes
        elif NETBSD:
            # XXX - most of the times the underlying sysctl() call on Net
            # and Open BSD returns a truncated string.
            # Also /proc/pid/cmdline behaves the same so it looks
            # like this is a kernel bug.
            try:
                return cext.proc_cmdline(self.pid)
            except OSError as err:
                if err.errno == errno.EINVAL:
                    if not pid_exists(self.pid):
                        raise NoSuchProcess(self.pid, self._name)
                    else:
                        raise ZombieProcess(self.pid, self._name, self._ppid)
                else:
                    raise
        else:
            return cext.proc_cmdline(self.pid)

    @wrap_exceptions
    def terminal(self):
        tty_nr = self.oneshot()[kinfo_proc_map['ttynr']]
        tmap = _psposix.get_terminal_map()
        try:
            return tmap[tty_nr]
        except KeyError:
            return None

    @wrap_exceptions
    def ppid(self):
        self._ppid = self.oneshot()[kinfo_proc_map['ppid']]
        return self._ppid

    @wrap_exceptions
    def uids(self):
        rawtuple = self.oneshot()
        return _common.puids(
            rawtuple[kinfo_proc_map['real_uid']],
            rawtuple[kinfo_proc_map['effective_uid']],
            rawtuple[kinfo_proc_map['saved_uid']])

    @wrap_exceptions
    def gids(self):
        rawtuple = self.oneshot()
        return _common.pgids(
            rawtuple[kinfo_proc_map['real_gid']],
            rawtuple[kinfo_proc_map['effective_gid']],
            rawtuple[kinfo_proc_map['saved_gid']])

    @wrap_exceptions
    def cpu_times(self):
        rawtuple = self.oneshot()
        return _common.pcputimes(
            rawtuple[kinfo_proc_map['user_time']],
            rawtuple[kinfo_proc_map['sys_time']],
            rawtuple[kinfo_proc_map['ch_user_time']],
            rawtuple[kinfo_proc_map['ch_sys_time']])

    if FREEBSD:
        @wrap_exceptions
        def cpu_num(self):
            return self.oneshot()[kinfo_proc_map['cpunum']]

    @wrap_exceptions
    def memory_info(self):
        rawtuple = self.oneshot()
        return pmem(
            rawtuple[kinfo_proc_map['rss']],
            rawtuple[kinfo_proc_map['vms']],
            rawtuple[kinfo_proc_map['memtext']],
            rawtuple[kinfo_proc_map['memdata']],
            rawtuple[kinfo_proc_map['memstack']])

    memory_full_info = memory_info

    @wrap_exceptions
    def create_time(self):
        return self.oneshot()[kinfo_proc_map['create_time']]

    @wrap_exceptions
    def num_threads(self):
        if hasattr(cext, "proc_num_threads"):
            # FreeBSD
            return cext.proc_num_threads(self.pid)
        else:
            return len(self.threads())

    @wrap_exceptions
    def num_ctx_switches(self):
        rawtuple = self.oneshot()
        return _common.pctxsw(
            rawtuple[kinfo_proc_map['ctx_switches_vol']],
            rawtuple[kinfo_proc_map['ctx_switches_unvol']])

    @wrap_exceptions
    def threads(self):
        # Note: on OpenSBD this (/dev/mem) requires root access.
        rawlist = cext.proc_threads(self.pid)
        retlist = []
        for thread_id, utime, stime in rawlist:
            ntuple = _common.pthread(thread_id, utime, stime)
            retlist.append(ntuple)
        if OPENBSD:
            # On OpenBSD the underlying C function does not raise NSP
            # in case the process is gone (and the returned list may
            # incomplete).
            self.name()  # raise NSP if the process disappeared on us
        return retlist

    @wrap_exceptions
    def connections(self, kind='inet'):
        if kind not in conn_tmap:
            raise ValueError("invalid %r kind argument; choose between %s"
                             % (kind, ', '.join([repr(x) for x in conn_tmap])))

        if NETBSD:
            families, types = conn_tmap[kind]
            ret = set()
            rawlist = cext.net_connections(self.pid)
            for item in rawlist:
                fd, fam, type, laddr, raddr, status, pid = item
                assert pid == self.pid
                if fam in families and type in types:
                    try:
                        status = TCP_STATUSES[status]
                    except KeyError:
                        status = TCP_STATUSES[cext.PSUTIL_CONN_NONE]
                    if fam in (AF_INET, AF_INET6):
                        if laddr:
                            laddr = _common.addr(*laddr)
                        if raddr:
                            raddr = _common.addr(*raddr)
                    fam = sockfam_to_enum(fam)
                    type = socktype_to_enum(type)
                    nt = _common.pconn(fd, fam, type, laddr, raddr, status)
                    ret.add(nt)
            # On NetBSD the underlying C function does not raise NSP
            # in case the process is gone (and the returned list may
            # incomplete).
            self.name()  # raise NSP if the process disappeared on us
            return list(ret)

        families, types = conn_tmap[kind]
        rawlist = cext.proc_connections(self.pid, families, types)
        ret = []
        for item in rawlist:
            fd, fam, type, laddr, raddr, status = item
            if fam in (AF_INET, AF_INET6):
                if laddr:
                    laddr = _common.addr(*laddr)
                if raddr:
                    raddr = _common.addr(*raddr)
            fam = sockfam_to_enum(fam)
            type = socktype_to_enum(type)
            status = TCP_STATUSES[status]
            nt = _common.pconn(fd, fam, type, laddr, raddr, status)
            ret.append(nt)
        if OPENBSD:
            # On OpenBSD the underlying C function does not raise NSP
            # in case the process is gone (and the returned list may
            # incomplete).
            self.name()  # raise NSP if the process disappeared on us
        return ret

    @wrap_exceptions
    def wait(self, timeout=None):
        return _psposix.wait_pid(self.pid, timeout, self._name)

    @wrap_exceptions
    def nice_get(self):
        return cext_posix.getpriority(self.pid)

    @wrap_exceptions
    def nice_set(self, value):
        return cext_posix.setpriority(self.pid, value)

    @wrap_exceptions
    def status(self):
        code = self.oneshot()[kinfo_proc_map['status']]
        # XXX is '?' legit? (we're not supposed to return it anyway)
        return PROC_STATUSES.get(code, '?')

    @wrap_exceptions
    def io_counters(self):
        rawtuple = self.oneshot()
        return _common.pio(
            rawtuple[kinfo_proc_map['read_io_count']],
            rawtuple[kinfo_proc_map['write_io_count']],
            -1,
            -1)

    @wrap_exceptions
    def cwd(self):
        """Return process current working directory."""
        # sometimes we get an empty string, in which case we turn
        # it into None
        if OPENBSD and self.pid == 0:
            return None  # ...else it would raise EINVAL
        elif NETBSD:
            with wrap_exceptions_procfs(self):
                return os.readlink("/proc/%s/cwd" % self.pid)
        elif hasattr(cext, 'proc_open_files'):
            # FreeBSD < 8 does not support functions based on
            # kinfo_getfile() and kinfo_getvmmap()
            return cext.proc_cwd(self.pid) or None
        else:
            raise NotImplementedError(
                "supported only starting from FreeBSD 8" if
                FREEBSD else "")

    nt_mmap_grouped = namedtuple(
        'mmap', 'path rss, private, ref_count, shadow_count')
    nt_mmap_ext = namedtuple(
        'mmap', 'addr, perms path rss, private, ref_count, shadow_count')

    def _not_implemented(self):
        raise NotImplementedError

    # FreeBSD < 8 does not support functions based on kinfo_getfile()
    # and kinfo_getvmmap()
    if hasattr(cext, 'proc_open_files'):
        @wrap_exceptions
        def open_files(self):
            """Return files opened by process as a list of namedtuples."""
            rawlist = cext.proc_open_files(self.pid)
            return [_common.popenfile(path, fd) for path, fd in rawlist]
    else:
        open_files = _not_implemented

    # FreeBSD < 8 does not support functions based on kinfo_getfile()
    # and kinfo_getvmmap()
    if hasattr(cext, 'proc_num_fds'):
        @wrap_exceptions
        def num_fds(self):
            """Return the number of file descriptors opened by this process."""
            ret = cext.proc_num_fds(self.pid)
            if NETBSD:
                # On NetBSD the underlying C function does not raise NSP
                # in case the process is gone.
                self.name()  # raise NSP if the process disappeared on us
            return ret
    else:
        num_fds = _not_implemented

    # --- FreeBSD only APIs

    if FREEBSD:

        @wrap_exceptions
        def cpu_affinity_get(self):
            return cext.proc_cpu_affinity_get(self.pid)

        @wrap_exceptions
        def cpu_affinity_set(self, cpus):
            # Pre-emptively check if CPUs are valid because the C
            # function has a weird behavior in case of invalid CPUs,
            # see: https://github.com/giampaolo/psutil/issues/586
            allcpus = tuple(range(len(per_cpu_times())))
            for cpu in cpus:
                if cpu not in allcpus:
                    raise ValueError("invalid CPU #%i (choose between %s)"
                                     % (cpu, allcpus))
            try:
                cext.proc_cpu_affinity_set(self.pid, cpus)
            except OSError as err:
                # 'man cpuset_setaffinity' about EDEADLK:
                # <<the call would leave a thread without a valid CPU to run
                # on because the set does not overlap with the thread's
                # anonymous mask>>
                if err.errno in (errno.EINVAL, errno.EDEADLK):
                    for cpu in cpus:
                        if cpu not in allcpus:
                            raise ValueError(
                                "invalid CPU #%i (choose between %s)" % (
                                    cpu, allcpus))
                raise

        @wrap_exceptions
        def memory_maps(self):
            return cext.proc_memory_maps(self.pid)
tests/__init__.py000064400000111430150466730540010031 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Test utilities.
"""

from __future__ import print_function

import atexit
import contextlib
import ctypes
import errno
import functools
import os
import random
import re
import select
import shutil
import socket
import stat
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import traceback
import warnings
from socket import AF_INET
from socket import AF_INET6
from socket import SOCK_DGRAM
from socket import SOCK_STREAM

import psutil
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._common import supports_ipv6
from psutil._compat import PY3
from psutil._compat import u
from psutil._compat import unicode
from psutil._compat import which

if sys.version_info < (2, 7):
    import unittest2 as unittest  # requires "pip install unittest2"
else:
    import unittest

try:
    from unittest import mock  # py3
except ImportError:
    import mock  # NOQA - requires "pip install mock"

if sys.version_info >= (3, 4):
    import enum
else:
    enum = None


__all__ = [
    # constants
    'APPVEYOR', 'DEVNULL', 'GLOBAL_TIMEOUT', 'MEMORY_TOLERANCE', 'NO_RETRIES',
    'PYPY', 'PYTHON_EXE', 'ROOT_DIR', 'SCRIPTS_DIR', 'TESTFILE_PREFIX',
    'TESTFN', 'TESTFN_UNICODE', 'TOX', 'TRAVIS', 'VALID_PROC_STATUSES',
    'VERBOSITY',
    "HAS_CPU_AFFINITY", "HAS_CPU_FREQ", "HAS_ENVIRON", "HAS_PROC_IO_COUNTERS",
    "HAS_IONICE", "HAS_MEMORY_MAPS", "HAS_PROC_CPU_NUM", "HAS_RLIMIT",
    "HAS_SENSORS_BATTERY", "HAS_BATTERY", "HAS_SENSORS_FANS",
    "HAS_SENSORS_TEMPERATURES", "HAS_MEMORY_FULL_INFO",
    # subprocesses
    'pyrun', 'reap_children', 'get_test_subprocess', 'create_zombie_proc',
    'create_proc_children_pair',
    # threads
    'ThreadTask'
    # test utils
    'unittest', 'skip_on_access_denied', 'skip_on_not_implemented',
    'retry_before_failing', 'run_test_module_by_name', 'get_suite',
    'run_suite',
    # install utils
    'install_pip', 'install_test_deps',
    # fs utils
    'chdir', 'safe_rmpath', 'create_exe', 'decode_path', 'encode_path',
    'unique_filename',
    # os
    'get_winver', 'get_kernel_version',
    # sync primitives
    'call_until', 'wait_for_pid', 'wait_for_file',
    # network
    'check_connection_ntuple', 'check_net_address',
    'get_free_port', 'unix_socket_path', 'bind_socket', 'bind_unix_socket',
    'tcp_socketpair', 'unix_socketpair', 'create_sockets',
    # compat
    'reload_module', 'import_module_by_path',
    # others
    'warn', 'copyload_shared_lib', 'is_namedtuple',
]


# ===================================================================
# --- constants
# ===================================================================

# --- platforms

TOX = os.getenv('TOX') or '' in ('1', 'true')
PYPY = '__pypy__' in sys.builtin_module_names
WIN_VISTA = (6, 0, 0) if WINDOWS else None
# whether we're running this test suite on Travis (https://travis-ci.org/)
TRAVIS = bool(os.environ.get('TRAVIS'))
# whether we're running this test suite on Appveyor for Windows
# (http://www.appveyor.com/)
APPVEYOR = bool(os.environ.get('APPVEYOR'))

# --- configurable defaults

# how many times retry_before_failing() decorator will retry
NO_RETRIES = 10
# bytes tolerance for system-wide memory related tests
MEMORY_TOLERANCE = 500 * 1024  # 500KB
# the timeout used in functions which have to wait
GLOBAL_TIMEOUT = 3
# test output verbosity
VERBOSITY = 1 if os.getenv('SILENT') or TOX else 2
# be more tolerant if we're on travis / appveyor in order to avoid
# false positives
if TRAVIS or APPVEYOR:
    NO_RETRIES *= 3
    GLOBAL_TIMEOUT *= 3

# --- files

TESTFILE_PREFIX = '$testfn'
TESTFN = os.path.join(os.path.realpath(os.getcwd()), TESTFILE_PREFIX)
_TESTFN = TESTFN + '-internal'
TESTFN_UNICODE = TESTFN + u("-ƒőő")
ASCII_FS = sys.getfilesystemencoding().lower() in ('ascii', 'us-ascii')

# --- paths

ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
SCRIPTS_DIR = os.path.join(ROOT_DIR, 'scripts')
HERE = os.path.abspath(os.path.dirname(__file__))

# --- support

HAS_CPU_AFFINITY = hasattr(psutil.Process, "cpu_affinity")
HAS_CPU_FREQ = hasattr(psutil, "cpu_freq")
HAS_CONNECTIONS_UNIX = POSIX and not SUNOS
HAS_ENVIRON = hasattr(psutil.Process, "environ")
HAS_PROC_IO_COUNTERS = hasattr(psutil.Process, "io_counters")
HAS_IONICE = hasattr(psutil.Process, "ionice")
HAS_MEMORY_FULL_INFO = 'uss' in psutil.Process().memory_full_info()._fields
HAS_MEMORY_MAPS = hasattr(psutil.Process, "memory_maps")
HAS_PROC_CPU_NUM = hasattr(psutil.Process, "cpu_num")
HAS_RLIMIT = hasattr(psutil.Process, "rlimit")
HAS_THREADS = hasattr(psutil.Process, "threads")
HAS_SENSORS_BATTERY = hasattr(psutil, "sensors_battery")
HAS_BATTERY = HAS_SENSORS_BATTERY and psutil.sensors_battery()
HAS_SENSORS_FANS = hasattr(psutil, "sensors_fans")
HAS_SENSORS_TEMPERATURES = hasattr(psutil, "sensors_temperatures")

# --- misc


def _get_py_exe():
    def attempt(exe):
        try:
            subprocess.check_call(
                [exe, "-V"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except Exception:
            return None
        else:
            return exe

    if OSX:
        exe = \
            attempt(sys.executable) or \
            attempt(os.path.realpath(sys.executable)) or \
            attempt(which("python%s.%s" % sys.version_info[:2])) or \
            attempt(psutil.Process().exe())
        if not exe:
            raise ValueError("can't find python exe real abspath")
        return exe
    else:
        exe = os.path.realpath(sys.executable)
        assert os.path.exists(exe), exe
        return exe


PYTHON_EXE = _get_py_exe()
DEVNULL = open(os.devnull, 'r+')
VALID_PROC_STATUSES = [getattr(psutil, x) for x in dir(psutil)
                       if x.startswith('STATUS_')]
AF_UNIX = getattr(socket, "AF_UNIX", object())
SOCK_SEQPACKET = getattr(socket, "SOCK_SEQPACKET", object())

_subprocesses_started = set()
_pids_started = set()
_testfiles_created = set()


@atexit.register
def _cleanup_files():
    DEVNULL.close()
    for name in os.listdir(u('.')):
        if isinstance(name, unicode):
            prefix = u(TESTFILE_PREFIX)
        else:
            prefix = TESTFILE_PREFIX
        if name.startswith(prefix):
            try:
                safe_rmpath(name)
            except Exception:
                traceback.print_exc()
    for path in _testfiles_created:
        try:
            safe_rmpath(path)
        except Exception:
            traceback.print_exc()


# this is executed first
@atexit.register
def _cleanup_procs():
    reap_children(recursive=True)


# ===================================================================
# --- threads
# ===================================================================


class ThreadTask(threading.Thread):
    """A thread task which does nothing expect staying alive."""

    def __init__(self):
        threading.Thread.__init__(self)
        self._running = False
        self._interval = 0.001
        self._flag = threading.Event()

    def __repr__(self):
        name = self.__class__.__name__
        return '<%s running=%s at %#x>' % (name, self._running, id(self))

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, *args, **kwargs):
        self.stop()

    def start(self):
        """Start thread and keep it running until an explicit
        stop() request. Polls for shutdown every 'timeout' seconds.
        """
        if self._running:
            raise ValueError("already started")
        threading.Thread.start(self)
        self._flag.wait()

    def run(self):
        self._running = True
        self._flag.set()
        while self._running:
            time.sleep(self._interval)

    def stop(self):
        """Stop thread execution and and waits until it is stopped."""
        if not self._running:
            raise ValueError("already stopped")
        self._running = False
        self.join()


# ===================================================================
# --- subprocesses
# ===================================================================


def _cleanup_on_err(fun):
    @functools.wraps(fun)
    def wrapper(*args, **kwargs):
        try:
            return fun(*args, **kwargs)
        except Exception:
            reap_children()
            raise
    return wrapper


@_cleanup_on_err
def get_test_subprocess(cmd=None, **kwds):
    """Creates a python subprocess which does nothing for 60 secs and
    return it as subprocess.Popen instance.
    If "cmd" is specified that is used instead of python.
    By default stdin and stdout are redirected to /dev/null.
    It also attemps to make sure the process is in a reasonably
    initialized state.
    The process is registered for cleanup on reap_children().
    """
    kwds.setdefault("stdin", DEVNULL)
    kwds.setdefault("stdout", DEVNULL)
    kwds.setdefault("cwd", os.getcwd())
    kwds.setdefault("env", os.environ)
    if WINDOWS:
        # Prevents the subprocess to open error dialogs.
        kwds.setdefault("creationflags", 0x8000000)  # CREATE_NO_WINDOW
    if cmd is None:
        safe_rmpath(_TESTFN)
        pyline = "from time import sleep;" \
                 "open(r'%s', 'w').close();" \
                 "sleep(60);" % _TESTFN
        cmd = [PYTHON_EXE, "-c", pyline]
        sproc = subprocess.Popen(cmd, **kwds)
        _subprocesses_started.add(sproc)
        wait_for_file(_TESTFN, delete=True, empty=True)
    else:
        sproc = subprocess.Popen(cmd, **kwds)
        _subprocesses_started.add(sproc)
        wait_for_pid(sproc.pid)
    return sproc


@_cleanup_on_err
def create_proc_children_pair():
    """Create a subprocess which creates another one as in:
    A (us) -> B (child) -> C (grandchild).
    Return a (child, grandchild) tuple.
    The 2 processes are fully initialized and will live for 60 secs
    and are registered for cleanup on reap_children().
    """
    _TESTFN2 = os.path.basename(_TESTFN) + '2'  # need to be relative
    s = textwrap.dedent("""\
        import subprocess, os, sys, time
        s = "import os, time;"
        s += "f = open('%s', 'w');"
        s += "f.write(str(os.getpid()));"
        s += "f.close();"
        s += "time.sleep(60);"
        subprocess.Popen(['%s', '-c', s])
        time.sleep(60)
        """ % (_TESTFN2, PYTHON_EXE))
    # On Windows if we create a subprocess with CREATE_NO_WINDOW flag
    # set (which is the default) a "conhost.exe" extra process will be
    # spawned as a child. We don't want that.
    if WINDOWS:
        subp = pyrun(s, creationflags=0)
    else:
        subp = pyrun(s)
    child1 = psutil.Process(subp.pid)
    data = wait_for_file(_TESTFN2, delete=False, empty=False)
    os.remove(_TESTFN2)
    child2_pid = int(data)
    _pids_started.add(child2_pid)
    child2 = psutil.Process(child2_pid)
    return (child1, child2)


def create_zombie_proc():
    """Create a zombie process and return its PID."""
    assert psutil.POSIX
    unix_file = tempfile.mktemp(prefix=TESTFILE_PREFIX) if OSX else TESTFN
    src = textwrap.dedent("""\
        import os, sys, time, socket, contextlib
        child_pid = os.fork()
        if child_pid > 0:
            time.sleep(3000)
        else:
            # this is the zombie process
            s = socket.socket(socket.AF_UNIX)
            with contextlib.closing(s):
                s.connect('%s')
                if sys.version_info < (3, ):
                    pid = str(os.getpid())
                else:
                    pid = bytes(str(os.getpid()), 'ascii')
                s.sendall(pid)
        """ % unix_file)
    with contextlib.closing(socket.socket(socket.AF_UNIX)) as sock:
        sock.settimeout(GLOBAL_TIMEOUT)
        sock.bind(unix_file)
        sock.listen(1)
        pyrun(src)
        conn, _ = sock.accept()
        try:
            select.select([conn.fileno()], [], [], GLOBAL_TIMEOUT)
            zpid = int(conn.recv(1024))
            _pids_started.add(zpid)
            zproc = psutil.Process(zpid)
            call_until(lambda: zproc.status(), "ret == psutil.STATUS_ZOMBIE")
            return zpid
        finally:
            conn.close()


@_cleanup_on_err
def pyrun(src, **kwds):
    """Run python 'src' code string in a separate interpreter.
    Returns a subprocess.Popen instance.
    """
    kwds.setdefault("stdout", None)
    kwds.setdefault("stderr", None)
    with tempfile.NamedTemporaryFile(
            prefix=TESTFILE_PREFIX, mode="wt", delete=False) as f:
        _testfiles_created.add(f.name)
        f.write(src)
        f.flush()
        subp = get_test_subprocess([PYTHON_EXE, f.name], **kwds)
        wait_for_pid(subp.pid)
    return subp


@_cleanup_on_err
def sh(cmd, **kwds):
    """run cmd in a subprocess and return its output.
    raises RuntimeError on error.
    """
    shell = True if isinstance(cmd, (str, unicode)) else False
    # Prevents subprocess to open error dialogs in case of error.
    flags = 0x8000000 if WINDOWS and shell else 0
    kwds.setdefault("shell", shell)
    kwds.setdefault("stdout", subprocess.PIPE)
    kwds.setdefault("stderr", subprocess.PIPE)
    kwds.setdefault("universal_newlines", True)
    kwds.setdefault("creationflags", flags)
    p = subprocess.Popen(cmd, **kwds)
    _subprocesses_started.add(p)
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise RuntimeError(stderr)
    if stderr:
        warn(stderr)
    if stdout.endswith('\n'):
        stdout = stdout[:-1]
    return stdout


def reap_children(recursive=False):
    """Terminate and wait() any subprocess started by this test suite
    and ensure that no zombies stick around to hog resources and
    create problems  when looking for refleaks.

    If resursive is True it also tries to terminate and wait()
    all grandchildren started by this process.
    """
    # This is here to make sure wait_procs() behaves properly and
    # investigate:
    # https://ci.appveyor.com/project/giampaolo/psutil/build/job/
    #     jiq2cgd6stsbtn60
    def assert_gone(pid):
        assert not psutil.pid_exists(pid), pid
        assert pid not in psutil.pids(), pid
        try:
            p = psutil.Process(pid)
            assert not p.is_running(), pid
        except psutil.NoSuchProcess:
            pass
        else:
            assert 0, "pid %s is not gone" % pid

    # Get the children here, before terminating the children sub
    # processes as we don't want to lose the intermediate reference
    # in case of grandchildren.
    if recursive:
        children = set(psutil.Process().children(recursive=True))
    else:
        children = set()

    # Terminate subprocess.Popen instances "cleanly" by closing their
    # fds and wiat()ing for them in order to avoid zombies.
    while _subprocesses_started:
        subp = _subprocesses_started.pop()
        _pids_started.add(subp.pid)
        try:
            subp.terminate()
        except OSError as err:
            if err.errno != errno.ESRCH:
                raise
        if subp.stdout:
            subp.stdout.close()
        if subp.stderr:
            subp.stderr.close()
        try:
            # Flushing a BufferedWriter may raise an error.
            if subp.stdin:
                subp.stdin.close()
        finally:
            # Wait for the process to terminate, to avoid zombies.
            try:
                subp.wait()
            except OSError as err:
                if err.errno != errno.ECHILD:
                    raise

    # Terminate started pids.
    while _pids_started:
        pid = _pids_started.pop()
        try:
            p = psutil.Process(pid)
        except psutil.NoSuchProcess:
            assert_gone(pid)
        else:
            children.add(p)

    # Terminate children.
    if children:
        for p in children:
            try:
                p.terminate()
            except psutil.NoSuchProcess:
                pass
        gone, alive = psutil.wait_procs(children, timeout=GLOBAL_TIMEOUT)
        for p in alive:
            warn("couldn't terminate process %r; attempting kill()" % p)
            try:
                p.kill()
            except psutil.NoSuchProcess:
                pass
        gone, alive = psutil.wait_procs(alive, timeout=GLOBAL_TIMEOUT)
        if alive:
            for p in alive:
                warn("process %r survived kill()" % p)

        for p in children:
            assert_gone(p.pid)


# ===================================================================
# --- OS
# ===================================================================


def get_kernel_version():
    """Return a tuple such as (2, 6, 36)."""
    if not POSIX:
        raise NotImplementedError("not POSIX")
    s = ""
    uname = os.uname()[2]
    for c in uname:
        if c.isdigit() or c == '.':
            s += c
        else:
            break
    if not s:
        raise ValueError("can't parse %r" % uname)
    minor = 0
    micro = 0
    nums = s.split('.')
    major = int(nums[0])
    if len(nums) >= 2:
        minor = int(nums[1])
    if len(nums) >= 3:
        micro = int(nums[2])
    return (major, minor, micro)


def get_winver():
    if not WINDOWS:
        raise NotImplementedError("not WINDOWS")
    wv = sys.getwindowsversion()
    if hasattr(wv, 'service_pack_major'):  # python >= 2.7
        sp = wv.service_pack_major or 0
    else:
        r = re.search(r"\s\d$", wv[4])
        if r:
            sp = int(r.group(0))
        else:
            sp = 0
    return (wv[0], wv[1], sp)


# ===================================================================
# --- sync primitives
# ===================================================================


class retry(object):
    """A retry decorator."""

    def __init__(self,
                 exception=Exception,
                 timeout=None,
                 retries=None,
                 interval=0.001,
                 logfun=lambda s: print(s, file=sys.stderr),
                 ):
        if timeout and retries:
            raise ValueError("timeout and retries args are mutually exclusive")
        self.exception = exception
        self.timeout = timeout
        self.retries = retries
        self.interval = interval
        self.logfun = logfun

    def __iter__(self):
        if self.timeout:
            stop_at = time.time() + self.timeout
            while time.time() < stop_at:
                yield
        elif self.retries:
            for _ in range(self.retries):
                yield
        else:
            while True:
                yield

    def sleep(self):
        if self.interval is not None:
            time.sleep(self.interval)

    def __call__(self, fun):
        @functools.wraps(fun)
        def wrapper(*args, **kwargs):
            exc = None
            for _ in self:
                try:
                    return fun(*args, **kwargs)
                except self.exception as _:
                    exc = _
                    if self.logfun is not None:
                        self.logfun(exc)
                    self.sleep()
                    continue
            if PY3:
                raise exc
            else:
                raise

        # This way the user of the decorated function can change config
        # parameters.
        wrapper.decorator = self
        return wrapper


@retry(exception=psutil.NoSuchProcess, logfun=None, timeout=GLOBAL_TIMEOUT,
       interval=0.001)
def wait_for_pid(pid):
    """Wait for pid to show up in the process list then return.
    Used in the test suite to give time the sub process to initialize.
    """
    psutil.Process(pid)
    if WINDOWS:
        # give it some more time to allow better initialization
        time.sleep(0.01)


@retry(exception=(EnvironmentError, AssertionError), logfun=None,
       timeout=GLOBAL_TIMEOUT, interval=0.001)
def wait_for_file(fname, delete=True, empty=False):
    """Wait for a file to be written on disk with some content."""
    with open(fname, "rb") as f:
        data = f.read()
    if not empty:
        assert data
    if delete:
        os.remove(fname)
    return data


@retry(exception=AssertionError, logfun=None, timeout=GLOBAL_TIMEOUT,
       interval=0.001)
def call_until(fun, expr):
    """Keep calling function for timeout secs and exit if eval()
    expression is True.
    """
    ret = fun()
    assert eval(expr)
    return ret


# ===================================================================
# --- fs
# ===================================================================


def safe_rmpath(path):
    "Convenience function for removing temporary test files or dirs"
    try:
        st = os.stat(path)
        if stat.S_ISDIR(st.st_mode):
            os.rmdir(path)
        else:
            os.remove(path)
    except OSError as err:
        if err.errno != errno.ENOENT:
            raise


def safe_mkdir(dir):
    "Convenience function for creating a directory"
    try:
        os.mkdir(dir)
    except OSError as err:
        if err.errno != errno.EEXIST:
            raise


@contextlib.contextmanager
def chdir(dirname):
    "Context manager which temporarily changes the current directory."
    curdir = os.getcwd()
    try:
        os.chdir(dirname)
        yield
    finally:
        os.chdir(curdir)


def create_exe(outpath, c_code=None):
    """Creates an executable file in the given location."""
    assert not os.path.exists(outpath), outpath
    if c_code:
        if not which("gcc"):
            raise ValueError("gcc is not installed")
        if isinstance(c_code, bool):        # c_code is True
            c_code = textwrap.dedent(
                """
                #include <unistd.h>
                int main() {
                    pause();
                    return 1;
                }
                """)
        assert isinstance(c_code, str), c_code
        with tempfile.NamedTemporaryFile(
                suffix='.c', delete=False, mode='wt') as f:
            f.write(c_code)
        try:
            subprocess.check_call(["gcc", f.name, "-o", outpath])
        finally:
            safe_rmpath(f.name)
    else:
        # copy python executable
        shutil.copyfile(PYTHON_EXE, outpath)
        if POSIX:
            st = os.stat(outpath)
            os.chmod(outpath, st.st_mode | stat.S_IEXEC)


def unique_filename(prefix=TESTFILE_PREFIX, suffix=""):
    return tempfile.mktemp(prefix=prefix, suffix=suffix)


# ===================================================================
# --- testing
# ===================================================================


class TestCase(unittest.TestCase):

    # Print a full path representation of the single unit tests
    # being run.
    def __str__(self):
        return "%s.%s.%s" % (
            self.__class__.__module__, self.__class__.__name__,
            self._testMethodName)

    # assertRaisesRegexp renamed to assertRaisesRegex in 3.3;
    # add support for the new name.
    if not hasattr(unittest.TestCase, 'assertRaisesRegex'):
        assertRaisesRegex = unittest.TestCase.assertRaisesRegexp


# override default unittest.TestCase
unittest.TestCase = TestCase


def _setup_tests():
    if 'PSUTIL_TESTING' not in os.environ:
        # This won't work on Windows but set_testing() below will do it.
        os.environ['PSUTIL_TESTING'] = '1'
    psutil._psplatform.cext.set_testing()


def get_suite():
    testmods = [os.path.splitext(x)[0] for x in os.listdir(HERE)
                if x.endswith('.py') and x.startswith('test_') and not
                x.startswith('test_memory_leaks')]
    if "WHEELHOUSE_UPLOADER_USERNAME" in os.environ:
        testmods = [x for x in testmods if not x.endswith((
                    "osx", "posix", "linux"))]
    suite = unittest.TestSuite()
    for tm in testmods:
        # ...so that the full test paths are printed on screen
        tm = "psutil.tests.%s" % tm
        suite.addTest(unittest.defaultTestLoader.loadTestsFromName(tm))
    return suite


def run_suite():
    _setup_tests()
    result = unittest.TextTestRunner(verbosity=VERBOSITY).run(get_suite())
    success = result.wasSuccessful()
    sys.exit(0 if success else 1)


def run_test_module_by_name(name):
    # testmodules = [os.path.splitext(x)[0] for x in os.listdir(HERE)
    #                if x.endswith('.py') and x.startswith('test_')]
    _setup_tests()
    name = os.path.splitext(os.path.basename(name))[0]
    suite = unittest.TestSuite()
    suite.addTest(unittest.defaultTestLoader.loadTestsFromName(name))
    result = unittest.TextTestRunner(verbosity=VERBOSITY).run(suite)
    success = result.wasSuccessful()
    sys.exit(0 if success else 1)


def retry_before_failing(retries=NO_RETRIES):
    """Decorator which runs a test function and retries N times before
    actually failing.
    """
    return retry(exception=AssertionError, timeout=None, retries=retries)


def skip_on_access_denied(only_if=None):
    """Decorator to Ignore AccessDenied exceptions."""
    def decorator(fun):
        @functools.wraps(fun)
        def wrapper(*args, **kwargs):
            try:
                return fun(*args, **kwargs)
            except psutil.AccessDenied:
                if only_if is not None:
                    if not only_if:
                        raise
                raise unittest.SkipTest("raises AccessDenied")
        return wrapper
    return decorator


def skip_on_not_implemented(only_if=None):
    """Decorator to Ignore NotImplementedError exceptions."""
    def decorator(fun):
        @functools.wraps(fun)
        def wrapper(*args, **kwargs):
            try:
                return fun(*args, **kwargs)
            except NotImplementedError:
                if only_if is not None:
                    if not only_if:
                        raise
                msg = "%r was skipped because it raised NotImplementedError" \
                      % fun.__name__
                raise unittest.SkipTest(msg)
        return wrapper
    return decorator


# ===================================================================
# --- network
# ===================================================================


def get_free_port(host='127.0.0.1'):
    """Return an unused TCP port."""
    with contextlib.closing(socket.socket()) as sock:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((host, 0))
        return sock.getsockname()[1]


@contextlib.contextmanager
def unix_socket_path(suffix=""):
    """A context manager which returns a non-existent file name
    and tries to delete it on exit.
    """
    assert psutil.POSIX
    path = unique_filename(suffix=suffix)
    try:
        yield path
    finally:
        try:
            os.unlink(path)
        except OSError:
            pass


def bind_socket(family=AF_INET, type=SOCK_STREAM, addr=None):
    """Binds a generic socket."""
    if addr is None and family in (AF_INET, AF_INET6):
        addr = ("", 0)
    sock = socket.socket(family, type)
    try:
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(addr)
        if type == socket.SOCK_STREAM:
            sock.listen(10)
        return sock
    except Exception:
        sock.close()
        raise


def bind_unix_socket(name, type=socket.SOCK_STREAM):
    """Bind a UNIX socket."""
    assert psutil.POSIX
    assert not os.path.exists(name), name
    sock = socket.socket(socket.AF_UNIX, type)
    try:
        sock.bind(name)
        if type == socket.SOCK_STREAM:
            sock.listen(10)
    except Exception:
        sock.close()
        raise
    return sock


def tcp_socketpair(family, addr=("", 0)):
    """Build a pair of TCP sockets connected to each other.
    Return a (server, client) tuple.
    """
    with contextlib.closing(socket.socket(family, SOCK_STREAM)) as ll:
        ll.bind(addr)
        ll.listen(10)
        addr = ll.getsockname()
        c = socket.socket(family, SOCK_STREAM)
        try:
            c.connect(addr)
            caddr = c.getsockname()
            while True:
                a, addr = ll.accept()
                # check that we've got the correct client
                if addr == caddr:
                    return (a, c)
                a.close()
        except OSError:
            c.close()
            raise


def unix_socketpair(name):
    """Build a pair of UNIX sockets connected to each other through
    the same UNIX file name.
    Return a (server, client) tuple.
    """
    assert psutil.POSIX
    server = client = None
    try:
        server = bind_unix_socket(name, type=socket.SOCK_STREAM)
        server.setblocking(0)
        client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        client.setblocking(0)
        client.connect(name)
        # new = server.accept()
    except Exception:
        if server is not None:
            server.close()
        if client is not None:
            client.close()
        raise
    return (server, client)


@contextlib.contextmanager
def create_sockets():
    """Open as many socket families / types as possible."""
    socks = []
    fname1 = fname2 = None
    try:
        socks.append(bind_socket(socket.AF_INET, socket.SOCK_STREAM))
        socks.append(bind_socket(socket.AF_INET, socket.SOCK_DGRAM))
        if supports_ipv6():
            socks.append(bind_socket(socket.AF_INET6, socket.SOCK_STREAM))
            socks.append(bind_socket(socket.AF_INET6, socket.SOCK_DGRAM))
        if POSIX and HAS_CONNECTIONS_UNIX:
            fname1 = unix_socket_path().__enter__()
            fname2 = unix_socket_path().__enter__()
            s1, s2 = unix_socketpair(fname1)
            s3 = bind_unix_socket(fname2, type=socket.SOCK_DGRAM)
            # self.addCleanup(safe_rmpath, fname1)
            # self.addCleanup(safe_rmpath, fname2)
            for s in (s1, s2, s3):
                socks.append(s)
        yield socks
    finally:
        for s in socks:
            s.close()
        if fname1 is not None:
            safe_rmpath(fname1)
        if fname2 is not None:
            safe_rmpath(fname2)


def check_net_address(addr, family):
    """Check a net address validity. Supported families are IPv4,
    IPv6 and MAC addresses.
    """
    import ipaddress  # python >= 3.3 / requires "pip install ipaddress"
    if enum and PY3:
        assert isinstance(family, enum.IntEnum), family
    if family == socket.AF_INET:
        octs = [int(x) for x in addr.split('.')]
        assert len(octs) == 4, addr
        for num in octs:
            assert 0 <= num <= 255, addr
        if not PY3:
            addr = unicode(addr)
        ipaddress.IPv4Address(addr)
    elif family == socket.AF_INET6:
        assert isinstance(addr, str), addr
        if not PY3:
            addr = unicode(addr)
        ipaddress.IPv6Address(addr)
    elif family == psutil.AF_LINK:
        assert re.match(r'([a-fA-F0-9]{2}[:|\-]?){6}', addr) is not None, addr
    else:
        raise ValueError("unknown family %r", family)


def check_connection_ntuple(conn):
    """Check validity of a connection namedtuple."""
    # check ntuple
    assert len(conn) in (6, 7), conn
    has_pid = len(conn) == 7
    has_fd = getattr(conn, 'fd', -1) != -1
    assert conn[0] == conn.fd
    assert conn[1] == conn.family
    assert conn[2] == conn.type
    assert conn[3] == conn.laddr
    assert conn[4] == conn.raddr
    assert conn[5] == conn.status
    if has_pid:
        assert conn[6] == conn.pid

    # check fd
    if has_fd:
        assert conn.fd >= 0, conn
        if hasattr(socket, 'fromfd') and not WINDOWS:
            try:
                dupsock = socket.fromfd(conn.fd, conn.family, conn.type)
            except (socket.error, OSError) as err:
                if err.args[0] != errno.EBADF:
                    raise
            else:
                with contextlib.closing(dupsock):
                    assert dupsock.family == conn.family
                    assert dupsock.type == conn.type

    # check family
    assert conn.family in (AF_INET, AF_INET6, AF_UNIX), repr(conn.family)
    if conn.family in (AF_INET, AF_INET6):
        # actually try to bind the local socket; ignore IPv6
        # sockets as their address might be represented as
        # an IPv4-mapped-address (e.g. "::127.0.0.1")
        # and that's rejected by bind()
        if conn.family == AF_INET:
            s = socket.socket(conn.family, conn.type)
            with contextlib.closing(s):
                try:
                    s.bind((conn.laddr[0], 0))
                except socket.error as err:
                    if err.errno != errno.EADDRNOTAVAIL:
                        raise
    elif conn.family == AF_UNIX:
        assert conn.status == psutil.CONN_NONE, conn.status

    # check type (SOCK_SEQPACKET may happen in case of AF_UNIX socks)
    assert conn.type in (SOCK_STREAM, SOCK_DGRAM, SOCK_SEQPACKET), \
        repr(conn.type)
    if conn.type == SOCK_DGRAM:
        assert conn.status == psutil.CONN_NONE, conn.status

    # check laddr (IP address and port sanity)
    for addr in (conn.laddr, conn.raddr):
        if conn.family in (AF_INET, AF_INET6):
            assert isinstance(addr, tuple), addr
            if not addr:
                continue
            assert isinstance(addr.port, int), addr.port
            assert 0 <= addr.port <= 65535, addr.port
            check_net_address(addr.ip, conn.family)
        elif conn.family == AF_UNIX:
            assert isinstance(addr, str), addr

    # check status
    assert isinstance(conn.status, str), conn
    valids = [getattr(psutil, x) for x in dir(psutil) if x.startswith('CONN_')]
    assert conn.status in valids, conn


# ===================================================================
# --- compatibility
# ===================================================================


def reload_module(module):
    """Backport of importlib.reload of Python 3.3+."""
    try:
        import importlib
        if not hasattr(importlib, 'reload'):  # python <=3.3
            raise ImportError
    except ImportError:
        import imp
        return imp.reload(module)
    else:
        return importlib.reload(module)


def import_module_by_path(path):
    name = os.path.splitext(os.path.basename(path))[0]
    if sys.version_info[0] == 2:
        import imp
        return imp.load_source(name, path)
    elif sys.version_info[:2] <= (3, 4):
        from importlib.machinery import SourceFileLoader
        return SourceFileLoader(name, path).load_module()
    else:
        import importlib.util
        spec = importlib.util.spec_from_file_location(name, path)
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
        return mod


# ===================================================================
# --- others
# ===================================================================


def warn(msg):
    """Raise a warning msg."""
    warnings.warn(msg, UserWarning)


def is_namedtuple(x):
    """Check if object is an instance of namedtuple."""
    t = type(x)
    b = t.__bases__
    if len(b) != 1 or b[0] != tuple:
        return False
    f = getattr(t, '_fields', None)
    if not isinstance(f, tuple):
        return False
    return all(type(n) == str for n in f)


if POSIX:
    @contextlib.contextmanager
    def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
        """Ctx manager which picks up a random shared CO lib used
        by this process, copies it in another location and loads it
        in memory via ctypes. Return the new absolutized path.
        """
        ext = ".so"
        dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
        libs = [x.path for x in psutil.Process().memory_maps() if
                os.path.splitext(x.path)[1] == ext and
                'python' in x.path.lower()]
        src = random.choice(libs)
        shutil.copyfile(src, dst)
        try:
            ctypes.CDLL(dst)
            yield dst
        finally:
            safe_rmpath(dst)
else:
    @contextlib.contextmanager
    def copyload_shared_lib(dst_prefix=TESTFILE_PREFIX):
        """Ctx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        """
        from ctypes import wintypes
        from ctypes import WinError
        ext = ".dll"
        dst = tempfile.mktemp(prefix=dst_prefix, suffix=ext)
        libs = [x.path for x in psutil.Process().memory_maps() if
                os.path.splitext(x.path)[1].lower() == ext and
                'python' in os.path.basename(x.path).lower() and
                'wow64' not in x.path.lower()]
        src = random.choice(libs)
        shutil.copyfile(src, dst)
        cfile = None
        try:
            cfile = ctypes.WinDLL(dst)
            yield dst
        finally:
            # Work around OverflowError:
            # - https://ci.appveyor.com/project/giampaolo/psutil/build/1207/
            #       job/o53330pbnri9bcw7
            # - http://bugs.python.org/issue30286
            # - http://stackoverflow.com/questions/23522055
            if cfile is not None:
                FreeLibrary = ctypes.windll.kernel32.FreeLibrary
                FreeLibrary.argtypes = [wintypes.HMODULE]
                ret = FreeLibrary(cfile._handle)
                if ret == 0:
                    WinError()
            safe_rmpath(dst)
tests/test_windows.py000064400000077513150466730540011040 0ustar00# -*- coding: UTF-8 -*

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Windows specific tests."""

import datetime
import errno
import glob
import os
import platform
import re
import signal
import subprocess
import sys
import time
import warnings

import psutil
from psutil import WINDOWS
from psutil._compat import callable
from psutil.tests import APPVEYOR
from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import mock
from psutil.tests import reap_children
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import sh
from psutil.tests import unittest

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    try:
        import win32api  # requires "pip install pypiwin32"
        import win32con
        import win32process
        import wmi  # requires "pip install wmi" / "make setup-dev-env"
    except ImportError:
        if os.name == 'nt':
            raise


cext = psutil._psplatform.cext

# are we a 64 bit process
IS_64_BIT = sys.maxsize > 2**32


def wrap_exceptions(fun):
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            from psutil._pswindows import ACCESS_DENIED_SET
            if err.errno in ACCESS_DENIED_SET:
                raise psutil.AccessDenied(None, None)
            if err.errno == errno.ESRCH:
                raise psutil.NoSuchProcess(None, None)
            raise
    return wrapper


# ===================================================================
# System APIs
# ===================================================================


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class TestSystemAPIs(unittest.TestCase):

    def test_nic_names(self):
        out = sh('ipconfig /all')
        nics = psutil.net_io_counters(pernic=True).keys()
        for nic in nics:
            if "pseudo-interface" in nic.replace(' ', '-').lower():
                continue
            if nic not in out:
                self.fail(
                    "%r nic wasn't found in 'ipconfig /all' output" % nic)

    @unittest.skipIf('NUMBER_OF_PROCESSORS' not in os.environ,
                     'NUMBER_OF_PROCESSORS env var is not available')
    def test_cpu_count(self):
        num_cpus = int(os.environ['NUMBER_OF_PROCESSORS'])
        self.assertEqual(num_cpus, psutil.cpu_count())

    def test_cpu_count_2(self):
        sys_value = win32api.GetSystemInfo()[5]
        psutil_value = psutil.cpu_count()
        self.assertEqual(sys_value, psutil_value)

    def test_cpu_freq(self):
        w = wmi.WMI()
        proc = w.Win32_Processor()[0]
        self.assertEqual(proc.CurrentClockSpeed, psutil.cpu_freq().current)
        self.assertEqual(proc.MaxClockSpeed, psutil.cpu_freq().max)

    def test_total_phymem(self):
        w = wmi.WMI().Win32_ComputerSystem()[0]
        self.assertEqual(int(w.TotalPhysicalMemory),
                         psutil.virtual_memory().total)

    # @unittest.skipIf(wmi is None, "wmi module is not installed")
    # def test__UPTIME(self):
    #     # _UPTIME constant is not public but it is used internally
    #     # as value to return for pid 0 creation time.
    #     # WMI behaves the same.
    #     w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
    #     p = psutil.Process(0)
    #     wmic_create = str(w.CreationDate.split('.')[0])
    #     psutil_create = time.strftime("%Y%m%d%H%M%S",
    #                                   time.localtime(p.create_time()))

    # Note: this test is not very reliable
    @unittest.skipIf(APPVEYOR, "test not relieable on appveyor")
    @retry_before_failing()
    def test_pids(self):
        # Note: this test might fail if the OS is starting/killing
        # other processes in the meantime
        w = wmi.WMI().Win32_Process()
        wmi_pids = set([x.ProcessId for x in w])
        psutil_pids = set(psutil.pids())
        self.assertEqual(wmi_pids, psutil_pids)

    @retry_before_failing()
    def test_disks(self):
        ps_parts = psutil.disk_partitions(all=True)
        wmi_parts = wmi.WMI().Win32_LogicalDisk()
        for ps_part in ps_parts:
            for wmi_part in wmi_parts:
                if ps_part.device.replace('\\', '') == wmi_part.DeviceID:
                    if not ps_part.mountpoint:
                        # this is usually a CD-ROM with no disk inserted
                        break
                    try:
                        usage = psutil.disk_usage(ps_part.mountpoint)
                    except OSError as err:
                        if err.errno == errno.ENOENT:
                            # usually this is the floppy
                            break
                        else:
                            raise
                    self.assertEqual(usage.total, int(wmi_part.Size))
                    wmi_free = int(wmi_part.FreeSpace)
                    self.assertEqual(usage.free, wmi_free)
                    # 10 MB tollerance
                    if abs(usage.free - wmi_free) > 10 * 1024 * 1024:
                        self.fail("psutil=%s, wmi=%s" % (
                            usage.free, wmi_free))
                    break
            else:
                self.fail("can't find partition %s" % repr(ps_part))

    def test_disk_usage(self):
        for disk in psutil.disk_partitions():
            sys_value = win32api.GetDiskFreeSpaceEx(disk.mountpoint)
            psutil_value = psutil.disk_usage(disk.mountpoint)
            self.assertAlmostEqual(sys_value[0], psutil_value.free,
                                   delta=1024 * 1024)
            self.assertAlmostEqual(sys_value[1], psutil_value.total,
                                   delta=1024 * 1024)
            self.assertEqual(psutil_value.used,
                             psutil_value.total - psutil_value.free)

    def test_disk_partitions(self):
        sys_value = [
            x + '\\' for x in win32api.GetLogicalDriveStrings().split("\\\x00")
            if x and not x.startswith('A:')]
        psutil_value = [x.mountpoint for x in psutil.disk_partitions(all=True)]
        self.assertEqual(sys_value, psutil_value)

    def test_net_if_stats(self):
        ps_names = set(cext.net_if_stats())
        wmi_adapters = wmi.WMI().Win32_NetworkAdapter()
        wmi_names = set()
        for wmi_adapter in wmi_adapters:
            wmi_names.add(wmi_adapter.Name)
            wmi_names.add(wmi_adapter.NetConnectionID)
        self.assertTrue(ps_names & wmi_names,
                        "no common entries in %s, %s" % (ps_names, wmi_names))

    def test_boot_time(self):
        wmi_os = wmi.WMI().Win32_OperatingSystem()
        wmi_btime_str = wmi_os[0].LastBootUpTime.split('.')[0]
        wmi_btime_dt = datetime.datetime.strptime(
            wmi_btime_str, "%Y%m%d%H%M%S")
        psutil_dt = datetime.datetime.fromtimestamp(psutil.boot_time())
        diff = abs((wmi_btime_dt - psutil_dt).total_seconds())
        # Wmic time is 2-3 secs lower for some reason; that's OK.
        self.assertLessEqual(diff, 3)

    def test_boot_time_fluctuation(self):
        # https://github.com/giampaolo/psutil/issues/1007
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=5):
            self.assertEqual(psutil.boot_time(), 5)
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=4):
            self.assertEqual(psutil.boot_time(), 5)
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=6):
            self.assertEqual(psutil.boot_time(), 5)
        with mock.patch('psutil._pswindows.cext.boot_time', return_value=333):
            self.assertEqual(psutil.boot_time(), 333)


# ===================================================================
# sensors_battery()
# ===================================================================


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class TestSensorsBattery(unittest.TestCase):

    def test_has_battery(self):
        if win32api.GetPwrCapabilities()['SystemBatteriesPresent']:
            self.assertIsNotNone(psutil.sensors_battery())
        else:
            self.assertIsNone(psutil.sensors_battery())

    @unittest.skipIf(not HAS_BATTERY, "no battery")
    def test_percent(self):
        w = wmi.WMI()
        battery_wmi = w.query('select * from Win32_Battery')[0]
        battery_psutil = psutil.sensors_battery()
        self.assertAlmostEqual(
            battery_psutil.percent, battery_wmi.EstimatedChargeRemaining,
            delta=1)

    @unittest.skipIf(not HAS_BATTERY, "no battery")
    def test_power_plugged(self):
        w = wmi.WMI()
        battery_wmi = w.query('select * from Win32_Battery')[0]
        battery_psutil = psutil.sensors_battery()
        # Status codes:
        # https://msdn.microsoft.com/en-us/library/aa394074(v=vs.85).aspx
        self.assertEqual(battery_psutil.power_plugged,
                         battery_wmi.BatteryStatus == 2)

    def test_emulate_no_battery(self):
        with mock.patch("psutil._pswindows.cext.sensors_battery",
                        return_value=(0, 128, 0, 0)) as m:
            self.assertIsNone(psutil.sensors_battery())
            assert m.called

    def test_emulate_power_connected(self):
        with mock.patch("psutil._pswindows.cext.sensors_battery",
                        return_value=(1, 0, 0, 0)) as m:
            self.assertEqual(psutil.sensors_battery().secsleft,
                             psutil.POWER_TIME_UNLIMITED)
            assert m.called

    def test_emulate_power_charging(self):
        with mock.patch("psutil._pswindows.cext.sensors_battery",
                        return_value=(0, 8, 0, 0)) as m:
            self.assertEqual(psutil.sensors_battery().secsleft,
                             psutil.POWER_TIME_UNLIMITED)
            assert m.called

    def test_emulate_secs_left_unknown(self):
        with mock.patch("psutil._pswindows.cext.sensors_battery",
                        return_value=(0, 0, 0, -1)) as m:
            self.assertEqual(psutil.sensors_battery().secsleft,
                             psutil.POWER_TIME_UNKNOWN)
            assert m.called


# ===================================================================
# Process APIs
# ===================================================================


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class TestProcess(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.pid = get_test_subprocess().pid

    @classmethod
    def tearDownClass(cls):
        reap_children()

    def test_issue_24(self):
        p = psutil.Process(0)
        self.assertRaises(psutil.AccessDenied, p.kill)

    def test_special_pid(self):
        p = psutil.Process(4)
        self.assertEqual(p.name(), 'System')
        # use __str__ to access all common Process properties to check
        # that nothing strange happens
        str(p)
        p.username()
        self.assertTrue(p.create_time() >= 0.0)
        try:
            rss, vms = p.memory_info()[:2]
        except psutil.AccessDenied:
            # expected on Windows Vista and Windows 7
            if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
                raise
        else:
            self.assertTrue(rss > 0)

    def test_send_signal(self):
        p = psutil.Process(self.pid)
        self.assertRaises(ValueError, p.send_signal, signal.SIGINT)

    def test_exe(self):
        for p in psutil.process_iter():
            try:
                self.assertEqual(os.path.basename(p.exe()), p.name())
            except psutil.Error:
                pass

    def test_num_handles_increment(self):
        p = psutil.Process(os.getpid())
        before = p.num_handles()
        handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      win32con.FALSE, os.getpid())
        after = p.num_handles()
        self.assertEqual(after, before + 1)
        win32api.CloseHandle(handle)
        self.assertEqual(p.num_handles(), before)

    def test_handles_leak(self):
        # Call all Process methods and make sure no handles are left
        # open. This is here mainly to make sure functions using
        # OpenProcess() always call CloseHandle().
        def call(p, attr):
            attr = getattr(p, name, None)
            if attr is not None and callable(attr):
                attr()
            else:
                attr

        p = psutil.Process(self.pid)
        failures = []
        for name in dir(psutil.Process):
            if name.startswith('_') \
                    or name in ('terminate', 'kill', 'suspend', 'resume',
                                'nice', 'send_signal', 'wait', 'children',
                                'as_dict', 'memory_info_ex'):
                continue
            else:
                try:
                    call(p, name)
                    num1 = p.num_handles()
                    call(p, name)
                    num2 = p.num_handles()
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    pass
                else:
                    if num2 > num1:
                        fail = \
                            "failure while processing Process.%s method " \
                            "(before=%s, after=%s)" % (name, num1, num2)
                        failures.append(fail)
        if failures:
            self.fail('\n' + '\n'.join(failures))

    def test_name_always_available(self):
        # On Windows name() is never supposed to raise AccessDenied,
        # see https://github.com/giampaolo/psutil/issues/627
        for p in psutil.process_iter():
            try:
                p.name()
            except psutil.NoSuchProcess:
                pass

    @unittest.skipIf(not sys.version_info >= (2, 7),
                     "CTRL_* signals not supported")
    def test_ctrl_signals(self):
        p = psutil.Process(get_test_subprocess().pid)
        p.send_signal(signal.CTRL_C_EVENT)
        p.send_signal(signal.CTRL_BREAK_EVENT)
        p.kill()
        p.wait()
        self.assertRaises(psutil.NoSuchProcess,
                          p.send_signal, signal.CTRL_C_EVENT)
        self.assertRaises(psutil.NoSuchProcess,
                          p.send_signal, signal.CTRL_BREAK_EVENT)

    def test_compare_name_exe(self):
        for p in psutil.process_iter():
            try:
                a = os.path.basename(p.exe())
                b = p.name()
            except (psutil.NoSuchProcess, psutil.AccessDenied):
                pass
            else:
                self.assertEqual(a, b)

    def test_username(self):
        self.assertEqual(psutil.Process().username(),
                         win32api.GetUserNameEx(win32con.NameSamCompatible))

    def test_cmdline(self):
        sys_value = re.sub(' +', ' ', win32api.GetCommandLine()).strip()
        psutil_value = ' '.join(psutil.Process().cmdline())
        self.assertEqual(sys_value, psutil_value)

    # XXX - occasional failures

    # def test_cpu_times(self):
    #     handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
    #                                   win32con.FALSE, os.getpid())
    #     self.addCleanup(win32api.CloseHandle, handle)
    #     sys_value = win32process.GetProcessTimes(handle)
    #     psutil_value = psutil.Process().cpu_times()
    #     self.assertAlmostEqual(
    #         psutil_value.user, sys_value['UserTime'] / 10000000.0,
    #         delta=0.2)
    #     self.assertAlmostEqual(
    #         psutil_value.user, sys_value['KernelTime'] / 10000000.0,
    #         delta=0.2)

    def test_nice(self):
        handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      win32con.FALSE, os.getpid())
        self.addCleanup(win32api.CloseHandle, handle)
        sys_value = win32process.GetPriorityClass(handle)
        psutil_value = psutil.Process().nice()
        self.assertEqual(psutil_value, sys_value)

    def test_memory_info(self):
        handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      win32con.FALSE, self.pid)
        self.addCleanup(win32api.CloseHandle, handle)
        sys_value = win32process.GetProcessMemoryInfo(handle)
        psutil_value = psutil.Process(self.pid).memory_info()
        self.assertEqual(
            sys_value['PeakWorkingSetSize'], psutil_value.peak_wset)
        self.assertEqual(
            sys_value['WorkingSetSize'], psutil_value.wset)
        self.assertEqual(
            sys_value['QuotaPeakPagedPoolUsage'], psutil_value.peak_paged_pool)
        self.assertEqual(
            sys_value['QuotaPagedPoolUsage'], psutil_value.paged_pool)
        self.assertEqual(
            sys_value['QuotaPeakNonPagedPoolUsage'],
            psutil_value.peak_nonpaged_pool)
        self.assertEqual(
            sys_value['QuotaNonPagedPoolUsage'], psutil_value.nonpaged_pool)
        self.assertEqual(
            sys_value['PagefileUsage'], psutil_value.pagefile)
        self.assertEqual(
            sys_value['PeakPagefileUsage'], psutil_value.peak_pagefile)

        self.assertEqual(psutil_value.rss, psutil_value.wset)
        self.assertEqual(psutil_value.vms, psutil_value.pagefile)

    def test_wait(self):
        handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      win32con.FALSE, self.pid)
        self.addCleanup(win32api.CloseHandle, handle)
        p = psutil.Process(self.pid)
        p.terminate()
        psutil_value = p.wait()
        sys_value = win32process.GetExitCodeProcess(handle)
        self.assertEqual(psutil_value, sys_value)

    def test_cpu_affinity(self):
        def from_bitmask(x):
            return [i for i in range(64) if (1 << i) & x]

        handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      win32con.FALSE, self.pid)
        self.addCleanup(win32api.CloseHandle, handle)
        sys_value = from_bitmask(
            win32process.GetProcessAffinityMask(handle)[0])
        psutil_value = psutil.Process(self.pid).cpu_affinity()
        self.assertEqual(psutil_value, sys_value)

    def test_io_counters(self):
        handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
                                      win32con.FALSE, os.getpid())
        self.addCleanup(win32api.CloseHandle, handle)
        sys_value = win32process.GetProcessIoCounters(handle)
        psutil_value = psutil.Process().io_counters()
        self.assertEqual(
            psutil_value.read_count, sys_value['ReadOperationCount'])
        self.assertEqual(
            psutil_value.write_count, sys_value['WriteOperationCount'])
        self.assertEqual(
            psutil_value.read_bytes, sys_value['ReadTransferCount'])
        self.assertEqual(
            psutil_value.write_bytes, sys_value['WriteTransferCount'])
        self.assertEqual(
            psutil_value.other_count, sys_value['OtherOperationCount'])
        self.assertEqual(
            psutil_value.other_bytes, sys_value['OtherTransferCount'])

    def test_num_handles(self):
        import ctypes
        import ctypes.wintypes
        PROCESS_QUERY_INFORMATION = 0x400
        handle = ctypes.windll.kernel32.OpenProcess(
            PROCESS_QUERY_INFORMATION, 0, os.getpid())
        self.addCleanup(ctypes.windll.kernel32.CloseHandle, handle)
        hndcnt = ctypes.wintypes.DWORD()
        ctypes.windll.kernel32.GetProcessHandleCount(
            handle, ctypes.byref(hndcnt))
        sys_value = hndcnt.value
        psutil_value = psutil.Process().num_handles()
        ctypes.windll.kernel32.CloseHandle(handle)
        self.assertEqual(psutil_value, sys_value + 1)


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class TestProcessWMI(unittest.TestCase):
    """Compare Process API results with WMI."""

    @classmethod
    def setUpClass(cls):
        cls.pid = get_test_subprocess().pid

    @classmethod
    def tearDownClass(cls):
        reap_children()

    def test_name(self):
        w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
        p = psutil.Process(self.pid)
        self.assertEqual(p.name(), w.Caption)

    def test_exe(self):
        w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
        p = psutil.Process(self.pid)
        # Note: wmi reports the exe as a lower case string.
        # Being Windows paths case-insensitive we ignore that.
        self.assertEqual(p.exe().lower(), w.ExecutablePath.lower())

    def test_cmdline(self):
        w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
        p = psutil.Process(self.pid)
        self.assertEqual(' '.join(p.cmdline()),
                         w.CommandLine.replace('"', ''))

    def test_username(self):
        w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
        p = psutil.Process(self.pid)
        domain, _, username = w.GetOwner()
        username = "%s\\%s" % (domain, username)
        self.assertEqual(p.username(), username)

    def test_memory_rss(self):
        time.sleep(0.1)
        w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
        p = psutil.Process(self.pid)
        rss = p.memory_info().rss
        self.assertEqual(rss, int(w.WorkingSetSize))

    def test_memory_vms(self):
        time.sleep(0.1)
        w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
        p = psutil.Process(self.pid)
        vms = p.memory_info().vms
        # http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx
        # ...claims that PageFileUsage is represented in Kilo
        # bytes but funnily enough on certain platforms bytes are
        # returned instead.
        wmi_usage = int(w.PageFileUsage)
        if (vms != wmi_usage) and (vms != wmi_usage * 1024):
            self.fail("wmi=%s, psutil=%s" % (wmi_usage, vms))

    def test_create_time(self):
        w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
        p = psutil.Process(self.pid)
        wmic_create = str(w.CreationDate.split('.')[0])
        psutil_create = time.strftime("%Y%m%d%H%M%S",
                                      time.localtime(p.create_time()))
        self.assertEqual(wmic_create, psutil_create)


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class TestDualProcessImplementation(unittest.TestCase):
    """
    Certain APIs on Windows have 2 internal implementations, one
    based on documented Windows APIs, another one based
    NtQuerySystemInformation() which gets called as fallback in
    case the first fails because of limited permission error.
    Here we test that the two methods return the exact same value,
    see:
    https://github.com/giampaolo/psutil/issues/304
    """

    @classmethod
    def setUpClass(cls):
        cls.pid = get_test_subprocess().pid

    @classmethod
    def tearDownClass(cls):
        reap_children()
    # ---
    # same tests as above but mimicks the AccessDenied failure of
    # the first (fast) method failing with AD.

    def test_name(self):
        name = psutil.Process(self.pid).name()
        with mock.patch("psutil._psplatform.cext.proc_exe",
                        side_effect=psutil.AccessDenied(os.getpid())) as fun:
            self.assertEqual(psutil.Process(self.pid).name(), name)
            assert fun.called

    def test_memory_info(self):
        mem_1 = psutil.Process(self.pid).memory_info()
        with mock.patch("psutil._psplatform.cext.proc_memory_info",
                        side_effect=OSError(errno.EPERM, "msg")) as fun:
            mem_2 = psutil.Process(self.pid).memory_info()
            self.assertEqual(len(mem_1), len(mem_2))
            for i in range(len(mem_1)):
                self.assertGreaterEqual(mem_1[i], 0)
                self.assertGreaterEqual(mem_2[i], 0)
                self.assertAlmostEqual(mem_1[i], mem_2[i], delta=512)
            assert fun.called

    def test_create_time(self):
        ctime = psutil.Process(self.pid).create_time()
        with mock.patch("psutil._psplatform.cext.proc_create_time",
                        side_effect=OSError(errno.EPERM, "msg")) as fun:
            self.assertEqual(psutil.Process(self.pid).create_time(), ctime)
            assert fun.called

    def test_cpu_times(self):
        cpu_times_1 = psutil.Process(self.pid).cpu_times()
        with mock.patch("psutil._psplatform.cext.proc_cpu_times",
                        side_effect=OSError(errno.EPERM, "msg")) as fun:
            cpu_times_2 = psutil.Process(self.pid).cpu_times()
            assert fun.called
            self.assertAlmostEqual(
                cpu_times_1.user, cpu_times_2.user, delta=0.01)
            self.assertAlmostEqual(
                cpu_times_1.system, cpu_times_2.system, delta=0.01)

    def test_io_counters(self):
        io_counters_1 = psutil.Process(self.pid).io_counters()
        with mock.patch("psutil._psplatform.cext.proc_io_counters",
                        side_effect=OSError(errno.EPERM, "msg")) as fun:
            io_counters_2 = psutil.Process(self.pid).io_counters()
            for i in range(len(io_counters_1)):
                self.assertAlmostEqual(
                    io_counters_1[i], io_counters_2[i], delta=5)
            assert fun.called

    def test_num_handles(self):
        num_handles = psutil.Process(self.pid).num_handles()
        with mock.patch("psutil._psplatform.cext.proc_num_handles",
                        side_effect=OSError(errno.EPERM, "msg")) as fun:
            self.assertEqual(psutil.Process(self.pid).num_handles(),
                             num_handles)
            assert fun.called


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class RemoteProcessTestCase(unittest.TestCase):
    """Certain functions require calling ReadProcessMemory.
    This trivially works when called on the current process.
    Check that this works on other processes, especially when they
    have a different bitness.
    """

    @staticmethod
    def find_other_interpreter():
        # find a python interpreter that is of the opposite bitness from us
        code = "import sys; sys.stdout.write(str(sys.maxsize > 2**32))"

        # XXX: a different and probably more stable approach might be to access
        # the registry but accessing 64 bit paths from a 32 bit process
        for filename in glob.glob(r"C:\Python*\python.exe"):
            proc = subprocess.Popen(args=[filename, "-c", code],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)
            output, _ = proc.communicate()
            if output == str(not IS_64_BIT):
                return filename

    @classmethod
    def setUpClass(cls):
        other_python = cls.find_other_interpreter()

        if other_python is None:
            raise unittest.SkipTest(
                "could not find interpreter with opposite bitness")

        if IS_64_BIT:
            cls.python64 = sys.executable
            cls.python32 = other_python
        else:
            cls.python64 = other_python
            cls.python32 = sys.executable

    test_args = ["-c", "import sys; sys.stdin.read()"]

    def setUp(self):
        env = os.environ.copy()
        env["THINK_OF_A_NUMBER"] = str(os.getpid())
        self.proc32 = get_test_subprocess([self.python32] + self.test_args,
                                          env=env,
                                          stdin=subprocess.PIPE)
        self.proc64 = get_test_subprocess([self.python64] + self.test_args,
                                          env=env,
                                          stdin=subprocess.PIPE)

    def tearDown(self):
        self.proc32.communicate()
        self.proc64.communicate()
        reap_children()

    @classmethod
    def tearDownClass(cls):
        reap_children()

    def test_cmdline_32(self):
        p = psutil.Process(self.proc32.pid)
        self.assertEqual(len(p.cmdline()), 3)
        self.assertEqual(p.cmdline()[1:], self.test_args)

    def test_cmdline_64(self):
        p = psutil.Process(self.proc64.pid)
        self.assertEqual(len(p.cmdline()), 3)
        self.assertEqual(p.cmdline()[1:], self.test_args)

    def test_cwd_32(self):
        p = psutil.Process(self.proc32.pid)
        self.assertEqual(p.cwd(), os.getcwd())

    def test_cwd_64(self):
        p = psutil.Process(self.proc64.pid)
        self.assertEqual(p.cwd(), os.getcwd())

    def test_environ_32(self):
        p = psutil.Process(self.proc32.pid)
        e = p.environ()
        self.assertIn("THINK_OF_A_NUMBER", e)
        self.assertEquals(e["THINK_OF_A_NUMBER"], str(os.getpid()))

    def test_environ_64(self):
        p = psutil.Process(self.proc64.pid)
        e = p.environ()
        self.assertIn("THINK_OF_A_NUMBER", e)
        self.assertEquals(e["THINK_OF_A_NUMBER"], str(os.getpid()))


# ===================================================================
# Windows services
# ===================================================================


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class TestServices(unittest.TestCase):

    def test_win_service_iter(self):
        valid_statuses = set([
            "running",
            "paused",
            "start",
            "pause",
            "continue",
            "stop",
            "stopped",
        ])
        valid_start_types = set([
            "automatic",
            "manual",
            "disabled",
        ])
        valid_statuses = set([
            "running",
            "paused",
            "start_pending",
            "pause_pending",
            "continue_pending",
            "stop_pending",
            "stopped"
        ])
        for serv in psutil.win_service_iter():
            data = serv.as_dict()
            self.assertIsInstance(data['name'], str)
            self.assertNotEqual(data['name'].strip(), "")
            self.assertIsInstance(data['display_name'], str)
            self.assertIsInstance(data['username'], str)
            self.assertIn(data['status'], valid_statuses)
            if data['pid'] is not None:
                psutil.Process(data['pid'])
            self.assertIsInstance(data['binpath'], str)
            self.assertIsInstance(data['username'], str)
            self.assertIsInstance(data['start_type'], str)
            self.assertIn(data['start_type'], valid_start_types)
            self.assertIn(data['status'], valid_statuses)
            self.assertIsInstance(data['description'], str)
            pid = serv.pid()
            if pid is not None:
                p = psutil.Process(pid)
                self.assertTrue(p.is_running())
            # win_service_get
            s = psutil.win_service_get(serv.name())
            # test __eq__
            self.assertEqual(serv, s)

    def test_win_service_get(self):
        name = next(psutil.win_service_iter()).name()

        with self.assertRaises(psutil.NoSuchProcess) as cm:
            psutil.win_service_get(name + '???')
        self.assertEqual(cm.exception.name, name + '???')

        # test NoSuchProcess
        service = psutil.win_service_get(name)
        exc = WindowsError(
            psutil._psplatform.cext.ERROR_SERVICE_DOES_NOT_EXIST, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.NoSuchProcess, service.username)

        # test AccessDenied
        exc = WindowsError(
            psutil._psplatform.cext.ERROR_ACCESS_DENIED, "")
        with mock.patch("psutil._psplatform.cext.winservice_query_status",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.status)
        with mock.patch("psutil._psplatform.cext.winservice_query_config",
                        side_effect=exc):
            self.assertRaises(psutil.AccessDenied, service.username)

        # test __str__ and __repr__
        self.assertIn(service.name(), str(service))
        self.assertIn(service.display_name(), str(service))
        self.assertIn(service.name(), repr(service))
        self.assertIn(service.display_name(), repr(service))


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_unicode.py000064400000031133150466730540010760 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Notes about unicode handling in psutil
======================================

In psutil these are the APIs returning or dealing with a string
('not tested' means they are not tested to deal with non-ASCII strings):

* Process.cmdline()
* Process.connections('unix')
* Process.cwd()
* Process.environ()
* Process.exe()
* Process.memory_maps()
* Process.name()
* Process.open_files()
* Process.username()             (not tested)

* disk_io_counters()             (not tested)
* disk_partitions()              (not tested)
* disk_usage(str)
* net_connections('unix')
* net_if_addrs()                 (not tested)
* net_if_stats()                 (not tested)
* net_io_counters()              (not tested)
* sensors_fans()                 (not tested)
* sensors_temperatures()         (not tested)
* users()                        (not tested)

* WindowsService.binpath()       (not tested)
* WindowsService.description()   (not tested)
* WindowsService.display_name()  (not tested)
* WindowsService.name()          (not tested)
* WindowsService.status()        (not tested)
* WindowsService.username()      (not tested)

In here we create a unicode path with a funky non-ASCII name and (where
possible) make psutil return it back (e.g. on name(), exe(), open_files(),
etc.) and make sure that:

* psutil never crashes with UnicodeDecodeError
* the returned path matches

For a detailed explanation of how psutil handles unicode see:
- https://github.com/giampaolo/psutil/issues/1040
- http://psutil.readthedocs.io/#unicode
"""

import os
import traceback
import warnings
from contextlib import closing

from psutil import BSD
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import WINDOWS
from psutil._compat import PY3
from psutil._compat import u
from psutil.tests import APPVEYOR
from psutil.tests import ASCII_FS
from psutil.tests import bind_unix_socket
from psutil.tests import chdir
from psutil.tests import copyload_shared_lib
from psutil.tests import create_exe
from psutil.tests import get_test_subprocess
from psutil.tests import HAS_CONNECTIONS_UNIX
from psutil.tests import HAS_ENVIRON
from psutil.tests import HAS_MEMORY_MAPS
from psutil.tests import mock
from psutil.tests import reap_children
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_mkdir
from psutil.tests import safe_rmpath as _safe_rmpath
from psutil.tests import skip_on_access_denied
from psutil.tests import TESTFILE_PREFIX
from psutil.tests import TESTFN
from psutil.tests import TESTFN_UNICODE
from psutil.tests import TRAVIS
from psutil.tests import unittest
from psutil.tests import unix_socket_path
import psutil
import psutil.tests


def safe_rmpath(path):
    if APPVEYOR:
        # TODO - this is quite random and I'm not sure why it happens,
        # nor I can reproduce it locally:
        # https://ci.appveyor.com/project/giampaolo/psutil/build/job/
        #     jiq2cgd6stsbtn60
        # safe_rmpath() happens after reap_children() so this is weird
        # Perhaps wait_procs() on Windows is broken? Maybe because
        # of STILL_ACTIVE?
        # https://github.com/giampaolo/psutil/blob/
        #     68c7a70728a31d8b8b58f4be6c4c0baa2f449eda/psutil/arch/
        #     windows/process_info.c#L146
        try:
            return _safe_rmpath(path)
        except WindowsError:
            traceback.print_exc()
    else:
        return _safe_rmpath(path)


def subprocess_supports_unicode(name):
    """Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    """
    if PY3:
        return True
    try:
        safe_rmpath(name)
        create_exe(name)
        get_test_subprocess(cmd=[name])
    except UnicodeEncodeError:
        return False
    else:
        return True
    finally:
        reap_children()


# An invalid unicode string.
if PY3:
    INVALID_NAME = (TESTFN.encode('utf8') + b"f\xc0\x80").decode(
        'utf8', 'surrogateescape')
else:
    INVALID_NAME = TESTFN + "f\xc0\x80"


# ===================================================================
# FS APIs
# ===================================================================


class _BaseFSAPIsTests(object):
    funky_name = None

    @classmethod
    def setUpClass(cls):
        safe_rmpath(cls.funky_name)
        create_exe(cls.funky_name)

    @classmethod
    def tearDownClass(cls):
        reap_children()
        safe_rmpath(cls.funky_name)

    def tearDown(self):
        reap_children()

    def expect_exact_path_match(self):
        raise NotImplementedError("must be implemented in subclass")

    def test_proc_exe(self):
        subp = get_test_subprocess(cmd=[self.funky_name])
        p = psutil.Process(subp.pid)
        exe = p.exe()
        self.assertIsInstance(exe, str)
        if self.expect_exact_path_match():
            self.assertEqual(exe, self.funky_name)

    def test_proc_name(self):
        subp = get_test_subprocess(cmd=[self.funky_name])
        if WINDOWS:
            # On Windows name() is determined from exe() first, because
            # it's faster; we want to overcome the internal optimization
            # and test name() instead of exe().
            with mock.patch("psutil._psplatform.cext.proc_exe",
                            side_effect=psutil.AccessDenied(os.getpid())) as m:
                name = psutil.Process(subp.pid).name()
                assert m.called
        else:
            name = psutil.Process(subp.pid).name()
        self.assertIsInstance(name, str)
        if self.expect_exact_path_match():
            self.assertEqual(name, os.path.basename(self.funky_name))

    def test_proc_cmdline(self):
        subp = get_test_subprocess(cmd=[self.funky_name])
        p = psutil.Process(subp.pid)
        cmdline = p.cmdline()
        for part in cmdline:
            self.assertIsInstance(part, str)
        if self.expect_exact_path_match():
            self.assertEqual(cmdline, [self.funky_name])

    def test_proc_cwd(self):
        dname = self.funky_name + "2"
        self.addCleanup(safe_rmpath, dname)
        safe_mkdir(dname)
        with chdir(dname):
            p = psutil.Process()
            cwd = p.cwd()
        self.assertIsInstance(p.cwd(), str)
        if self.expect_exact_path_match():
            self.assertEqual(cwd, dname)

    def test_proc_open_files(self):
        p = psutil.Process()
        start = set(p.open_files())
        with open(self.funky_name, 'rb'):
            new = set(p.open_files())
        path = (new - start).pop().path
        self.assertIsInstance(path, str)
        if BSD and not path:
            # XXX - see https://github.com/giampaolo/psutil/issues/595
            return self.skipTest("open_files on BSD is broken")
        if self.expect_exact_path_match():
            self.assertEqual(os.path.normcase(path),
                             os.path.normcase(self.funky_name))

    @unittest.skipIf(not POSIX, "POSIX only")
    def test_proc_connections(self):
        suffix = os.path.basename(self.funky_name)
        with unix_socket_path(suffix=suffix) as name:
            try:
                sock = bind_unix_socket(name)
            except UnicodeEncodeError:
                if PY3:
                    raise
                else:
                    raise unittest.SkipTest("not supported")
            with closing(sock):
                conn = psutil.Process().connections('unix')[0]
                self.assertIsInstance(conn.laddr, str)
                # AF_UNIX addr not set on OpenBSD
                if not OPENBSD:
                    self.assertEqual(conn.laddr, name)

    @unittest.skipIf(not POSIX, "POSIX only")
    @unittest.skipIf(not HAS_CONNECTIONS_UNIX, "can't list UNIX sockets")
    @skip_on_access_denied()
    def test_net_connections(self):
        def find_sock(cons):
            for conn in cons:
                if os.path.basename(conn.laddr).startswith(TESTFILE_PREFIX):
                    return conn
            raise ValueError("connection not found")

        suffix = os.path.basename(self.funky_name)
        with unix_socket_path(suffix=suffix) as name:
            try:
                sock = bind_unix_socket(name)
            except UnicodeEncodeError:
                if PY3:
                    raise
                else:
                    raise unittest.SkipTest("not supported")
            with closing(sock):
                cons = psutil.net_connections(kind='unix')
                # AF_UNIX addr not set on OpenBSD
                if not OPENBSD:
                    conn = find_sock(cons)
                    self.assertIsInstance(conn.laddr, str)
                    self.assertEqual(conn.laddr, name)

    def test_disk_usage(self):
        dname = self.funky_name + "2"
        self.addCleanup(safe_rmpath, dname)
        safe_mkdir(dname)
        psutil.disk_usage(dname)

    @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
    @unittest.skipIf(not PY3, "ctypes does not support unicode on PY2")
    def test_memory_maps(self):
        # XXX: on Python 2, using ctypes.CDLL with a unicode path
        # opens a message box which blocks the test run.
        with copyload_shared_lib(dst_prefix=self.funky_name) as funky_path:
            def normpath(p):
                return os.path.realpath(os.path.normcase(p))
            libpaths = [normpath(x.path)
                        for x in psutil.Process().memory_maps()]
            # ...just to have a clearer msg in case of failure
            libpaths = [x for x in libpaths if TESTFILE_PREFIX in x]
            self.assertIn(normpath(funky_path), libpaths)
            for path in libpaths:
                self.assertIsInstance(path, str)


@unittest.skipIf(OSX and TRAVIS, "unreliable on TRAVIS")  # TODO
@unittest.skipIf(ASCII_FS, "ASCII fs")
@unittest.skipIf(not subprocess_supports_unicode(TESTFN_UNICODE),
                 "subprocess can't deal with unicode")
class TestFSAPIs(_BaseFSAPIsTests, unittest.TestCase):
    """Test FS APIs with a funky, valid, UTF8 path name."""
    funky_name = TESTFN_UNICODE

    @classmethod
    def expect_exact_path_match(cls):
        # Do not expect psutil to correctly handle unicode paths on
        # Python 2 if os.listdir() is not able either.
        if PY3:
            return True
        else:
            here = '.' if isinstance(cls.funky_name, str) else u('.')
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                return cls.funky_name in os.listdir(here)


@unittest.skipIf(OSX and TRAVIS, "unreliable on TRAVIS")  # TODO
@unittest.skipIf(not subprocess_supports_unicode(INVALID_NAME),
                 "subprocess can't deal with invalid unicode")
class TestFSAPIsWithInvalidPath(_BaseFSAPIsTests, unittest.TestCase):
    """Test FS APIs with a funky, invalid path name."""
    funky_name = INVALID_NAME

    @classmethod
    def expect_exact_path_match(cls):
        # Invalid unicode names are supposed to work on Python 2.
        return True


@unittest.skipIf(not WINDOWS, "WINDOWS only")
class TestWinProcessName(unittest.TestCase):

    def test_name_type(self):
        # On Windows name() is determined from exe() first, because
        # it's faster; we want to overcome the internal optimization
        # and test name() instead of exe().
        with mock.patch("psutil._psplatform.cext.proc_exe",
                        side_effect=psutil.AccessDenied(os.getpid())) as m:
            self.assertIsInstance(psutil.Process().name(), str)
            assert m.called


# ===================================================================
# Non fs APIs
# ===================================================================


class TestNonFSAPIS(unittest.TestCase):
    """Unicode tests for non fs-related APIs."""

    def tearDown(self):
        reap_children()

    @unittest.skipIf(not HAS_ENVIRON, "not supported")
    def test_proc_environ(self):
        # Note: differently from others, this test does not deal
        # with fs paths. On Python 2 subprocess module is broken as
        # it's not able to handle with non-ASCII env vars, so
        # we use "è", which is part of the extended ASCII table
        # (unicode point <= 255).
        env = os.environ.copy()
        funky_str = TESTFN_UNICODE if PY3 else 'è'
        env['FUNNY_ARG'] = funky_str
        sproc = get_test_subprocess(env=env)
        p = psutil.Process(sproc.pid)
        env = p.environ()
        for k, v in env.items():
            self.assertIsInstance(k, str)
            self.assertIsInstance(v, str)
        self.assertEqual(env['FUNNY_ARG'], funky_str)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_aix.py000064400000010555150466730540010120 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'
# Copyright (c) 2017, Arnon Yaari
# All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""AIX specific tests."""

import re

from psutil import AIX
from psutil.tests import run_test_module_by_name
from psutil.tests import sh
from psutil.tests import unittest
import psutil


@unittest.skipIf(not AIX, "AIX only")
class AIXSpecificTestCase(unittest.TestCase):

    def test_virtual_memory(self):
        out = sh('/usr/bin/svmon -O unit=KB')
        re_pattern = "memory\s*"
        for field in ("size inuse free pin virtual available mmode").split():
            re_pattern += "(?P<%s>\S+)\s+" % (field,)
        matchobj = re.search(re_pattern, out)

        self.assertIsNotNone(
            matchobj, "svmon command returned unexpected output")

        KB = 1024
        total = int(matchobj.group("size")) * KB
        available = int(matchobj.group("available")) * KB
        used = int(matchobj.group("inuse")) * KB
        free = int(matchobj.group("free")) * KB

        psutil_result = psutil.virtual_memory()

        # MEMORY_TOLERANCE from psutil.tests is not enough. For some reason
        # we're seeing differences of ~1.2 MB. 2 MB is still a good tolerance
        # when compared to GBs.
        MEMORY_TOLERANCE = 2 * KB * KB   # 2 MB
        self.assertEqual(psutil_result.total, total)
        self.assertAlmostEqual(
            psutil_result.used, used, delta=MEMORY_TOLERANCE)
        self.assertAlmostEqual(
            psutil_result.available, available, delta=MEMORY_TOLERANCE)
        self.assertAlmostEqual(
            psutil_result.free, free, delta=MEMORY_TOLERANCE)

    def test_swap_memory(self):
        out = sh('/usr/sbin/lsps -a')
        # From the man page, "The size is given in megabytes" so we assume
        # we'll always have 'MB' in the result
        # TODO maybe try to use "swap -l" to check "used" too, but its units
        # are not guaranteed to be "MB" so parsing may not be consistent
        matchobj = re.search("(?P<space>\S+)\s+"
                             "(?P<vol>\S+)\s+"
                             "(?P<vg>\S+)\s+"
                             "(?P<size>\d+)MB", out)

        self.assertIsNotNone(
            matchobj, "lsps command returned unexpected output")

        total_mb = int(matchobj.group("size"))
        MB = 1024 ** 2
        psutil_result = psutil.swap_memory()
        # we divide our result by MB instead of multiplying the lsps value by
        # MB because lsps may round down, so we round down too
        self.assertEqual(int(psutil_result.total / MB), total_mb)

    def test_cpu_stats(self):
        out = sh('/usr/bin/mpstat -a')

        re_pattern = "ALL\s*"
        for field in ("min maj mpcs mpcr dev soft dec ph cs ics bound rq "
                      "push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd "
                      "sysc").split():
            re_pattern += "(?P<%s>\S+)\s+" % (field,)
        matchobj = re.search(re_pattern, out)

        self.assertIsNotNone(
            matchobj, "mpstat command returned unexpected output")

        # numbers are usually in the millions so 1000 is ok for tolerance
        CPU_STATS_TOLERANCE = 1000
        psutil_result = psutil.cpu_stats()
        self.assertAlmostEqual(
            psutil_result.ctx_switches,
            int(matchobj.group("cs")),
            delta=CPU_STATS_TOLERANCE)
        self.assertAlmostEqual(
            psutil_result.syscalls,
            int(matchobj.group("sysc")),
            delta=CPU_STATS_TOLERANCE)
        self.assertAlmostEqual(
            psutil_result.interrupts,
            int(matchobj.group("dev")),
            delta=CPU_STATS_TOLERANCE)
        self.assertAlmostEqual(
            psutil_result.soft_interrupts,
            int(matchobj.group("soft")),
            delta=CPU_STATS_TOLERANCE)

    def test_cpu_count_logical(self):
        out = sh('/usr/bin/mpstat -a')
        mpstat_lcpu = int(re.search("lcpu=(\d+)", out).group(1))
        psutil_lcpu = psutil.cpu_count(logical=True)
        self.assertEqual(mpstat_lcpu, psutil_lcpu)

    def test_net_if_addrs_names(self):
        out = sh('/etc/ifconfig -l')
        ifconfig_names = set(out.split())
        psutil_names = set(psutil.net_if_addrs().keys())
        self.assertSetEqual(ifconfig_names, psutil_names)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/__main__.py000064400000005312150466730540010013 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Run unit tests. This is invoked by:

$ python -m psutil.tests
"""

import contextlib
import optparse
import os
import ssl
import sys
import tempfile
try:
    from urllib.request import urlopen  # py3
except ImportError:
    from urllib2 import urlopen

from psutil.tests import PYTHON_EXE
from psutil.tests import run_suite


HERE = os.path.abspath(os.path.dirname(__file__))
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
TEST_DEPS = []
if sys.version_info[:2] == (2, 6):
    TEST_DEPS.extend(["ipaddress", "unittest2", "argparse", "mock==1.0.1"])
elif sys.version_info[:2] == (2, 7) or sys.version_info[:2] <= (3, 2):
    TEST_DEPS.extend(["ipaddress", "mock"])
elif sys.version_info[:2] == (3, 3):
    TEST_DEPS.extend(["ipaddress"])


def install_pip():
    try:
        import pip  # NOQA
    except ImportError:
        f = tempfile.NamedTemporaryFile(suffix='.py')
        with contextlib.closing(f):
            print("downloading %s to %s" % (GET_PIP_URL, f.name))
            if hasattr(ssl, '_create_unverified_context'):
                ctx = ssl._create_unverified_context()
            else:
                ctx = None
            kwargs = dict(context=ctx) if ctx else {}
            req = urlopen(GET_PIP_URL, **kwargs)
            data = req.read()
            f.write(data)
            f.flush()

            print("installing pip")
            code = os.system('%s %s --user' % (PYTHON_EXE, f.name))
            return code


def install_test_deps(deps=None):
    """Install test dependencies via pip."""
    if deps is None:
        deps = TEST_DEPS
    deps = set(deps)
    if deps:
        is_venv = hasattr(sys, 'real_prefix')
        opts = "--user" if not is_venv else ""
        install_pip()
        code = os.system('%s -m pip install %s --upgrade %s' % (
            PYTHON_EXE, opts, " ".join(deps)))
        return code


def main():
    usage = "%s -m psutil.tests [opts]" % PYTHON_EXE
    parser = optparse.OptionParser(usage=usage, description="run unit tests")
    parser.add_option("-i", "--install-deps",
                      action="store_true", default=False,
                      help="don't print status messages to stdout")

    opts, args = parser.parse_args()
    if opts.install_deps:
        install_pip()
        install_test_deps()
    else:
        for dep in TEST_DEPS:
            try:
                __import__(dep.split("==")[0])
            except ImportError:
                sys.exit("%r lib is not installed; run %s -m psutil.tests "
                         "--install-deps" % (dep, PYTHON_EXE))
        run_suite()


main()
tests/test_linux.py000064400000231604150466730540010476 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Linux specific tests."""

from __future__ import division
import collections
import contextlib
import errno
import glob
import io
import os
import pprint
import re
import shutil
import socket
import struct
import tempfile
import textwrap
import time
import warnings

import psutil
from psutil import LINUX
from psutil._compat import PY3
from psutil._compat import u
from psutil.tests import call_until
from psutil.tests import HAS_BATTERY
from psutil.tests import HAS_CPU_FREQ
from psutil.tests import HAS_RLIMIT
from psutil.tests import MEMORY_TOLERANCE
from psutil.tests import mock
from psutil.tests import PYPY
from psutil.tests import pyrun
from psutil.tests import reap_children
from psutil.tests import reload_module
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_rmpath
from psutil.tests import sh
from psutil.tests import skip_on_not_implemented
from psutil.tests import TESTFN
from psutil.tests import ThreadTask
from psutil.tests import TRAVIS
from psutil.tests import unittest
from psutil.tests import which


HERE = os.path.abspath(os.path.dirname(__file__))
SIOCGIFADDR = 0x8915
SIOCGIFCONF = 0x8912
SIOCGIFHWADDR = 0x8927
if LINUX:
    SECTOR_SIZE = 512


# =====================================================================
# --- utils
# =====================================================================


def get_ipv4_address(ifname):
    import fcntl
    ifname = ifname[:15]
    if PY3:
        ifname = bytes(ifname, 'ascii')
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    with contextlib.closing(s):
        return socket.inet_ntoa(
            fcntl.ioctl(s.fileno(),
                        SIOCGIFADDR,
                        struct.pack('256s', ifname))[20:24])


def get_mac_address(ifname):
    import fcntl
    ifname = ifname[:15]
    if PY3:
        ifname = bytes(ifname, 'ascii')
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    with contextlib.closing(s):
        info = fcntl.ioctl(
            s.fileno(), SIOCGIFHWADDR, struct.pack('256s', ifname))
        if PY3:
            def ord(x):
                return x
        else:
            import __builtin__
            ord = __builtin__.ord
        return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]


def free_swap():
    """Parse 'free' cmd and return swap memory's s total, used and free
    values.
    """
    out = sh('free -b')
    lines = out.split('\n')
    for line in lines:
        if line.startswith('Swap'):
            _, total, used, free = line.split()
            nt = collections.namedtuple('free', 'total used free')
            return nt(int(total), int(used), int(free))
    raise ValueError(
        "can't find 'Swap' in 'free' output:\n%s" % '\n'.join(lines))


def free_physmem():
    """Parse 'free' cmd and return physical memory's total, used
    and free values.
    """
    # Note: free can have 2 different formats, invalidating 'shared'
    # and 'cached' memory which may have different positions so we
    # do not return them.
    # https://github.com/giampaolo/psutil/issues/538#issuecomment-57059946
    out = sh('free -b')
    lines = out.split('\n')
    for line in lines:
        if line.startswith('Mem'):
            total, used, free, shared = \
                [int(x) for x in line.split()[1:5]]
            nt = collections.namedtuple(
                'free', 'total used free shared output')
            return nt(total, used, free, shared, out)
    raise ValueError(
        "can't find 'Mem' in 'free' output:\n%s" % '\n'.join(lines))


def vmstat(stat):
    out = sh("vmstat -s")
    for line in out.split("\n"):
        line = line.strip()
        if stat in line:
            return int(line.split(' ')[0])
    raise ValueError("can't find %r in 'vmstat' output" % stat)


def get_free_version_info():
    out = sh("free -V").strip()
    return tuple(map(int, out.split()[-1].split('.')))


# =====================================================================
# --- system virtual memory
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemVirtualMemory(unittest.TestCase):

    def test_total(self):
        # free_value = free_physmem().total
        # psutil_value = psutil.virtual_memory().total
        # self.assertEqual(free_value, psutil_value)
        vmstat_value = vmstat('total memory') * 1024
        psutil_value = psutil.virtual_memory().total
        self.assertAlmostEqual(vmstat_value, psutil_value)

    # Older versions of procps used slab memory to calculate used memory.
    # This got changed in:
    # https://gitlab.com/procps-ng/procps/commit/
    #     05d751c4f076a2f0118b914c5e51cfbb4762ad8e
    @unittest.skipIf(LINUX and get_free_version_info() < (3, 3, 12),
                     "old free version")
    @retry_before_failing()
    def test_used(self):
        free = free_physmem()
        free_value = free.used
        psutil_value = psutil.virtual_memory().used
        self.assertAlmostEqual(
            free_value, psutil_value, delta=MEMORY_TOLERANCE,
            msg='%s %s \n%s' % (free_value, psutil_value, free.output))

    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    @retry_before_failing()
    def test_free(self):
        # _, _, free_value, _ = free_physmem()
        # psutil_value = psutil.virtual_memory().free
        # self.assertAlmostEqual(
        #     free_value, psutil_value, delta=MEMORY_TOLERANCE)
        vmstat_value = vmstat('free memory') * 1024
        psutil_value = psutil.virtual_memory().free
        self.assertAlmostEqual(
            vmstat_value, psutil_value, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_buffers(self):
        vmstat_value = vmstat('buffer memory') * 1024
        psutil_value = psutil.virtual_memory().buffers
        self.assertAlmostEqual(
            vmstat_value, psutil_value, delta=MEMORY_TOLERANCE)

    # https://travis-ci.org/giampaolo/psutil/jobs/226719664
    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    @retry_before_failing()
    def test_active(self):
        vmstat_value = vmstat('active memory') * 1024
        psutil_value = psutil.virtual_memory().active
        self.assertAlmostEqual(
            vmstat_value, psutil_value, delta=MEMORY_TOLERANCE)

    # https://travis-ci.org/giampaolo/psutil/jobs/227242952
    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    @retry_before_failing()
    def test_inactive(self):
        vmstat_value = vmstat('inactive memory') * 1024
        psutil_value = psutil.virtual_memory().inactive
        self.assertAlmostEqual(
            vmstat_value, psutil_value, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_shared(self):
        free = free_physmem()
        free_value = free.shared
        if free_value == 0:
            raise unittest.SkipTest("free does not support 'shared' column")
        psutil_value = psutil.virtual_memory().shared
        self.assertAlmostEqual(
            free_value, psutil_value, delta=MEMORY_TOLERANCE,
            msg='%s %s \n%s' % (free_value, psutil_value, free.output))

    @retry_before_failing()
    def test_available(self):
        # "free" output format has changed at some point:
        # https://github.com/giampaolo/psutil/issues/538#issuecomment-147192098
        out = sh("free -b")
        lines = out.split('\n')
        if 'available' not in lines[0]:
            raise unittest.SkipTest("free does not support 'available' column")
        else:
            free_value = int(lines[1].split()[-1])
            psutil_value = psutil.virtual_memory().available
            self.assertAlmostEqual(
                free_value, psutil_value, delta=MEMORY_TOLERANCE,
                msg='%s %s \n%s' % (free_value, psutil_value, out))

    def test_warnings_on_misses(self):
        # Emulate a case where /proc/meminfo provides few info.
        # psutil is supposed to set the missing fields to 0 and
        # raise a warning.
        def open_mock(name, *args, **kwargs):
            if name == '/proc/meminfo':
                return io.BytesIO(textwrap.dedent("""\
                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemAvailable:         -1 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    SReclaimable:     346648 kB
                    """).encode())
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
            with warnings.catch_warnings(record=True) as ws:
                warnings.simplefilter("always")
                ret = psutil.virtual_memory()
                assert m.called
                self.assertEqual(len(ws), 1)
                w = ws[0]
                assert w.filename.endswith('psutil/_pslinux.py')
                self.assertIn(
                    "memory stats couldn't be determined", str(w.message))
                self.assertIn("cached", str(w.message))
                self.assertIn("shared", str(w.message))
                self.assertIn("active", str(w.message))
                self.assertIn("inactive", str(w.message))
                self.assertIn("buffers", str(w.message))
                self.assertIn("available", str(w.message))
                self.assertEqual(ret.cached, 0)
                self.assertEqual(ret.active, 0)
                self.assertEqual(ret.inactive, 0)
                self.assertEqual(ret.shared, 0)
                self.assertEqual(ret.buffers, 0)
                self.assertEqual(ret.available, 0)

    def test_avail_old_percent(self):
        # Make sure that our calculation of avail mem for old kernels
        # is off by max 10%.
        from psutil._pslinux import calculate_avail_vmem
        from psutil._pslinux import open_binary

        mems = {}
        with open_binary('/proc/meminfo') as f:
            for line in f:
                fields = line.split()
                mems[fields[0]] = int(fields[1]) * 1024

        a = calculate_avail_vmem(mems)
        if b'MemAvailable:' in mems:
            b = mems[b'MemAvailable:']
            diff_percent = abs(a - b) / a * 100
            self.assertLess(diff_percent, 10)

    def test_avail_old_comes_from_kernel(self):
        # Make sure "MemAvailable:" coluimn is used instead of relying
        # on our internal algorithm to calculate avail mem.
        def open_mock(name, *args, **kwargs):
            if name == "/proc/meminfo":
                return io.BytesIO(textwrap.dedent("""\
                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemAvailable:    6574984 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    SReclaimable:     346648 kB
                    """).encode())
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
            with warnings.catch_warnings(record=True) as ws:
                ret = psutil.virtual_memory()
            assert m.called
            self.assertEqual(ret.available, 6574984 * 1024)
            w = ws[0]
            self.assertIn(
                "inactive memory stats couldn't be determined", str(w.message))

    def test_avail_old_missing_fields(self):
        # Remove Active(file), Inactive(file) and SReclaimable
        # from /proc/meminfo and make sure the fallback is used
        # (free + cached),
        def open_mock(name, *args, **kwargs):
            if name == "/proc/meminfo":
                return io.BytesIO(textwrap.dedent("""\
                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    """).encode())
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
            with warnings.catch_warnings(record=True) as ws:
                ret = psutil.virtual_memory()
            assert m.called
            self.assertEqual(ret.available, 2057400 * 1024 + 4818144 * 1024)
            w = ws[0]
            self.assertIn(
                "inactive memory stats couldn't be determined", str(w.message))

    def test_avail_old_missing_zoneinfo(self):
        # Remove /proc/zoneinfo file. Make sure fallback is used
        # (free + cached).
        def open_mock(name, *args, **kwargs):
            if name == "/proc/meminfo":
                return io.BytesIO(textwrap.dedent("""\
                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    SReclaimable:     346648 kB
                    """).encode())
            elif name == "/proc/zoneinfo":
                raise IOError(errno.ENOENT, 'no such file or directory')
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
            with warnings.catch_warnings(record=True) as ws:
                ret = psutil.virtual_memory()
            assert m.called
            self.assertEqual(ret.available, 2057400 * 1024 + 4818144 * 1024)
            w = ws[0]
            self.assertIn(
                "inactive memory stats couldn't be determined", str(w.message))


# =====================================================================
# --- system swap memory
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemSwapMemory(unittest.TestCase):

    @staticmethod
    def meminfo_has_swap_info():
        """Return True if /proc/meminfo provides swap metrics."""
        with open("/proc/meminfo") as f:
            data = f.read()
        return 'SwapTotal:' in data and 'SwapFree:' in data

    def test_total(self):
        free_value = free_swap().total
        psutil_value = psutil.swap_memory().total
        return self.assertAlmostEqual(
            free_value, psutil_value, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_used(self):
        free_value = free_swap().used
        psutil_value = psutil.swap_memory().used
        return self.assertAlmostEqual(
            free_value, psutil_value, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_free(self):
        free_value = free_swap().free
        psutil_value = psutil.swap_memory().free
        return self.assertAlmostEqual(
            free_value, psutil_value, delta=MEMORY_TOLERANCE)

    def test_missing_sin_sout(self):
        with mock.patch('psutil._pslinux.open', create=True) as m:
            with warnings.catch_warnings(record=True) as ws:
                warnings.simplefilter("always")
                ret = psutil.swap_memory()
                assert m.called
                self.assertEqual(len(ws), 1)
                w = ws[0]
                assert w.filename.endswith('psutil/_pslinux.py')
                self.assertIn(
                    "'sin' and 'sout' swap memory stats couldn't "
                    "be determined", str(w.message))
                self.assertEqual(ret.sin, 0)
                self.assertEqual(ret.sout, 0)

    def test_no_vmstat_mocked(self):
        # see https://github.com/giampaolo/psutil/issues/722
        def open_mock(name, *args, **kwargs):
            if name == "/proc/vmstat":
                raise IOError(errno.ENOENT, 'no such file or directory')
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
            with warnings.catch_warnings(record=True) as ws:
                warnings.simplefilter("always")
                ret = psutil.swap_memory()
                assert m.called
                self.assertEqual(len(ws), 1)
                w = ws[0]
                assert w.filename.endswith('psutil/_pslinux.py')
                self.assertIn(
                    "'sin' and 'sout' swap memory stats couldn't "
                    "be determined and were set to 0",
                    str(w.message))
                self.assertEqual(ret.sin, 0)
                self.assertEqual(ret.sout, 0)

    def test_meminfo_against_sysinfo(self):
        # Make sure the content of /proc/meminfo about swap memory
        # matches sysinfo() syscall, see:
        # https://github.com/giampaolo/psutil/issues/1015
        if not self.meminfo_has_swap_info():
            return unittest.skip("/proc/meminfo has no swap metrics")
        with mock.patch('psutil._pslinux.cext.linux_sysinfo') as m:
            swap = psutil.swap_memory()
        assert not m.called
        import psutil._psutil_linux as cext
        _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
        total *= unit_multiplier
        free *= unit_multiplier
        self.assertEqual(swap.total, total)
        self.assertEqual(swap.free, free)

    def test_emulate_meminfo_has_no_metrics(self):
        # Emulate a case where /proc/meminfo provides no swap metrics
        # in which case sysinfo() syscall is supposed to be used
        # as a fallback.
        def open_mock(name, *args, **kwargs):
            if name == "/proc/meminfo":
                return io.BytesIO(b"")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, create=True, side_effect=open_mock) as m:
            psutil.swap_memory()
            assert m.called


# =====================================================================
# --- system CPU
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPU(unittest.TestCase):

    @unittest.skipIf(TRAVIS, "unknown failure on travis")
    def test_cpu_times(self):
        fields = psutil.cpu_times()._fields
        kernel_ver = re.findall(r'\d+\.\d+\.\d+', os.uname()[2])[0]
        kernel_ver_info = tuple(map(int, kernel_ver.split('.')))
        if kernel_ver_info >= (2, 6, 11):
            self.assertIn('steal', fields)
        else:
            self.assertNotIn('steal', fields)
        if kernel_ver_info >= (2, 6, 24):
            self.assertIn('guest', fields)
        else:
            self.assertNotIn('guest', fields)
        if kernel_ver_info >= (3, 2, 0):
            self.assertIn('guest_nice', fields)
        else:
            self.assertNotIn('guest_nice', fields)

    @unittest.skipIf(not os.path.exists("/sys/devices/system/cpu/online"),
                     "/sys/devices/system/cpu/online does not exist")
    def test_cpu_count_logical_w_sysdev_cpu_online(self):
        with open("/sys/devices/system/cpu/online") as f:
            value = f.read().strip()
        if "-" in str(value):
            value = int(value.split('-')[1]) + 1
            self.assertEqual(psutil.cpu_count(), value)

    @unittest.skipIf(not os.path.exists("/sys/devices/system/cpu"),
                     "/sys/devices/system/cpu does not exist")
    def test_cpu_count_logical_w_sysdev_cpu_num(self):
        ls = os.listdir("/sys/devices/system/cpu")
        count = len([x for x in ls if re.search(r"cpu\d+$", x) is not None])
        self.assertEqual(psutil.cpu_count(), count)

    @unittest.skipIf(not which("nproc"), "nproc utility not available")
    def test_cpu_count_logical_w_nproc(self):
        num = int(sh("nproc --all"))
        self.assertEqual(psutil.cpu_count(logical=True), num)

    @unittest.skipIf(not which("lscpu"), "lscpu utility not available")
    def test_cpu_count_logical_w_lscpu(self):
        out = sh("lscpu -p")
        num = len([x for x in out.split('\n') if not x.startswith('#')])
        self.assertEqual(psutil.cpu_count(logical=True), num)

    def test_cpu_count_logical_mocked(self):
        import psutil._pslinux
        original = psutil._pslinux.cpu_count_logical()
        # Here we want to mock os.sysconf("SC_NPROCESSORS_ONLN") in
        # order to cause the parsing of /proc/cpuinfo and /proc/stat.
        with mock.patch(
                'psutil._pslinux.os.sysconf', side_effect=ValueError) as m:
            self.assertEqual(psutil._pslinux.cpu_count_logical(), original)
            assert m.called

            # Let's have open() return emtpy data and make sure None is
            # returned ('cause we mimick os.cpu_count()).
            with mock.patch('psutil._pslinux.open', create=True) as m:
                self.assertIsNone(psutil._pslinux.cpu_count_logical())
                self.assertEqual(m.call_count, 2)
                # /proc/stat should be the last one
                self.assertEqual(m.call_args[0][0], '/proc/stat')

            # Let's push this a bit further and make sure /proc/cpuinfo
            # parsing works as expected.
            with open('/proc/cpuinfo', 'rb') as f:
                cpuinfo_data = f.read()
            fake_file = io.BytesIO(cpuinfo_data)
            with mock.patch('psutil._pslinux.open',
                            return_value=fake_file, create=True) as m:
                self.assertEqual(psutil._pslinux.cpu_count_logical(), original)

            # Finally, let's make /proc/cpuinfo return meaningless data;
            # this way we'll fall back on relying on /proc/stat
            def open_mock(name, *args, **kwargs):
                if name.startswith('/proc/cpuinfo'):
                    return io.BytesIO(b"")
                else:
                    return orig_open(name, *args, **kwargs)

            orig_open = open
            patch_point = 'builtins.open' if PY3 else '__builtin__.open'
            with mock.patch(patch_point, side_effect=open_mock, create=True):
                self.assertEqual(psutil._pslinux.cpu_count_logical(), original)

    def test_cpu_count_physical_mocked(self):
        # Have open() return emtpy data and make sure None is returned
        # ('cause we want to mimick os.cpu_count())
        with mock.patch('psutil._pslinux.open', create=True) as m:
            self.assertIsNone(psutil._pslinux.cpu_count_physical())
            assert m.called

    @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
    def test_cpu_freq_no_result(self):
        with mock.patch("psutil._pslinux.glob.glob", return_value=[]):
            self.assertIsNone(psutil.cpu_freq())

    @unittest.skipIf(TRAVIS, "fails on Travis")
    @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
    def test_cpu_freq_use_second_file(self):
        # https://github.com/giampaolo/psutil/issues/981
        def glob_mock(pattern):
            if pattern.startswith("/sys/devices/system/cpu/cpufreq/policy"):
                flags.append(None)
                return []
            else:
                flags.append(None)
                return orig_glob(pattern)

        flags = []
        orig_glob = glob.glob
        with mock.patch("psutil._pslinux.glob.glob", side_effect=glob_mock,
                        create=True):
            assert psutil.cpu_freq()
            self.assertEqual(len(flags), 2)

    @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
    def test_cpu_freq_emulate_data(self):
        def open_mock(name, *args, **kwargs):
            if name.endswith('/scaling_cur_freq'):
                return io.BytesIO(b"500000")
            elif name.endswith('/scaling_min_freq'):
                return io.BytesIO(b"600000")
            elif name.endswith('/scaling_max_freq'):
                return io.BytesIO(b"700000")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            with mock.patch(
                    'glob.glob',
                    return_value=['/sys/devices/system/cpu/cpufreq/policy0']):
                freq = psutil.cpu_freq()
                self.assertEqual(freq.current, 500.0)
                self.assertEqual(freq.min, 600.0)
                self.assertEqual(freq.max, 700.0)

    @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
    def test_cpu_freq_emulate_multi_cpu(self):
        def open_mock(name, *args, **kwargs):
            if name.endswith('/scaling_cur_freq'):
                return io.BytesIO(b"100000")
            elif name.endswith('/scaling_min_freq'):
                return io.BytesIO(b"200000")
            elif name.endswith('/scaling_max_freq'):
                return io.BytesIO(b"300000")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        policies = ['/sys/devices/system/cpu/cpufreq/policy0',
                    '/sys/devices/system/cpu/cpufreq/policy1',
                    '/sys/devices/system/cpu/cpufreq/policy2']
        with mock.patch(patch_point, side_effect=open_mock):
            with mock.patch('glob.glob', return_value=policies):
                freq = psutil.cpu_freq()
                self.assertEqual(freq.current, 100.0)
                self.assertEqual(freq.min, 200.0)
                self.assertEqual(freq.max, 300.0)

    @unittest.skipIf(TRAVIS, "fails on Travis")
    @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
    def test_cpu_freq_no_scaling_cur_freq_file(self):
        # See: https://github.com/giampaolo/psutil/issues/1071
        def open_mock(name, *args, **kwargs):
            if name.endswith('/scaling_cur_freq'):
                raise IOError(errno.ENOENT, "")
            elif name.endswith('/cpuinfo_cur_freq'):
                return io.BytesIO(b"200000")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        policies = ['/sys/devices/system/cpu/cpufreq/policy0',
                    '/sys/devices/system/cpu/cpufreq/policy1',
                    '/sys/devices/system/cpu/cpufreq/policy2']

        with mock.patch(patch_point, side_effect=open_mock):
            with mock.patch('glob.glob', return_value=policies):
                freq = psutil.cpu_freq()
                self.assertEqual(freq.current, 200)

        # Also test that NotImplementedError is raised in case no
        # current freq file is present.

        def open_mock(name, *args, **kwargs):
            if name.endswith('/scaling_cur_freq'):
                raise IOError(errno.ENOENT, "")
            elif name.endswith('/cpuinfo_cur_freq'):
                raise IOError(errno.ENOENT, "")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            with mock.patch('glob.glob', return_value=policies):
                self.assertRaises(NotImplementedError, psutil.cpu_freq)


# =====================================================================
# --- system CPU stats
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemCPUStats(unittest.TestCase):

    @unittest.skipIf(TRAVIS, "fails on Travis")
    def test_ctx_switches(self):
        vmstat_value = vmstat("context switches")
        psutil_value = psutil.cpu_stats().ctx_switches
        self.assertAlmostEqual(vmstat_value, psutil_value, delta=500)

    @unittest.skipIf(TRAVIS, "fails on Travis")
    def test_interrupts(self):
        vmstat_value = vmstat("interrupts")
        psutil_value = psutil.cpu_stats().interrupts
        self.assertAlmostEqual(vmstat_value, psutil_value, delta=500)


# =====================================================================
# --- system network
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemNetwork(unittest.TestCase):

    def test_net_if_addrs_ips(self):
        for name, addrs in psutil.net_if_addrs().items():
            for addr in addrs:
                if addr.family == psutil.AF_LINK:
                    self.assertEqual(addr.address, get_mac_address(name))
                elif addr.family == socket.AF_INET:
                    self.assertEqual(addr.address, get_ipv4_address(name))
                # TODO: test for AF_INET6 family

    def test_net_if_stats(self):
        for name, stats in psutil.net_if_stats().items():
            try:
                out = sh("ifconfig %s" % name)
            except RuntimeError:
                pass
            else:
                # Not always reliable.
                # self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
                self.assertEqual(stats.mtu,
                                 int(re.findall(r'(?i)MTU[: ](\d+)', out)[0]))

    @retry_before_failing()
    def test_net_io_counters(self):
        def ifconfig(nic):
            ret = {}
            out = sh("ifconfig %s" % name)
            ret['packets_recv'] = int(
                re.findall(r'RX packets[: ](\d+)', out)[0])
            ret['packets_sent'] = int(
                re.findall(r'TX packets[: ](\d+)', out)[0])
            ret['errin'] = int(re.findall(r'errors[: ](\d+)', out)[0])
            ret['errout'] = int(re.findall(r'errors[: ](\d+)', out)[1])
            ret['dropin'] = int(re.findall(r'dropped[: ](\d+)', out)[0])
            ret['dropout'] = int(re.findall(r'dropped[: ](\d+)', out)[1])
            ret['bytes_recv'] = int(
                re.findall(r'RX (?:packets \d+ +)?bytes[: ](\d+)', out)[0])
            ret['bytes_sent'] = int(
                re.findall(r'TX (?:packets \d+ +)?bytes[: ](\d+)', out)[0])
            return ret

        nio = psutil.net_io_counters(pernic=True, nowrap=False)
        for name, stats in nio.items():
            try:
                ifconfig_ret = ifconfig(name)
            except RuntimeError:
                continue
            self.assertAlmostEqual(
                stats.bytes_recv, ifconfig_ret['bytes_recv'], delta=1024 * 5)
            self.assertAlmostEqual(
                stats.bytes_sent, ifconfig_ret['bytes_sent'], delta=1024 * 5)
            self.assertAlmostEqual(
                stats.packets_recv, ifconfig_ret['packets_recv'], delta=1024)
            self.assertAlmostEqual(
                stats.packets_sent, ifconfig_ret['packets_sent'], delta=1024)
            self.assertAlmostEqual(
                stats.errin, ifconfig_ret['errin'], delta=10)
            self.assertAlmostEqual(
                stats.errout, ifconfig_ret['errout'], delta=10)
            self.assertAlmostEqual(
                stats.dropin, ifconfig_ret['dropin'], delta=10)
            self.assertAlmostEqual(
                stats.dropout, ifconfig_ret['dropout'], delta=10)

    @unittest.skipIf(not which('ip'), "'ip' utility not available")
    @unittest.skipIf(TRAVIS, "skipped on Travis")
    def test_net_if_names(self):
        out = sh("ip addr").strip()
        nics = [x for x in psutil.net_if_addrs().keys() if ':' not in x]
        found = 0
        for line in out.split('\n'):
            line = line.strip()
            if re.search(r"^\d+:", line):
                found += 1
                name = line.split(':')[1].strip()
                self.assertIn(name, nics)
        self.assertEqual(len(nics), found, msg="%s\n---\n%s" % (
            pprint.pformat(nics), out))

    @mock.patch('psutil._pslinux.socket.inet_ntop', side_effect=ValueError)
    @mock.patch('psutil._pslinux.supports_ipv6', return_value=False)
    def test_net_connections_ipv6_unsupported(self, supports_ipv6, inet_ntop):
        # see: https://github.com/giampaolo/psutil/issues/623
        try:
            s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
            self.addCleanup(s.close)
            s.bind(("::1", 0))
        except socket.error:
            pass
        psutil.net_connections(kind='inet6')

    def test_net_connections_mocked(self):
        def open_mock(name, *args, **kwargs):
            if name == '/proc/net/unix':
                return io.StringIO(textwrap.dedent(u"""\
                    0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
                    0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
                    0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
                    000000000000000000000000000000000000000000000000000000
                    """))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            psutil.net_connections(kind='unix')
            assert m.called


# =====================================================================
# --- system disk
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestSystemDisks(unittest.TestCase):

    @unittest.skipIf(not hasattr(os, 'statvfs'), "os.statvfs() not available")
    @skip_on_not_implemented()
    def test_disk_partitions_and_usage(self):
        # test psutil.disk_usage() and psutil.disk_partitions()
        # against "df -a"
        def df(path):
            out = sh('df -P -B 1 "%s"' % path).strip()
            lines = out.split('\n')
            lines.pop(0)
            line = lines.pop(0)
            dev, total, used, free = line.split()[:4]
            if dev == 'none':
                dev = ''
            total, used, free = int(total), int(used), int(free)
            return dev, total, used, free

        for part in psutil.disk_partitions(all=False):
            usage = psutil.disk_usage(part.mountpoint)
            dev, total, used, free = df(part.mountpoint)
            self.assertEqual(usage.total, total)
            # 10 MB tollerance
            if abs(usage.free - free) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.free, free))
            if abs(usage.used - used) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.used, used))

    def test_disk_partitions_mocked(self):
        # Test that ZFS partitions are returned.
        with open("/proc/filesystems", "r") as f:
            data = f.read()
        if 'zfs' in data:
            for part in psutil.disk_partitions():
                if part.fstype == 'zfs':
                    break
            else:
                self.fail("couldn't find any ZFS partition")
        else:
            # No ZFS partitions on this system. Let's fake one.
            fake_file = io.StringIO(u("nodev\tzfs\n"))
            with mock.patch('psutil._pslinux.open',
                            return_value=fake_file, create=True) as m1:
                with mock.patch(
                        'psutil._pslinux.cext.disk_partitions',
                        return_value=[('/dev/sdb3', '/', 'zfs', 'rw')]) as m2:
                    ret = psutil.disk_partitions()
                    assert m1.called
                    assert m2.called
                    assert ret
                    self.assertEqual(ret[0].fstype, 'zfs')

    def test_disk_io_counters_kernel_2_4_mocked(self):
        # Tests /proc/diskstats parsing format for 2.4 kernels, see:
        # https://github.com/giampaolo/psutil/issues/767
        def open_mock(name, *args, **kwargs):
            if name == '/proc/partitions':
                return io.StringIO(textwrap.dedent(u"""\
                    major minor  #blocks  name

                       8        0  488386584 hda
                    """))
            elif name == '/proc/diskstats':
                return io.StringIO(
                    u("   3     0   1 hda 2 3 4 5 6 7 8 9 10 11 12"))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            ret = psutil.disk_io_counters(nowrap=False)
            assert m.called
            self.assertEqual(ret.read_count, 1)
            self.assertEqual(ret.read_merged_count, 2)
            self.assertEqual(ret.read_bytes, 3 * SECTOR_SIZE)
            self.assertEqual(ret.read_time, 4)
            self.assertEqual(ret.write_count, 5)
            self.assertEqual(ret.write_merged_count, 6)
            self.assertEqual(ret.write_bytes, 7 * SECTOR_SIZE)
            self.assertEqual(ret.write_time, 8)
            self.assertEqual(ret.busy_time, 10)

    def test_disk_io_counters_kernel_2_6_full_mocked(self):
        # Tests /proc/diskstats parsing format for 2.6 kernels,
        # lines reporting all metrics:
        # https://github.com/giampaolo/psutil/issues/767
        def open_mock(name, *args, **kwargs):
            if name == '/proc/partitions':
                return io.StringIO(textwrap.dedent(u"""\
                    major minor  #blocks  name

                       8        0  488386584 hda
                    """))
            elif name == '/proc/diskstats':
                return io.StringIO(
                    u("   3    0   hda 1 2 3 4 5 6 7 8 9 10 11"))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            ret = psutil.disk_io_counters(nowrap=False)
            assert m.called
            self.assertEqual(ret.read_count, 1)
            self.assertEqual(ret.read_merged_count, 2)
            self.assertEqual(ret.read_bytes, 3 * SECTOR_SIZE)
            self.assertEqual(ret.read_time, 4)
            self.assertEqual(ret.write_count, 5)
            self.assertEqual(ret.write_merged_count, 6)
            self.assertEqual(ret.write_bytes, 7 * SECTOR_SIZE)
            self.assertEqual(ret.write_time, 8)
            self.assertEqual(ret.busy_time, 10)

    def test_disk_io_counters_kernel_2_6_limited_mocked(self):
        # Tests /proc/diskstats parsing format for 2.6 kernels,
        # where one line of /proc/partitions return a limited
        # amount of metrics when it bumps into a partition
        # (instead of a disk). See:
        # https://github.com/giampaolo/psutil/issues/767
        def open_mock(name, *args, **kwargs):
            if name == '/proc/partitions':
                return io.StringIO(textwrap.dedent(u"""\
                    major minor  #blocks  name

                       8        0  488386584 hda
                    """))
            elif name == '/proc/diskstats':
                return io.StringIO(
                    u("   3    1   hda 1 2 3 4"))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            ret = psutil.disk_io_counters(nowrap=False)
            assert m.called
            self.assertEqual(ret.read_count, 1)
            self.assertEqual(ret.read_bytes, 2 * SECTOR_SIZE)
            self.assertEqual(ret.write_count, 3)
            self.assertEqual(ret.write_bytes, 4 * SECTOR_SIZE)

            self.assertEqual(ret.read_merged_count, 0)
            self.assertEqual(ret.read_time, 0)
            self.assertEqual(ret.write_merged_count, 0)
            self.assertEqual(ret.write_time, 0)
            self.assertEqual(ret.busy_time, 0)


# =====================================================================
# --- misc
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestMisc(unittest.TestCase):

    def test_boot_time(self):
        vmstat_value = vmstat('boot time')
        psutil_value = psutil.boot_time()
        self.assertEqual(int(vmstat_value), int(psutil_value))

    @mock.patch('psutil.traceback.print_exc')
    def test_no_procfs_on_import(self, tb):
        my_procfs = tempfile.mkdtemp()

        with open(os.path.join(my_procfs, 'stat'), 'w') as f:
            f.write('cpu   0 0 0 0 0 0 0 0 0 0\n')
            f.write('cpu0  0 0 0 0 0 0 0 0 0 0\n')
            f.write('cpu1  0 0 0 0 0 0 0 0 0 0\n')

        try:
            orig_open = open

            def open_mock(name, *args, **kwargs):
                if name.startswith('/proc'):
                    raise IOError(errno.ENOENT, 'rejecting access for test')
                return orig_open(name, *args, **kwargs)

            patch_point = 'builtins.open' if PY3 else '__builtin__.open'
            with mock.patch(patch_point, side_effect=open_mock):
                reload_module(psutil)
                assert tb.called

                self.assertRaises(IOError, psutil.cpu_times)
                self.assertRaises(IOError, psutil.cpu_times, percpu=True)
                self.assertRaises(IOError, psutil.cpu_percent)
                self.assertRaises(IOError, psutil.cpu_percent, percpu=True)
                self.assertRaises(IOError, psutil.cpu_times_percent)
                self.assertRaises(
                    IOError, psutil.cpu_times_percent, percpu=True)

                psutil.PROCFS_PATH = my_procfs

                self.assertEqual(psutil.cpu_percent(), 0)
                self.assertEqual(sum(psutil.cpu_times_percent()), 0)

                # since we don't know the number of CPUs at import time,
                # we awkwardly say there are none until the second call
                per_cpu_percent = psutil.cpu_percent(percpu=True)
                self.assertEqual(sum(per_cpu_percent), 0)

                # ditto awkward length
                per_cpu_times_percent = psutil.cpu_times_percent(percpu=True)
                self.assertEqual(sum(map(sum, per_cpu_times_percent)), 0)

                # much user, very busy
                with open(os.path.join(my_procfs, 'stat'), 'w') as f:
                    f.write('cpu   1 0 0 0 0 0 0 0 0 0\n')
                    f.write('cpu0  1 0 0 0 0 0 0 0 0 0\n')
                    f.write('cpu1  1 0 0 0 0 0 0 0 0 0\n')

                self.assertNotEqual(psutil.cpu_percent(), 0)
                self.assertNotEqual(
                    sum(psutil.cpu_percent(percpu=True)), 0)
                self.assertNotEqual(sum(psutil.cpu_times_percent()), 0)
                self.assertNotEqual(
                    sum(map(sum, psutil.cpu_times_percent(percpu=True))), 0)
        finally:
            shutil.rmtree(my_procfs)
            reload_module(psutil)

        self.assertEqual(psutil.PROCFS_PATH, '/proc')

    def test_boot_time_mocked(self):
        with mock.patch('psutil._pslinux.open', create=True) as m:
            self.assertRaises(
                RuntimeError,
                psutil._pslinux.boot_time)
            assert m.called

    def test_users_mocked(self):
        # Make sure ':0' and ':0.0' (returned by C ext) are converted
        # to 'localhost'.
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', ':0.0',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'localhost')
            assert m.called
        # ...otherwise it should be returned as-is
        with mock.patch('psutil._pslinux.cext.users',
                        return_value=[('giampaolo', 'pts/2', 'foo',
                                       1436573184.0, True, 2)]) as m:
            self.assertEqual(psutil.users()[0].host, 'foo')
            assert m.called

    def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir)

    def test_sector_size_mock(self):
        # Test SECTOR_SIZE fallback in case 'hw_sector_size' file
        # does not exist.
        def open_mock(name, *args, **kwargs):
            if PY3 and isinstance(name, bytes):
                name = name.decode()
            if "hw_sector_size" in name:
                flag.append(None)
                raise IOError(errno.ENOENT, '')
            else:
                return orig_open(name, *args, **kwargs)

        flag = []
        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            psutil.disk_io_counters()
            assert flag

    def test_issue_687(self):
        # In case of thread ID:
        # - pid_exists() is supposed to return False
        # - Process(tid) is supposed to work
        # - pids() should not return the TID
        # See: https://github.com/giampaolo/psutil/issues/687
        t = ThreadTask()
        t.start()
        try:
            p = psutil.Process()
            tid = p.threads()[1].id
            assert not psutil.pid_exists(tid), tid
            pt = psutil.Process(tid)
            pt.as_dict()
            self.assertNotIn(tid, psutil.pids())
        finally:
            t.stop()

    def test_pid_exists_no_proc_status(self):
        # Internally pid_exists relies on /proc/{pid}/status.
        # Emulate a case where this file is empty in which case
        # psutil is supposed to fall back on using pids().
        def open_mock(name, *args, **kwargs):
            if name == "/proc/%s/status" % os.getpid():
                return io.StringIO(u(""))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            assert psutil.pid_exists(os.getpid())


# =====================================================================
# --- sensors
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
@unittest.skipIf(not HAS_BATTERY, "no battery")
class TestSensorsBattery(unittest.TestCase):

    @unittest.skipIf(not which("acpi"), "acpi utility not available")
    def test_percent(self):
        out = sh("acpi -b")
        acpi_value = int(out.split(",")[1].strip().replace('%', ''))
        psutil_value = psutil.sensors_battery().percent
        self.assertAlmostEqual(acpi_value, psutil_value, delta=1)

    @unittest.skipIf(not which("acpi"), "acpi utility not available")
    def test_power_plugged(self):
        out = sh("acpi -b")
        if 'unknown' in out.lower():
            return unittest.skip("acpi output not reliable")
        if 'discharging at zero rate' in out:
            plugged = True
        else:
            plugged = "Charging" in out.split('\n')[0]
        self.assertEqual(psutil.sensors_battery().power_plugged, plugged)

    def test_emulate_power_plugged(self):
        # Pretend the AC power cable is connected.
        def open_mock(name, *args, **kwargs):
            if name.endswith("AC0/online") or name.endswith("AC/online"):
                return io.BytesIO(b"1")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertEqual(psutil.sensors_battery().power_plugged, True)
            self.assertEqual(
                psutil.sensors_battery().secsleft, psutil.POWER_TIME_UNLIMITED)
            assert m.called

    def test_emulate_power_plugged_2(self):
        # Same as above but pretend /AC0/online does not exist in which
        # case code relies on /status file.
        def open_mock(name, *args, **kwargs):
            if name.endswith("AC0/online") or name.endswith("AC/online"):
                raise IOError(errno.ENOENT, "")
            elif name.endswith("/status"):
                return io.StringIO(u("charging"))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertEqual(psutil.sensors_battery().power_plugged, True)
            assert m.called

    def test_emulate_power_not_plugged(self):
        # Pretend the AC power cable is not connected.
        def open_mock(name, *args, **kwargs):
            if name.endswith("AC0/online") or name.endswith("AC/online"):
                return io.BytesIO(b"0")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertEqual(psutil.sensors_battery().power_plugged, False)
            assert m.called

    def test_emulate_power_not_plugged_2(self):
        # Same as above but pretend /AC0/online does not exist in which
        # case code relies on /status file.
        def open_mock(name, *args, **kwargs):
            if name.endswith("AC0/online") or name.endswith("AC/online"):
                raise IOError(errno.ENOENT, "")
            elif name.endswith("/status"):
                return io.StringIO(u("discharging"))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertEqual(psutil.sensors_battery().power_plugged, False)
            assert m.called

    def test_emulate_power_undetermined(self):
        # Pretend we can't know whether the AC power cable not
        # connected (assert fallback to False).
        def open_mock(name, *args, **kwargs):
            if name.startswith("/sys/class/power_supply/AC0/online") or \
                    name.startswith("/sys/class/power_supply/AC/online"):
                raise IOError(errno.ENOENT, "")
            elif name.startswith("/sys/class/power_supply/BAT0/status"):
                return io.BytesIO(b"???")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertIsNone(psutil.sensors_battery().power_plugged)
            assert m.called

    def test_emulate_no_base_files(self):
        # Emulate a case where base metrics files are not present,
        # in which case we're supposed to get None.
        def open_mock(name, *args, **kwargs):
            if name.startswith("/sys/class/power_supply/BAT0/energy_now") or \
                    name.startswith("/sys/class/power_supply/BAT0/charge_now"):
                raise IOError(errno.ENOENT, "")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertIsNone(psutil.sensors_battery())
            assert m.called

    def test_emulate_energy_full_0(self):
        # Emulate a case where energy_full files returns 0.
        def open_mock(name, *args, **kwargs):
            if name.startswith("/sys/class/power_supply/BAT0/energy_full"):
                return io.BytesIO(b"0")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertEqual(psutil.sensors_battery().percent, 0)
            assert m.called

    def test_emulate_energy_full_not_avail(self):
        # Emulate a case where energy_full file does not exist.
        # Expected fallback on /capacity.
        def open_mock(name, *args, **kwargs):
            energy_full = "/sys/class/power_supply/BAT0/energy_full"
            charge_full = "/sys/class/power_supply/BAT0/charge_full"
            if name.startswith(energy_full) or name.startswith(charge_full):
                raise IOError(errno.ENOENT, "")
            elif name.startswith("/sys/class/power_supply/BAT0/capacity"):
                return io.BytesIO(b"88")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertEqual(psutil.sensors_battery().percent, 88)
            assert m.called

    def test_emulate_no_ac0_online(self):
        # Emulate a case where /AC0/online file does not exist.
        def path_exists_mock(name):
            if name.startswith("/sys/class/power_supply/AC0/online"):
                return False
            else:
                return orig_path_exists(name)

        orig_path_exists = os.path.exists
        with mock.patch("psutil._pslinux.os.path.exists",
                        side_effect=path_exists_mock) as m:
            psutil.sensors_battery()
            assert m.called

    def test_emulate_no_power(self):
        # Emulate a case where /AC0/online file nor /BAT0/status exist.
        def open_mock(name, *args, **kwargs):
            if name.startswith("/sys/class/power_supply/AC/online") or \
                    name.startswith("/sys/class/power_supply/AC0/online") or \
                    name.startswith("/sys/class/power_supply/BAT0/status"):
                raise IOError(errno.ENOENT, "")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            self.assertIsNone(psutil.sensors_battery().power_plugged)
            assert m.called


@unittest.skipIf(not LINUX, "LINUX only")
class TestSensorsTemperatures(unittest.TestCase):

    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    def test_emulate_eio_error(self):
        def open_mock(name, *args, **kwargs):
            if name.endswith("_input"):
                raise OSError(errno.EIO, "")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            with warnings.catch_warnings(record=True) as ws:
                self.assertEqual(psutil.sensors_temperatures(), {})
                assert m.called
                self.assertIn("ignoring", str(ws[0].message))

    def test_emulate_data(self):
        def open_mock(name, *args, **kwargs):
            if name.endswith('/name'):
                return io.StringIO(u("name"))
            elif name.endswith('/temp1_label'):
                return io.StringIO(u("label"))
            elif name.endswith('/temp1_input'):
                return io.BytesIO(b"30000")
            elif name.endswith('/temp1_max'):
                return io.BytesIO(b"40000")
            elif name.endswith('/temp1_crit'):
                return io.BytesIO(b"50000")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            with mock.patch('glob.glob',
                            return_value=['/sys/class/hwmon/hwmon0/temp1']):
                temp = psutil.sensors_temperatures()['name'][0]
                self.assertEqual(temp.label, 'label')
                self.assertEqual(temp.current, 30.0)
                self.assertEqual(temp.high, 40.0)
                self.assertEqual(temp.critical, 50.0)


@unittest.skipIf(not LINUX, "LINUX only")
class TestSensorsFans(unittest.TestCase):

    def test_emulate_data(self):
        def open_mock(name, *args, **kwargs):
            if name.endswith('/name'):
                return io.StringIO(u("name"))
            elif name.endswith('/fan1_label'):
                return io.StringIO(u("label"))
            elif name.endswith('/fan1_input'):
                return io.StringIO(u("2000"))
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            with mock.patch('glob.glob',
                            return_value=['/sys/class/hwmon/hwmon2/fan1']):
                fan = psutil.sensors_fans()['name'][0]
                self.assertEqual(fan.label, 'label')
                self.assertEqual(fan.current, 2000)


# =====================================================================
# --- test process
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestProcess(unittest.TestCase):

    def setUp(self):
        safe_rmpath(TESTFN)

    tearDown = setUp

    def test_memory_full_info(self):
        src = textwrap.dedent("""
            import time
            with open("%s", "w") as f:
                time.sleep(10)
            """ % TESTFN)
        sproc = pyrun(src)
        self.addCleanup(reap_children)
        call_until(lambda: os.listdir('.'), "'%s' not in ret" % TESTFN)
        p = psutil.Process(sproc.pid)
        time.sleep(.1)
        mem = p.memory_full_info()
        maps = p.memory_maps(grouped=False)
        self.assertAlmostEqual(
            mem.uss, sum([x.private_dirty + x.private_clean for x in maps]),
            delta=4096)
        self.assertAlmostEqual(
            mem.pss, sum([x.pss for x in maps]), delta=4096)
        self.assertAlmostEqual(
            mem.swap, sum([x.swap for x in maps]), delta=4096)

    # On PYPY file descriptors are not closed fast enough.
    @unittest.skipIf(PYPY, "unreliable on PYPY")
    def test_open_files_mode(self):
        def get_test_file():
            p = psutil.Process()
            giveup_at = time.time() + 2
            while True:
                for file in p.open_files():
                    if file.path == os.path.abspath(TESTFN):
                        return file
                    elif time.time() > giveup_at:
                        break
            raise RuntimeError("timeout looking for test file")

        #
        with open(TESTFN, "w"):
            self.assertEqual(get_test_file().mode, "w")
        with open(TESTFN, "r"):
            self.assertEqual(get_test_file().mode, "r")
        with open(TESTFN, "a"):
            self.assertEqual(get_test_file().mode, "a")
        #
        with open(TESTFN, "r+"):
            self.assertEqual(get_test_file().mode, "r+")
        with open(TESTFN, "w+"):
            self.assertEqual(get_test_file().mode, "r+")
        with open(TESTFN, "a+"):
            self.assertEqual(get_test_file().mode, "a+")
        # note: "x" bit is not supported
        if PY3:
            safe_rmpath(TESTFN)
            with open(TESTFN, "x"):
                self.assertEqual(get_test_file().mode, "w")
            safe_rmpath(TESTFN)
            with open(TESTFN, "x+"):
                self.assertEqual(get_test_file().mode, "r+")

    def test_open_files_file_gone(self):
        # simulates a file which gets deleted during open_files()
        # execution
        p = psutil.Process()
        files = p.open_files()
        with tempfile.NamedTemporaryFile():
            # give the kernel some time to see the new file
            call_until(p.open_files, "len(ret) != %i" % len(files))
            with mock.patch('psutil._pslinux.os.readlink',
                            side_effect=OSError(errno.ENOENT, "")) as m:
                files = p.open_files()
                assert not files
                assert m.called
            # also simulate the case where os.readlink() returns EINVAL
            # in which case psutil is supposed to 'continue'
            with mock.patch('psutil._pslinux.os.readlink',
                            side_effect=OSError(errno.EINVAL, "")) as m:
                self.assertEqual(p.open_files(), [])
                assert m.called

    def test_open_files_fd_gone(self):
        # Simulate a case where /proc/{pid}/fdinfo/{fd} disappears
        # while iterating through fds.
        # https://travis-ci.org/giampaolo/psutil/jobs/225694530
        p = psutil.Process()
        files = p.open_files()
        with tempfile.NamedTemporaryFile():
            # give the kernel some time to see the new file
            call_until(p.open_files, "len(ret) != %i" % len(files))
            patch_point = 'builtins.open' if PY3 else '__builtin__.open'
            with mock.patch(patch_point,
                            side_effect=IOError(errno.ENOENT, "")) as m:
                files = p.open_files()
                assert not files
                assert m.called

    # --- mocked tests

    def test_terminal_mocked(self):
        with mock.patch('psutil._pslinux._psposix.get_terminal_map',
                        return_value={}) as m:
            self.assertIsNone(psutil._pslinux.Process(os.getpid()).terminal())
            assert m.called

    # TODO: re-enable this test.
    # def test_num_ctx_switches_mocked(self):
    #     with mock.patch('psutil._pslinux.open', create=True) as m:
    #         self.assertRaises(
    #             NotImplementedError,
    #             psutil._pslinux.Process(os.getpid()).num_ctx_switches)
    #         assert m.called

    def test_cmdline_mocked(self):
        # see: https://github.com/giampaolo/psutil/issues/639
        p = psutil.Process()
        fake_file = io.StringIO(u('foo\x00bar\x00'))
        with mock.patch('psutil._pslinux.open',
                        return_value=fake_file, create=True) as m:
            self.assertEqual(p.cmdline(), ['foo', 'bar'])
            assert m.called
        fake_file = io.StringIO(u('foo\x00bar\x00\x00'))
        with mock.patch('psutil._pslinux.open',
                        return_value=fake_file, create=True) as m:
            self.assertEqual(p.cmdline(), ['foo', 'bar', ''])
            assert m.called

    def test_cmdline_spaces_mocked(self):
        # see: https://github.com/giampaolo/psutil/issues/1179
        p = psutil.Process()
        fake_file = io.StringIO(u('foo bar '))
        with mock.patch('psutil._pslinux.open',
                        return_value=fake_file, create=True) as m:
            self.assertEqual(p.cmdline(), ['foo', 'bar'])
            assert m.called
        fake_file = io.StringIO(u('foo bar  '))
        with mock.patch('psutil._pslinux.open',
                        return_value=fake_file, create=True) as m:
            self.assertEqual(p.cmdline(), ['foo', 'bar', ''])
            assert m.called

    def test_readlink_path_deleted_mocked(self):
        with mock.patch('psutil._pslinux.os.readlink',
                        return_value='/home/foo (deleted)'):
            self.assertEqual(psutil.Process().exe(), "/home/foo")
            self.assertEqual(psutil.Process().cwd(), "/home/foo")

    def test_threads_mocked(self):
        # Test the case where os.listdir() returns a file (thread)
        # which no longer exists by the time we open() it (race
        # condition). threads() is supposed to ignore that instead
        # of raising NSP.
        def open_mock(name, *args, **kwargs):
            if name.startswith('/proc/%s/task' % os.getpid()):
                raise IOError(errno.ENOENT, "")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            ret = psutil.Process().threads()
            assert m.called
            self.assertEqual(ret, [])

        # ...but if it bumps into something != ENOENT we want an
        # exception.
        def open_mock(name, *args, **kwargs):
            if name.startswith('/proc/%s/task' % os.getpid()):
                raise IOError(errno.EPERM, "")
            else:
                return orig_open(name, *args, **kwargs)

        with mock.patch(patch_point, side_effect=open_mock):
            self.assertRaises(psutil.AccessDenied, psutil.Process().threads)

    def test_exe_mocked(self):
        with mock.patch('psutil._pslinux.readlink',
                        side_effect=OSError(errno.ENOENT, "")) as m1:
            with mock.patch('psutil.Process.cmdline',
                            side_effect=psutil.AccessDenied(0, "")) as m2:
                # No such file error; might be raised also if /proc/pid/exe
                # path actually exists for system processes with low pids
                # (about 0-20). In this case psutil is supposed to return
                # an empty string.
                ret = psutil.Process().exe()
                assert m1.called
                assert m2.called
                self.assertEqual(ret, "")

                # ...but if /proc/pid no longer exist we're supposed to treat
                # it as an alias for zombie process
                with mock.patch('psutil._pslinux.os.path.lexists',
                                return_value=False):
                    self.assertRaises(
                        psutil.ZombieProcess, psutil.Process().exe)

    def test_issue_1014(self):
        # Emulates a case where smaps file does not exist. In this case
        # wrap_exception decorator should not raise NoSuchProcess.
        def open_mock(name, *args, **kwargs):
            if name.startswith('/proc/%s/smaps' % os.getpid()):
                raise IOError(errno.ENOENT, "")
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock) as m:
            p = psutil.Process()
            with self.assertRaises(IOError) as err:
                p.memory_maps()
            self.assertEqual(err.exception.errno, errno.ENOENT)
            assert m.called

    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit_zombie(self):
        # Emulate a case where rlimit() raises ENOSYS, which may
        # happen in case of zombie process:
        # https://travis-ci.org/giampaolo/psutil/jobs/51368273
        with mock.patch("psutil._pslinux.cext.linux_prlimit",
                        side_effect=OSError(errno.ENOSYS, "")) as m:
            p = psutil.Process()
            p.name()
            with self.assertRaises(psutil.ZombieProcess) as exc:
                p.rlimit(psutil.RLIMIT_NOFILE)
            assert m.called
        self.assertEqual(exc.exception.pid, p.pid)
        self.assertEqual(exc.exception.name, p.name())

    def test_cwd_zombie(self):
        with mock.patch("psutil._pslinux.os.readlink",
                        side_effect=OSError(errno.ENOENT, "")) as m:
            p = psutil.Process()
            p.name()
            with self.assertRaises(psutil.ZombieProcess) as exc:
                p.cwd()
            assert m.called
        self.assertEqual(exc.exception.pid, p.pid)
        self.assertEqual(exc.exception.name, p.name())

    def test_stat_file_parsing(self):
        from psutil._pslinux import CLOCK_TICKS

        def open_mock(name, *args, **kwargs):
            if name.startswith('/proc/%s/stat' % os.getpid()):
                args = [
                    "0",      # pid
                    "(cat)",  # name
                    "Z",      # status
                    "1",      # ppid
                    "0",      # pgrp
                    "0",      # session
                    "0",      # tty
                    "0",      # tpgid
                    "0",      # flags
                    "0",      # minflt
                    "0",      # cminflt
                    "0",      # majflt
                    "0",      # cmajflt
                    "2",      # utime
                    "3",      # stime
                    "4",      # cutime
                    "5",      # cstime
                    "0",      # priority
                    "0",      # nice
                    "0",      # num_threads
                    "0",      # itrealvalue
                    "6",      # starttime
                    "0",      # vsize
                    "0",      # rss
                    "0",      # rsslim
                    "0",      # startcode
                    "0",      # endcode
                    "0",      # startstack
                    "0",      # kstkesp
                    "0",      # kstkeip
                    "0",      # signal
                    "0",      # blocked
                    "0",      # sigignore
                    "0",      # sigcatch
                    "0",      # wchan
                    "0",      # nswap
                    "0",      # cnswap
                    "0",      # exit_signal
                    "6",      # processor
                ]
                return io.BytesIO(" ".join(args).encode())
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            p = psutil.Process()
            self.assertEqual(p.name(), 'cat')
            self.assertEqual(p.status(), psutil.STATUS_ZOMBIE)
            self.assertEqual(p.ppid(), 1)
            self.assertEqual(
                p.create_time(), 6 / CLOCK_TICKS + psutil.boot_time())
            cpu = p.cpu_times()
            self.assertEqual(cpu.user, 2 / CLOCK_TICKS)
            self.assertEqual(cpu.system, 3 / CLOCK_TICKS)
            self.assertEqual(cpu.children_user, 4 / CLOCK_TICKS)
            self.assertEqual(cpu.children_system, 5 / CLOCK_TICKS)
            self.assertEqual(p.cpu_num(), 6)

    def test_status_file_parsing(self):
        def open_mock(name, *args, **kwargs):
            if name.startswith('/proc/%s/status' % os.getpid()):
                return io.BytesIO(textwrap.dedent("""\
                    Uid:\t1000\t1001\t1002\t1003
                    Gid:\t1004\t1005\t1006\t1007
                    Threads:\t66
                    Cpus_allowed:\tf
                    Cpus_allowed_list:\t0-7
                    voluntary_ctxt_switches:\t12
                    nonvoluntary_ctxt_switches:\t13""").encode())
            else:
                return orig_open(name, *args, **kwargs)

        orig_open = open
        patch_point = 'builtins.open' if PY3 else '__builtin__.open'
        with mock.patch(patch_point, side_effect=open_mock):
            p = psutil.Process()
            self.assertEqual(p.num_ctx_switches().voluntary, 12)
            self.assertEqual(p.num_ctx_switches().involuntary, 13)
            self.assertEqual(p.num_threads(), 66)
            uids = p.uids()
            self.assertEqual(uids.real, 1000)
            self.assertEqual(uids.effective, 1001)
            self.assertEqual(uids.saved, 1002)
            gids = p.gids()
            self.assertEqual(gids.real, 1004)
            self.assertEqual(gids.effective, 1005)
            self.assertEqual(gids.saved, 1006)
            self.assertEqual(p._proc._get_eligible_cpus(), list(range(0, 8)))


@unittest.skipIf(not LINUX, "LINUX only")
class TestProcessAgainstStatus(unittest.TestCase):
    """/proc/pid/stat and /proc/pid/status have many values in common.
    Whenever possible, psutil uses /proc/pid/stat (it's faster).
    For all those cases we check that the value found in
    /proc/pid/stat (by psutil) matches the one found in
    /proc/pid/status.
    """

    @classmethod
    def setUpClass(cls):
        cls.proc = psutil.Process()

    def read_status_file(self, linestart):
        with psutil._psplatform.open_text(
                '/proc/%s/status' % self.proc.pid) as f:
            for line in f:
                line = line.strip()
                if line.startswith(linestart):
                    value = line.partition('\t')[2]
                    try:
                        return int(value)
                    except ValueError:
                        return value
            raise ValueError("can't find %r" % linestart)

    def test_name(self):
        value = self.read_status_file("Name:")
        self.assertEqual(self.proc.name(), value)

    def test_status(self):
        value = self.read_status_file("State:")
        value = value[value.find('(') + 1:value.rfind(')')]
        value = value.replace(' ', '-')
        self.assertEqual(self.proc.status(), value)

    def test_ppid(self):
        value = self.read_status_file("PPid:")
        self.assertEqual(self.proc.ppid(), value)

    def test_num_threads(self):
        value = self.read_status_file("Threads:")
        self.assertEqual(self.proc.num_threads(), value)

    def test_uids(self):
        value = self.read_status_file("Uid:")
        value = tuple(map(int, value.split()[1:4]))
        self.assertEqual(self.proc.uids(), value)

    def test_gids(self):
        value = self.read_status_file("Gid:")
        value = tuple(map(int, value.split()[1:4]))
        self.assertEqual(self.proc.gids(), value)

    @retry_before_failing()
    def test_num_ctx_switches(self):
        value = self.read_status_file("voluntary_ctxt_switches:")
        self.assertEqual(self.proc.num_ctx_switches().voluntary, value)
        value = self.read_status_file("nonvoluntary_ctxt_switches:")
        self.assertEqual(self.proc.num_ctx_switches().involuntary, value)

    def test_cpu_affinity(self):
        value = self.read_status_file("Cpus_allowed_list:")
        if '-' in str(value):
            min_, max_ = map(int, value.split('-'))
            self.assertEqual(
                self.proc.cpu_affinity(), list(range(min_, max_ + 1)))

    def test_cpu_affinity_eligible_cpus(self):
        value = self.read_status_file("Cpus_allowed_list:")
        with mock.patch("psutil._pslinux.per_cpu_times") as m:
            self.proc._proc._get_eligible_cpus()
        if '-' in str(value):
            assert not m.called
        else:
            assert m.called


# =====================================================================
# --- test utils
# =====================================================================


@unittest.skipIf(not LINUX, "LINUX only")
class TestUtils(unittest.TestCase):

    def test_open_text(self):
        with psutil._psplatform.open_text(__file__) as f:
            self.assertEqual(f.mode, 'rt')

    def test_open_binary(self):
        with psutil._psplatform.open_binary(__file__) as f:
            self.assertEqual(f.mode, 'rb')

    def test_readlink(self):
        with mock.patch("os.readlink", return_value="foo (deleted)") as m:
            self.assertEqual(psutil._psplatform.readlink("bar"), "foo")
            assert m.called

    def test_cat(self):
        fname = os.path.abspath(TESTFN)
        with open(fname, "wt") as f:
            f.write("foo ")
        self.assertEqual(psutil._psplatform.cat(TESTFN, binary=False), "foo")
        self.assertEqual(psutil._psplatform.cat(TESTFN, binary=True), b"foo")
        self.assertEqual(
            psutil._psplatform.cat(TESTFN + '??', fallback="bar"), "bar")


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_osx.py000064400000022636150466730540010153 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""OSX specific tests."""

import os
import re
import time

import psutil
from psutil import OSX
from psutil.tests import create_zombie_proc
from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import MEMORY_TOLERANCE
from psutil.tests import reap_children
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import sh
from psutil.tests import unittest


PAGESIZE = os.sysconf("SC_PAGE_SIZE") if OSX else None


def sysctl(cmdline):
    """Expects a sysctl command with an argument and parse the result
    returning only the value of interest.
    """
    out = sh(cmdline)
    result = out.split()[1]
    try:
        return int(result)
    except ValueError:
        return result


def vm_stat(field):
    """Wrapper around 'vm_stat' cmdline utility."""
    out = sh('vm_stat')
    for line in out.split('\n'):
        if field in line:
            break
    else:
        raise ValueError("line not found")
    return int(re.search(r'\d+', line).group(0)) * PAGESIZE


# http://code.activestate.com/recipes/578019/
def human2bytes(s):
    SYMBOLS = {
        'customary': ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'),
    }
    init = s
    num = ""
    while s and s[0:1].isdigit() or s[0:1] == '.':
        num += s[0]
        s = s[1:]
    num = float(num)
    letter = s.strip()
    for name, sset in SYMBOLS.items():
        if letter in sset:
            break
    else:
        if letter == 'k':
            sset = SYMBOLS['customary']
            letter = letter.upper()
        else:
            raise ValueError("can't interpret %r" % init)
    prefix = {sset[0]: 1}
    for i, s in enumerate(sset[1:]):
        prefix[s] = 1 << (i + 1) * 10
    return int(num * prefix[letter])


@unittest.skipIf(not OSX, "OSX only")
class TestProcess(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.pid = get_test_subprocess().pid

    @classmethod
    def tearDownClass(cls):
        reap_children()

    def test_process_create_time(self):
        output = sh("ps -o lstart -p %s" % self.pid)
        start_ps = output.replace('STARTED', '').strip()
        hhmmss = start_ps.split(' ')[-2]
        year = start_ps.split(' ')[-1]
        start_psutil = psutil.Process(self.pid).create_time()
        self.assertEqual(
            hhmmss,
            time.strftime("%H:%M:%S", time.localtime(start_psutil)))
        self.assertEqual(
            year,
            time.strftime("%Y", time.localtime(start_psutil)))


@unittest.skipIf(not OSX, "OSX only")
class TestZombieProcessAPIs(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        zpid = create_zombie_proc()
        cls.p = psutil.Process(zpid)

    @classmethod
    def tearDownClass(cls):
        reap_children(recursive=True)

    def test_pidtask_info(self):
        self.assertEqual(self.p.status(), psutil.STATUS_ZOMBIE)
        self.p.ppid()
        self.p.uids()
        self.p.gids()
        self.p.terminal()
        self.p.create_time()

    def test_exe(self):
        self.assertRaises(psutil.ZombieProcess, self.p.exe)

    def test_cmdline(self):
        self.assertRaises(psutil.ZombieProcess, self.p.cmdline)

    def test_environ(self):
        self.assertRaises(psutil.ZombieProcess, self.p.environ)

    def test_cwd(self):
        self.assertRaises(psutil.ZombieProcess, self.p.cwd)

    def test_memory_full_info(self):
        self.assertRaises(psutil.ZombieProcess, self.p.memory_full_info)

    def test_cpu_times(self):
        self.assertRaises(psutil.ZombieProcess, self.p.cpu_times)

    def test_num_ctx_switches(self):
        self.assertRaises(psutil.ZombieProcess, self.p.num_ctx_switches)

    def test_num_threads(self):
        self.assertRaises(psutil.ZombieProcess, self.p.num_threads)

    def test_open_files(self):
        self.assertRaises(psutil.ZombieProcess, self.p.open_files)

    def test_connections(self):
        self.assertRaises(psutil.ZombieProcess, self.p.connections)

    def test_num_fds(self):
        self.assertRaises(psutil.ZombieProcess, self.p.num_fds)

    def test_threads(self):
        self.assertRaises((psutil.ZombieProcess, psutil.AccessDenied),
                          self.p.threads)

    def test_memory_maps(self):
        self.assertRaises(psutil.ZombieProcess, self.p.memory_maps)


@unittest.skipIf(not OSX, "OSX only")
class TestSystemAPIs(unittest.TestCase):

    # --- disk

    def test_disks(self):
        # test psutil.disk_usage() and psutil.disk_partitions()
        # against "df -a"
        def df(path):
            out = sh('df -k "%s"' % path).strip()
            lines = out.split('\n')
            lines.pop(0)
            line = lines.pop(0)
            dev, total, used, free = line.split()[:4]
            if dev == 'none':
                dev = ''
            total = int(total) * 1024
            used = int(used) * 1024
            free = int(free) * 1024
            return dev, total, used, free

        for part in psutil.disk_partitions(all=False):
            usage = psutil.disk_usage(part.mountpoint)
            dev, total, used, free = df(part.mountpoint)
            self.assertEqual(part.device, dev)
            self.assertEqual(usage.total, total)
            # 10 MB tollerance
            if abs(usage.free - free) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % usage.free, free)
            if abs(usage.used - used) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % usage.used, used)

    # --- cpu

    def test_cpu_count_logical(self):
        num = sysctl("sysctl hw.logicalcpu")
        self.assertEqual(num, psutil.cpu_count(logical=True))

    def test_cpu_count_physical(self):
        num = sysctl("sysctl hw.physicalcpu")
        self.assertEqual(num, psutil.cpu_count(logical=False))

    def test_cpu_freq(self):
        freq = psutil.cpu_freq()
        self.assertEqual(
            freq.current * 1000 * 1000, sysctl("sysctl hw.cpufrequency"))
        self.assertEqual(
            freq.min * 1000 * 1000, sysctl("sysctl hw.cpufrequency_min"))
        self.assertEqual(
            freq.max * 1000 * 1000, sysctl("sysctl hw.cpufrequency_max"))

    # --- virtual mem

    def test_vmem_total(self):
        sysctl_hwphymem = sysctl('sysctl hw.memsize')
        self.assertEqual(sysctl_hwphymem, psutil.virtual_memory().total)

    @retry_before_failing()
    def test_vmem_free(self):
        vmstat_val = vm_stat("free")
        psutil_val = psutil.virtual_memory().free
        self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_available(self):
        vmstat_val = vm_stat("inactive") + vm_stat("free")
        psutil_val = psutil.virtual_memory().available
        self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_active(self):
        vmstat_val = vm_stat("active")
        psutil_val = psutil.virtual_memory().active
        self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_inactive(self):
        vmstat_val = vm_stat("inactive")
        psutil_val = psutil.virtual_memory().inactive
        self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_wired(self):
        vmstat_val = vm_stat("wired")
        psutil_val = psutil.virtual_memory().wired
        self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)

    # --- swap mem

    @retry_before_failing()
    def test_swapmem_sin(self):
        vmstat_val = vm_stat("Pageins")
        psutil_val = psutil.swap_memory().sin
        self.assertEqual(psutil_val, vmstat_val)

    @retry_before_failing()
    def test_swapmem_sout(self):
        vmstat_val = vm_stat("Pageout")
        psutil_val = psutil.swap_memory().sout
        self.assertEqual(psutil_val, vmstat_val)

    # Not very reliable.
    # def test_swapmem_total(self):
    #     out = sh('sysctl vm.swapusage')
    #     out = out.replace('vm.swapusage: ', '')
    #     total, used, free = re.findall('\d+.\d+\w', out)
    #     psutil_smem = psutil.swap_memory()
    #     self.assertEqual(psutil_smem.total, human2bytes(total))
    #     self.assertEqual(psutil_smem.used, human2bytes(used))
    #     self.assertEqual(psutil_smem.free, human2bytes(free))

    # --- network

    def test_net_if_stats(self):
        for name, stats in psutil.net_if_stats().items():
            try:
                out = sh("ifconfig %s" % name)
            except RuntimeError:
                pass
            else:
                self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
                self.assertEqual(stats.mtu,
                                 int(re.findall(r'mtu (\d+)', out)[0]))

    # --- sensors_battery

    @unittest.skipIf(not HAS_BATTERY, "no battery")
    def test_sensors_battery(self):
        out = sh("pmset -g batt")
        percent = re.search("(\d+)%", out).group(1)
        drawing_from = re.search("Now drawing from '([^']+)'", out).group(1)
        power_plugged = drawing_from == "AC Power"
        psutil_result = psutil.sensors_battery()
        self.assertEqual(psutil_result.power_plugged, power_plugged)
        self.assertEqual(psutil_result.percent, int(percent))


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_sunos.py000064400000002424150466730540010502 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Sun OS specific tests."""

import os

import psutil
from psutil import SUNOS
from psutil.tests import run_test_module_by_name
from psutil.tests import sh
from psutil.tests import unittest


@unittest.skipIf(not SUNOS, "SUNOS only")
class SunOSSpecificTestCase(unittest.TestCase):

    def test_swap_memory(self):
        out = sh('env PATH=/usr/sbin:/sbin:%s swap -l' % os.environ['PATH'])
        lines = out.strip().split('\n')[1:]
        if not lines:
            raise ValueError('no swap device(s) configured')
        total = free = 0
        for line in lines:
            line = line.split()
            t, f = line[-2:]
            total += int(int(t) * 512)
            free += int(int(f) * 512)
        used = total - free

        psutil_swap = psutil.swap_memory()
        self.assertEqual(psutil_swap.total, total)
        self.assertEqual(psutil_swap.used, used)
        self.assertEqual(psutil_swap.free, free)

    def test_cpu_count(self):
        out = sh("/usr/sbin/psrinfo")
        self.assertEqual(psutil.cpu_count(), len(out.split('\n')))


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/__pycache__/test_contracts.cpython-36.opt-1.pyc000064400000054162150466730540016564 0ustar003

��JZ2^�@s�dZddlZddlZddlZddlZddlZddlZddlmZddl	m
Z
ddl	mZddl	mZddl	m
Z
ddl	mZdd	l	mZdd
l	mZddl	mZddl	mZdd
l	mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddl	Z	Gd d!�d!e$j(�Z)Gd"d#�d#e$j(�Z*Gd$d%�d%e$j(�Z+Gd&d'�d'e$j(�Z,e-d(k�r�e e.�dS))z�Contracts tests. These tests mainly check API sanity in terms of
returned types and APIs availability.
Some of these are duplicates of tests test_system.py and test_process.py
�N)�closing)�AIX)�BSD)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�callable)�long)�bind_unix_socket)�check_connection_ntuple)�get_kernel_version)�HAS_CONNECTIONS_UNIX)�
HAS_RLIMIT)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�
is_namedtuple)�run_test_module_by_name)�safe_rmpath)�skip_on_access_denied)�TESTFN)�unittest)�unix_socket_path)�VALID_PROC_STATUSES)�warnc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.S)/�TestAvailabilityzQMake sure code reflects what doc promises in terms of APIs
    availability.
    cCs$tp
tp
t}|jttjd�|�dS)N�cpu_affinity)rrr�assertEqual�hasattr�psutil�Process)�self�hasit�r'�&/usr/lib64/python3.6/test_contracts.py�test_cpu_affinity<sz"TestAvailability.test_cpu_affinitycCs(|jttd�t�|jttd�t�dS)NZwin_service_iterZwin_service_get)r!r"r#r)r%r'r'r(�test_win_service@sz!TestAvailability.test_win_servicecCs|jttd�tptpt�dS)NZPROCFS_PATH)r!r"r#rrr)r%r'r'r(�test_PROCFS_PATHDsz!TestAvailability.test_PROCFS_PATHcCsj|j}|ttd�t�|ttd�t�|ttd�t�|ttd�t�|ttd�t�|ttd�t�dS)NZABOVE_NORMAL_PRIORITY_CLASSZBELOW_NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSZIDLE_PRIORITY_CLASSZNORMAL_PRIORITY_CLASSZREALTIME_PRIORITY_CLASS)r!r"r#r)r%�aer'r'r(�test_win_priorityHsz"TestAvailability.test_win_prioritycCsJ|j}|ttd�t�|ttd�t�|ttd�t�|ttd�t�dS)NZIOPRIO_CLASS_NONEZIOPRIO_CLASS_RTZIOPRIO_CLASS_BEZIOPRIO_CLASS_IDLE)r!r"r#r)r%r,r'r'r(�test_linux_ioprioQs
z"TestAvailability.test_linux_iopriocCsH|j}tot�dk}|ttjd�|�|ttd�|�|ttd�|�|ttd�|�|ttd�|�|ttd	�|�|ttd
�|�|ttd�|�|ttd�|�|ttd
�|�|ttd�|�|ttd�|�|ttd�|�to�t�dk}|ttd�|�|ttd�|�|ttd�|�|ttd�|�|ttd�|�dS)N���$�rlimitZ
RLIM_INFINITYZ	RLIMIT_ASZRLIMIT_COREZ
RLIMIT_CPUZRLIMIT_DATAZRLIMIT_FSIZEZRLIMIT_LOCKSZRLIMIT_MEMLOCK�
RLIMIT_NOFILEZRLIMIT_NPROCZ
RLIMIT_RSSZRLIMIT_STACK�rZRLIMIT_MSGQUEUEZRLIMIT_NICEZ
RLIMIT_RTPRIOZ
RLIMIT_RTTIMEZRLIMIT_SIGPENDING)r/r0r1)r4r)r!rrr"r#r$)r%r,r&r'r'r(�test_linux_rlimitXs*z"TestAvailability.test_linux_rlimitcCs:totjjd�ptjjd�}|jttd�|p2tp2t�dS)Nz/sys/devices/system/cpu/cpufreqz$/sys/devices/system/cpu/cpu0/cpufreqZcpu_freq)	r�os�path�existsr!r"r#r	r)r%�linuxr'r'r(�
test_cpu_freqpszTestAvailability.test_cpu_freqcCs|jttd�t�dS)N�sensors_temperatures)r!r"r#r)r%r'r'r(�test_sensors_temperaturesvsz*TestAvailability.test_sensors_temperaturescCs|jttd�t�dS)N�sensors_fans)r!r"r#r)r%r'r'r(�test_sensors_fansysz"TestAvailability.test_sensors_fanscCs"|jttd�tptptpt�dS)NZsensors_battery)r!r"r#rrrr	)r%r'r'r(�test_battery|szTestAvailability.test_batterycCs |jttjd�tptpt�dS)N�environ)r!r"r#r$rr	r)r%r'r'r(�test_proc_environ�sz"TestAvailability.test_proc_environcCs|jttjd�t�dS)N�uids)r!r"r#r$r
)r%r'r'r(�test_proc_uids�szTestAvailability.test_proc_uidscCs|jttjd�t�dS)NrB)r!r"r#r$r
)r%r'r'r(�test_proc_gids�szTestAvailability.test_proc_gidscCs|jttjd�t�dS)N�terminal)r!r"r#r$r
)r%r'r'r(�test_proc_terminal�sz#TestAvailability.test_proc_terminalcCs|jttjd�tpt�dS)N�ionice)r!r"r#r$rr)r%r'r'r(�test_proc_ionice�sz!TestAvailability.test_proc_ionicecCs|jttjd�t�dS)Nr2)r!r"r#r$r)r%r'r'r(�test_proc_rlimit�sz!TestAvailability.test_proc_rlimitcCs(ttjd�}|j|tstrdnd�dS)N�io_countersFT)r"r#r$r!r	r)r%r&r'r'r(�test_proc_io_counters�sz&TestAvailability.test_proc_io_counterscCs|jttjd�t�dS)N�num_fds)r!r"r#r$r
)r%r'r'r(�test_proc_num_fds�sz"TestAvailability.test_proc_num_fdscCs|jttjd�t�dS)N�num_handles)r!r"r#r$r)r%r'r'r(�test_proc_num_handles�sz&TestAvailability.test_proc_num_handlescCs |jttjd�tptpt�dS)Nr )r!r"r#r$rrr)r%r'r'r(�test_proc_cpu_affinity�sz'TestAvailability.test_proc_cpu_affinitycCs |jttjd�tptpt�dS)N�cpu_num)r!r"r#r$rrr)r%r'r'r(�test_proc_cpu_num�sz"TestAvailability.test_proc_cpu_numcCs,ttjd�}|j|tststr"dnd�dS)N�memory_mapsFT)r"r#r$r!rrr)r%r&r'r'r(�test_proc_memory_maps�sz&TestAvailability.test_proc_memory_mapsN)�__name__�
__module__�__qualname__�__doc__r)r*r+r-r.r5r:r<r>r?rArCrDrFrHrIrKrMrOrPrRrTr'r'r'r(r7s.	rc@seZdZdd�ZdS)�TestDeprecationscCsdtjdd��}tj�j�WdQRX|d}|j|j�t�|jdt	|j
��|jdt	|j
��dS)NT)�recordrzmemory_info_ex() is deprecatedzuse memory_info() instead)�warnings�catch_warningsr#r$�memory_info_ex�assertIsInstance�category�
FutureWarning�assertIn�str�message)r%Zws�wr'r'r(�test_memory_info_ex�sz$TestDeprecations.test_memory_info_exN)rUrVrWrer'r'r'r(rY�srYc@s�eZdZdZedd��Zdd�Zdd�Zdd	�Zd
d�Z	e
jed�e
je
d
�eed�dd����Zdd�Zdd�Zdd�Ze
jed�dd��Ze
jed�dd��Zdd�ZdS)�
TestSystemz�Check the return types of system related APIs.
    Mainly we want to test we never return unicode on Python 2, see:
    https://github.com/giampaolo/psutil/issues/1039
    cCstj�|_dS)N)r#r$�proc)�clsr'r'r(�
setUpClass�szTestSystem.setUpClasscCstt�dS)N)rr)r%r'r'r(�tearDown�szTestSystem.tearDowncCs2tj�}x$|D]}|j|t�|j|d�qWdS)Nr)r#�	cpu_timesr^�float�assertGreaterEqual)r%�ret�nr'r'r(�test_cpu_times�s
zTestSystem.test_cpu_timescCs&x tjdd�D]}|j|t�qWdS)NT)Zperdisk)r#Zdisk_io_countersr^rb)r%�kr'r'r(�test_io_counters�szTestSystem.test_io_counterscCsNxHtj�D]<}|j|jt�|j|jt�|j|jt�|j|jt�q
WdS)N)r#Zdisk_partitionsr^ZdevicerbZ
mountpointZfstypeZopts)r%Zdiskr'r'r(�test_disk_partitions�s
zTestSystem.test_disk_partitionsz
POSIX onlyzcan't list UNIX sockets)Zonly_ifcCsVt��F}tt|���.tjdd�}x|D]}|j|jt�q(WWdQRXWdQRXdS)NZunix)Zkind)rrrr#Znet_connectionsr^Zladdrrb)r%�nameZcons�connr'r'r(�test_net_connections�s

zTestSystem.test_net_connectionscCsrxltj�j�D]\\}}|j|t�xF|D]>}|j|jt�|j|jttd�f�|j|jttd�f�q(WqWdS)N)	r#Znet_if_addrs�itemsr^rbZaddressZnetmask�typeZ	broadcast)r%�ifnameZaddrs�addrr'r'r(�test_net_if_addrs�s
zTestSystem.test_net_if_addrscCs*x$tj�j�D]\}}|j|t�qWdS)N)r#Znet_if_statsrwr^rb)r%ry�_r'r'r(�test_net_if_stats�szTestSystem.test_net_if_statscCs.x(tjdd�j�D]\}}|j|t�qWdS)NT)Zpernic)r#Znet_io_countersrwr^rb)r%ryr|r'r'r(�test_net_io_counters�szTestSystem.test_net_io_countersz
not supportedcCsFx@tj�j�D]0\}}|j|t�x|D]}|j|jt�q(WqWdS)N)r#r=rwr^rb�label)r%rt�units�unitr'r'r(r>�s
zTestSystem.test_sensors_fanscCsFx@tj�j�D]0\}}|j|t�x|D]}|j|jt�q(WqWdS)N)r#r;rwr^rbr)r%rtr�r�r'r'r(r<s
z$TestSystem.test_sensors_temperaturescCsfx`tj�D]T}|j|jt�|j|jttd�f�|j|jttd�f�|j|jt	td�f�q
WdS)N)
r#�usersr^rtrbrErx�host�pid�int)r%�userr'r'r(�
test_userss
zTestSystem.test_usersN)rUrVrWrX�classmethodrirjrprrrsrZskipIfr
rrr	rvr{r}r~rr>rr<r�r'r'r'r(rf�s		rfc@s(eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Zd8d9�Zd:d;�Z d<d=�Z!d>d?�Z"d@dA�Z#dBdC�Z$dDdE�Z%dFdG�Z&dHS)I�TestFetchAllProcessesz~Test which iterates over all running processes and performs
    some sanity checks against Process API's returned values.
    cCsdtr`ddl}ddl}|j�}|j�}tdd�|D��|_tdd�|D��|_tdd�|D��|_dS)NrcSsg|]
}|j�qSr')Zpw_uid)�.0�xr'r'r(�
<listcomp>(sz/TestFetchAllProcesses.setUp.<locals>.<listcomp>cSsg|]
}|j�qSr')Zpw_name)r�r�r'r'r(r�)scSsg|]
}|j�qSr')Zgr_gid)r�r�r'r'r(r�*s)	r
�pwd�grpZgetpwallZgetgrall�set�all_uids�
all_usernames�all_gids)r%r�r�r��groupsr'r'r(�setUp"szTestFetchAllProcesses.setUpcCs�d}tdddddddd	d
ddg�}tr6tr6|jd
�g}x2ttj�D]$}|jd�rVqF||kr`qF|j|�qFWt	�}g}�xtj
�D�]�}|j�����x�|D�]�}|}ydf}	i}
t||d�}|dk	r�t
|�r�|d
kr�tjf}	n|dkr�ddi}
||	|
�}n|}|d7}W�n2tk
�r>d|jjd|}t|�Yq�tjtjfk
�r�}
z0|j|
j|j�|
j�r�|j|
j|j��WYdd}
~
Xq�tk
�r>}
z�dddd}|d||f7}||k�r�|dt|�7}|d7}|dd7}|dtj�7}djdd�|j�D��}|d7}|j|�PWYdd}
~
Xq�X|ddgdd ifk�rVt||�}|||�q�WWdQRXq�W|�r�|jd j|��dS)!NrZsend_signalZsuspendZresumeZ	terminate�kill�waitZas_dict�parentZchildrenr]�oneshotr2r|rSZgroupedF�z&%r was skipped because not implementedz.test_�
�=�FzFAIL: test_%s (proc=%sz	, ret=%s)z)
�-z
%scss|]}d|VqdS)� �Nz    r')r��ir'r'r(�	<genexpr>csz7TestFetchAllProcesses.test_fetch_all.<locals>.<genexpr>g�)r�rr�add�dirr#r$�
startswith�append�objectZprocess_iterr��getattrr
r3�NotImplementedError�	__class__rUrZ
NoSuchProcessZAccessDeniedr!r�rt�	Exception�repr�	traceback�
format_exc�join�
splitlinesZfail)r%Zvalid_procsZexcluded_namesZattrsrt�defaultZfailures�prn�args�kwargs�attr�msg�err�s�methr'r'r(�test_fetch_all,st






z$TestFetchAllProcesses.test_fetch_allcCs*|j|t�x|D]}|j|t�qWdS)N)r^�listrb)r%rnrg�partr'r'r(�cmdlinets
zTestFetchAllProcesses.cmdlinecCsN|j|ttd�f�|s&|j|d�n$trJtjj|�rJttd�rJttd�rJdS)Nr��access�X_OK)	r^rbrxr!r
r6r7�isfiler")r%rnrgr'r'r(�exeyszTestFetchAllProcesses.execCs|j|t�|j|d�dS)Nr)r^r�rm)r%rnrgr'r'r(r��szTestFetchAllProcesses.pidcCs |j|ttf�|j|d�dS)Nr)r^r�rrm)r%rnrgr'r'r(�ppid�szTestFetchAllProcesses.ppidcCs|j|t�tsdS)N)r^rbr)r%rnrgr'r'r(rt�szTestFetchAllProcesses.namecCs^|j|t�y|j|d�Wn*tk
rFtr@|j�tjkr@n�YnXtj	dtj
|��dS)Nrz%Y %m %d %H:%M:%S)r^rlrm�AssertionErrorr�statusr#Z
STATUS_ZOMBIE�timeZstrftimeZ	localtime)r%rnrgr'r'r(�create_time�sz!TestFetchAllProcesses.create_timecCs8x2|D]*}|j|t�|j|d�|j||j�qWdS)Nr)r^r�rmrar�)r%rnrgZuidr'r'r(rB�s
zTestFetchAllProcesses.uidscCsDx>|D]6}|j|t�trtr|j|d�|j||j�qWdS)Nr)r^r�r	rrmrar�)r%rnrg�gidr'r'r(�gids�s

zTestFetchAllProcesses.gidscCs"|j|t�tr|j||j�dS)N)r^rbr
rar�)r%rnrgr'r'r(�username�szTestFetchAllProcesses.usernamecCs(|j|t�|j|d�|j|t�dS)N�?)r^rbZassertNotEqualrar)r%rnrgr'r'r(r��szTestFetchAllProcesses.statuscCs6x0|D](}|j|ttf�|dkr|j|d�qWdS)Nr�r���)r^r�rrm)r%rnrg�fieldr'r'r(rJ�s
z!TestFetchAllProcesses.io_counterscCs\trx|D]}|j|t�q
Wtr@|j|jd�|j|jd�n|j|d�|j|d�dS)Nrr�r/)rr�r/)r
r^r�rrmZioclass�valuera)r%rnrgr�r'r'r(rG�s
zTestFetchAllProcesses.ionicecCs|j|t�|j|d�dS)Nr�)r^r�rm)r%rnrgr'r'r(�num_threads�sz!TestFetchAllProcesses.num_threadscCsf|j|t�xT|D]L}|j|jd�|j|jd�|j|jd�x|D]}|j|ttf�qFWqWdS)Nr)r^r�rm�idZ	user_timeZsystem_timer�rl)r%rnrg�tr�r'r'r(�threads�s

zTestFetchAllProcesses.threadscCs*x$|D]}|j|t�|j|d�qWdS)Nr)r^rlrm)r%rnrgror'r'r(rk�s
zTestFetchAllProcesses.cpu_timescCs|j|t�dS)N)r^rl)r%rnrgr'r'r(�cpu_percent�sz!TestFetchAllProcesses.cpu_percentcCs\|j|t�tr|dkrdS|j|d�tj�dkr@|j|d�|j|tt	tj����dS)Nr�rr�)
r^r�rrmr#�	cpu_countr!rar��range)r%rnrgr'r'r(rQ�szTestFetchAllProcesses.cpu_numcCs�x(|D] }|j|ttf�|j|d�qWtrttrt|jdkrtxx|jD](}|dkrFt||�}|j	|j||d�qFWnDt
r�|j|j|j�|j|j
|j�|j|j|j�|j|j|j�dS)Nr�vms)r�)r^r�rrmr
rr��_fieldsr��
assertGreaterrZ	peak_wsetZwsetZpeak_paged_poolZ
paged_poolZpeak_nonpaged_poolZ
nonpaged_poolZ
peak_pagefileZpagefile)r%rnrgr�rtr'r'r(�memory_info�s

z!TestFetchAllProcesses.memory_infocCsvtj�j}xR|jD]H}t||�}|j|ttf�|j|d||fd�|j	|||||fd�qWt
rr|j|j|j�dS)Nr)r�)
r#Zvirtual_memory�totalr�r�r^r�rrmZassertLessEqualrZpssZuss)r%rnrgr�rtr�r'r'r(�memory_full_infos

z&TestFetchAllProcesses.memory_full_infocCs�|j|t�x�|D]�}|j|jt�|j|jt�trF|j|jd�qtr�|j|j	t�|j|j
t�|j|jt�|j|j	d�|j
|j
d	�|j|jd�qtr|jrqqWdS)
Nr�r�rrd�a�r+�a+r�)r�rdr�r�r�)r^r��fdr�r7rbrr!rZposition�mode�flagsrmrar�r)r%rnrg�fr'r'r(�
open_filess 
z TestFetchAllProcesses.open_filescCs|j|t�|j|d�dS)Nr)r^r�rm)r%rnrgr'r'r(rL(szTestFetchAllProcesses.num_fdscCs2|jt|�tt|���x|D]}t|�qWdS)N)r!�lenr�r)r%rnrgrur'r'r(�connections,s
z!TestFetchAllProcesses.connectionscCsh|rd|j|t�ytj|�}WnDtk
rb}z(trD|jtjj	krDn|jtj
krR�WYdd}~XnXdS)N)r^rbr6�stat�OSErrorr�errnor#Z_psplatformZACCESS_DENIED_SET�ENOENT)r%rnrg�str�r'r'r(�cwd1s
zTestFetchAllProcesses.cwdcCs|j|t�dS)N)r^rl)r%rnrgr'r'r(�memory_percentAsz$TestFetchAllProcesses.memory_percentcCs|j|t�dS)N)r^�bool)r%rnrgr'r'r(�
is_runningEsz TestFetchAllProcesses.is_runningcCsB|j|t�ttj��}x$|D]}|j|t�|j||�qWdS)N)r^r�r�r#r�r�ra)r%rnrgZcpusror'r'r(r Hs

z"TestFetchAllProcesses.cpu_affinitycCs |j|ttd�f�|dk	rdS)N)r^rbrx)r%rnrgr'r'r(rEPszTestFetchAllProcesses.terminalcCs�x�|D]�}|j|jt�|j|jt�|j|jt�xR|jD]H}t||�}|dkr^|jd�s�q<|dkrhq<|j|tt	f�|j
|d�q<WqWdS)Nr7�[rz�permsr)rzr�)r^rzrbr�r7r�r�r�r�rrm)r%rnrg�ntZfnamer�r'r'r(rSVs


z!TestFetchAllProcesses.memory_mapscCs|j|t�|j|d�dS)Nr)r^r�rm)r%rnrgr'r'r(rNisz!TestFetchAllProcesses.num_handlescCs4|j|t�trndd�tt�D�}|j||�dS)NcSs g|]}|jd�rtt|��qS)Z_PRIORITY_CLASS)�endswithr�r#)r�r�r'r'r(r�rsz.TestFetchAllProcesses.nice.<locals>.<listcomp>)r^r�r
r�r#ra)r%rnrgZ
prioritiesr'r'r(�nicems
zTestFetchAllProcesses.nicecCs.x(|D] }|j|ttf�|j|d�qWdS)Nr)r^r�rrm)r%rnrgr�r'r'r(�num_ctx_switchesvs
z&TestFetchAllProcesses.num_ctx_switchescCs@|j|t�|jt|�d�|j|dd�|j|dd�dS)Nr/rr�r�r�)r^�tupler!r�rm)r%rnrgr'r'r(r2|szTestFetchAllProcesses.rlimitcCs>|j|t�x,|j�D] \}}|j|t�|j|t�qWdS)N)r^�dictrwrb)r%rnrgrq�vr'r'r(r@�szTestFetchAllProcesses.environN)'rUrVrWrXr�r�r�r�r�r�rtr�rBr�r�r�rJrGr�r�rkr�rQr�r�r�rLr�r�r�r�r rErSrNr�r�r2r@r'r'r'r(r�sH
H

		r��__main__)/rXr�r6r�r�r�r[�
contextlibrr#rrrrrrr	r
rrZpsutil._compatr
rZpsutil.testsrrrrrrrrrrrrrrrrZTestCaserrYrfr�rU�__file__r'r'r'r(�<module>	sXx^n
tests/__pycache__/test_bsd.cpython-36.pyc000064400000042355150466730540014376 0ustar003

��JZcE�@s�dZddlZddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddl
mZddl
mZdd	l
m
Z
dd
l
mZddl
mZddl
mZdd
l
mZddl
mZddl
mZer�ejd�Zej�dkr�ed�Zq�dZndZdd�Zdd�Zejed�Gdd�dej��Zejed�Gdd�dej��Zeje	d�Gdd�dej��Zejed�Gd d!�d!ej��Ze d"k�r�ee!�dS)#z$Tests specific to all BSD platforms.�N)�BSD)�FREEBSD)�NETBSD)�OPENBSD)�get_test_subprocess)�HAS_BATTERY)�MEMORY_TOLERANCE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�unittest)�which�SC_PAGE_SIZE�museFcCshtd|�}tr(||jd�dd�}nts0trF||jd�dd�}yt|�Stk
rb|SXdS)zmExpects a sysctl command with an argument and parse the result
    returning only the value of interest.
    zsysctl z: �N�=�)rr�findrr�int�
ValueError)�cmdline�result�r� /usr/lib64/python3.6/test_bsd.py�sysctl+srcCs@td�}x&|jd�D]}|j|�rPqWtd��t|j�d�S)z+Thin wrapper around 'muse' cmdline utility.r�
zline not foundr)r�split�
startswithrr)Zfield�out�linerrrr:s
zBSD onlyc@s�eZdZdZedd��Zedd��Zeje	d�dd��Z
d	d
�Zejed�d�d
d��Z
ejed�d�dd��Zdd�ZdS)�BSDSpecificTestCasez)Generic tests common to all BSD variants.cCst�j|_dS)N)r�pid)�clsrrr�
setUpClassNszBSDSpecificTestCase.setUpClasscCs
t�dS)N)r	)r#rrr�
tearDownClassRsz!BSDSpecificTestCase.tearDownClassz -o lstart doesn't work on NETBSDcCsPtd|j�}|jdd�j�}tj|j�j�}tjdtj	|��}|j
||�dS)Nzps -o lstart -p %sZSTARTED�z%a %b %e %H:%M:%S %Y)rr"�replace�strip�psutil�ProcessZcreate_time�timeZstrftimeZ	localtime�assertEqual)�self�outputZstart_psZstart_psutilrrr�test_process_create_timeVsz,BSDSpecificTestCase.test_process_create_timecCs�dd�}x�tjdd�D]�}tj|j�}||j�\}}}}|j|j|�|j|j|�t|j|�d	krz|j	d|j|f�t|j
|�dkr|j	d|j
|f�qWdS)NcSs�td|�j�}|jd�}|jd�|jd�}|j�dd�\}}}}|dkrRd}t|�d}t|�d}t|�d}||||fS)Nz
df -k "%s"rr�Znoner&i)rr(r�popr)�pathr�linesr �dev�total�used�freerrr�dfbs


z*BSDSpecificTestCase.test_disks.<locals>.dfF)�all�
izpsutil=%s, df=%si(i�i(i�)r)Zdisk_partitionsZ
disk_usageZ
mountpointr,Zdevicer5�absr7Zfailr6)r-r8�partZusager4r5r6r7rrr�
test_disks_s
zBSDSpecificTestCase.test_disksrzsysctl cmd not availablecCs td�}|jtjdd�|�dS)Nzhw.ncpuT)Zlogical)rr,r)�	cpu_count)r-�systrrr�test_cpu_count_logicalzsz*BSDSpecificTestCase.test_cpu_count_logicalcCstd�}|j|tj�j�dS)Nz
hw.physmem)rr,r)�virtual_memoryr5)r-�numrrr�test_virtual_memory_totalsz-BSDSpecificTestCase.test_virtual_memory_totalcCs�xztj�j�D]j\}}ytd|�}Wntk
r:YqX|j|jd|k|d�d|kr|j|jtt	j
d|�d��qWdS)Nzifconfig %sZRUNNING)�msg�mtuz	mtu (\d+)r)r)Znet_if_stats�itemsr�RuntimeErrorr,ZisuprEr�re�findall)r-�nameZstatsrrrr�test_net_if_stats�sz%BSDSpecificTestCase.test_net_if_statsN)�__name__�
__module__�__qualname__�__doc__�classmethodr$r%r
�skipIfrr/r=rr@rCrKrrrrr!Js	r!zFREEBSD onlyc@s�eZdZedd��Zedd��Ze�dd��Zdd�Zd	d
�Z	dd�Z
e�d
d��Ze�dd��Ze�dd��Z
e�dd��Ze�dd��Ze�dd��Ze�dd��Ze�dd��Zejed�dd��Zejed�e�d d!���Zejed�e�d"d#���Zejed�e�d$d%���Zejed�e�d&d'���Zejed�e�d(d)���Zejed�e�d*d+���Zd,d-�Zd.d/�Zd0d1�Zd2d3�Z d4d5�Z!eje"d6�d7d8��Z#eje"d6�d9d:��Z$eje"d;�d<d=��Z%d>S)?�FreeBSDSpecificTestCasecCst�j|_dS)N)rr")r#rrrr$�sz"FreeBSDSpecificTestCase.setUpClasscCs
t�dS)N)r	)r#rrrr%�sz%FreeBSDSpecificTestCase.tearDownClasscCs�td|j�}tj|j�jdd�}|jd�dd�}x||r�|j�}|j�}|dd�\}}}}	}
|j�}|jd||f|j�|jt	|
�|j
�|jjd�s6|j|d	|j�q6WdS)
Nzprocstat -v %sF)Zgroupedrr�z%s-%s�[r:)
rr"r)r*Zmemory_mapsrr1r,ZaddrrZrssr2r)r-r�mapsr3r �fields�_�start�stopZperms�res�maprrr�test_proc_memory_maps�sz-FreeBSDSpecificTestCase.test_proc_memory_mapscCs<td|j�}|jtj|j�j�|jd�dj�d�dS)Nzprocstat -b %srr���)rr"r,r)r*Zexer)r-rrrr�
test_proc_exe�sz%FreeBSDSpecificTestCase.test_proc_execCsLtd|j�}|jdjtj|j�j��dj|jd�dj�dd���dS)Nzprocstat -c %s� rrr)rr"r,�joinr)r*rr)r-rrrr�test_proc_cmdline�sz)FreeBSDSpecificTestCase.test_proc_cmdlinecCs�td|j�}|jd�dj�dd�\}}}}}}tj|j�}|j�}	|j�}
|j|	jt	|��|j|	j
t	|��|j|	jt	|��|j|
jt	|��|j|
j
t	|��|j|
jt	|��dS)Nzprocstat -s %srrr�)rr"rr)r*�uids�gidsr,�realrZ	effectiveZsaved)r-rZeuidZruidZsuidZegidZrgidZsgid�prcrdrrr�test_proc_uids_gids�s&z+FreeBSDSpecificTestCase.test_proc_uids_gidscCs�g}td|j�}tj|j�}x�|jd�D]�}|j�j�}d|krtt|j�d�}|j�j	}|j
||�|jd�q*d|kr*t|j�d	�}|j�j}|j
||�|jd�q*Wt
|�dkr�td��dS)
Nzprocstat -r %srz voluntary contextrz involuntary contextrz)couldn't find lines match in procstat outr]r])rr"r)r*r�lowerr(rZnum_ctx_switchesZ	voluntaryr,�appendZinvoluntary�lenrG)r-�testedrrfr �pstat_value�psutil_valuerrr�test_proc_ctx_switches�s"

z.FreeBSDSpecificTestCase.test_proc_ctx_switchescCs�g}td|j�}tj|j�}x�|jd�D]�}|j�j�}d|kr�td|j�d
jd�d�}|j�j	}|j
||�|jd�q*d|kr*td|j�djd�d
�}|j�j}|j
||�|jd�q*Wt
|�dkr�td	��dS)Nzprocstat -r %srz	user timez0.r�.zsystem timerz)couldn't find lines match in procstat outr]r]r]r])rr"r)r*rrhr(�floatZ	cpu_times�userr,ri�systemrjrG)r-rkrrfr rlrmrrr�test_proc_cpu_times�s"

z+FreeBSDSpecificTestCase.test_proc_cpu_timescCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_active_count)�delta)r�PAGESIZE�assertAlmostEqualr)rA�activer)r-r?rrr�test_vmem_active�sz(FreeBSDSpecificTestCase.test_vmem_activecCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_inactive_count)rt)rrurvr)rA�inactiver)r-r?rrr�test_vmem_inactive�sz*FreeBSDSpecificTestCase.test_vmem_inactivecCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_wire_count)rt)rrurvr)rA�wiredr)r-r?rrr�test_vmem_wired�sz'FreeBSDSpecificTestCase.test_vmem_wiredcCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_cache_count)rt)rrurvr)rA�cachedr)r-r?rrr�test_vmem_cachedsz(FreeBSDSpecificTestCase.test_vmem_cachedcCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_free_count)rt)rrurvr)rAr7r)r-r?rrr�test_vmem_free	sz&FreeBSDSpecificTestCase.test_vmem_freecCs"td�}|jtj�j|td�dS)Nzvfs.bufspace)rt)rrvr)rA�buffersr)r-r?rrr�test_vmem_bufferssz)FreeBSDSpecificTestCase.test_vmem_bufferszmuse not installedcCstd�}|jtj�j|�dS)NZTotal)rr,r)rAr5)r-rBrrr�test_muse_vmem_totalsz,FreeBSDSpecificTestCase.test_muse_vmem_totalcCs"td�}|jtj�j|td�dS)NZActive)rt)rrvr)rArwr)r-rBrrr�test_muse_vmem_activesz-FreeBSDSpecificTestCase.test_muse_vmem_activecCs"td�}|jtj�j|td�dS)NZInactive)rt)rrvr)rAryr)r-rBrrr�test_muse_vmem_inactive#sz/FreeBSDSpecificTestCase.test_muse_vmem_inactivecCs"td�}|jtj�j|td�dS)NZWired)rt)rrvr)rAr{r)r-rBrrr�test_muse_vmem_wired*sz,FreeBSDSpecificTestCase.test_muse_vmem_wiredcCs"td�}|jtj�j|td�dS)NZCache)rt)rrvr)rAr}r)r-rBrrr�test_muse_vmem_cached1sz-FreeBSDSpecificTestCase.test_muse_vmem_cachedcCs"td�}|jtj�j|td�dS)NZFree)rt)rrvr)rAr7r)r-rBrrr�test_muse_vmem_free8sz+FreeBSDSpecificTestCase.test_muse_vmem_freecCs"td�}|jtj�j|td�dS)NZBuffer)rt)rrvr)rAr�r)r-rBrrr�test_muse_vmem_buffers?sz.FreeBSDSpecificTestCase.test_muse_vmem_bufferscCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_swtchi�)rt)rvr)�	cpu_stats�ctx_switchesr)r-rrr�test_cpu_stats_ctx_switchesFsz3FreeBSDSpecificTestCase.test_cpu_stats_ctx_switchescCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_intri�)rt)rvr)r��
interruptsr)r-rrr�test_cpu_stats_interruptsJsz1FreeBSDSpecificTestCase.test_cpu_stats_interruptscCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_softi�)rt)rvr)r�Zsoft_interruptsr)r-rrr�test_cpu_stats_soft_interruptsNsz6FreeBSDSpecificTestCase.test_cpu_stats_soft_interruptscCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_syscalli�)rt)rvr)r�Zsyscallsr)r-rrr�test_cpu_stats_syscallsRsz/FreeBSDSpecificTestCase.test_cpu_stats_syscallscCsLtd�}||jd�dd�}|d|jd��}t|�}|j|tj��dS)Nzsysctl kern.boottimez sec = ��,)rrrr,r)�	boot_time)r-�sZbtimerrr�test_boot_time\s
z&FreeBSDSpecificTestCase.test_boot_timez
no batterycCs�dd�}td�}tdd�|jd�D��}tj�}t|djdd	��}|d
}|j|j|�|dkrt|j|j	tj
�n|j||j	�|�dS)NcSs(t|d�\}}t|d�\}}d||fS)N�<z%d:%02d)�divmod)Zsecs�mr��hrrr�
secs2hoursgsz@FreeBSDSpecificTestCase.test_sensors_battery.<locals>.secs2hoursz
acpiconf -i 0cSs(g|] }|jd�d|jd�df�qS)�	rrr])r)�.0�xrrr�
<listcomp>msz@FreeBSDSpecificTestCase.test_sensors_battery.<locals>.<listcomp>rzRemaining capacity:�%r&zRemaining time:�unknown)r�dictrr)�sensors_batteryrr'r,�percent�secsleftZPOWER_TIME_UNLIMITED)r-r�rrVZmetricsr�Zremaining_timerrr�test_sensors_batteryesz,FreeBSDSpecificTestCase.test_sensors_batterycCsl|jtj�jtd��|jtj�jtd�dk�tj�j}|dkrT|jtd�d�n|j|td�d�dS)Nzhw.acpi.battery.lifezhw.acpi.aclinerrzhw.acpi.battery.timer�r])r,r)r�r�rZ
power_pluggedr�)r-r�rrr�#test_sensors_battery_against_sysctlxs

z;FreeBSDSpecificTestCase.test_sensors_battery_against_sysctlzhas batteryc	Cs@|jt��td�td�td�WdQRX|jtj��dS)Nzhw.acpi.battery.lifezhw.acpi.battery.timezhw.acpi.acline)ZassertRaisesrGrZassertIsNoner)r�)r-rrr�test_sensors_battery_no_battery�s
z7FreeBSDSpecificTestCase.test_sensors_battery_no_batteryN)&rLrMrNrPr$r%r
r\r^rargrnrsrxrzr|r~rr�r
rQ�MUSE_AVAILABLEr�r�r�r�r�r�r�r�r�r�r�r�rr�r�r�rrrrrR�sF

	rRzOPENBSD onlyc@seZdZdd�ZdS)�OpenBSDSpecificTestCasecCs6td�}tjj|d�}tjjtj��}|j||�dS)Nz
kern.boottimez%a %b %d %H:%M:%S %Y)r�datetimeZstrptimeZ
fromtimestampr)r�r,)r-r�Zsys_btZ	psutil_btrrrr��sz&OpenBSDSpecificTestCase.test_boot_timeN)rLrMrNr�rrrrr��sr�zNETBSD onlyc@s`eZdZedd��Zdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dS)�NetBSDSpecificTestCasecCsRtdd��2}x*|D]"}|j|�rt|j�d�dSqWWdQRXtd|��dS)Nz
/proc/meminfo�rbriz
can't find %s)�openrrrr)Zlook_for�fr rrr�
parse_meminfo�s


"z$NetBSDSpecificTestCase.parse_meminfocCs|jtj�j|jd��dS)Nz	MemTotal:)r,r)rAr5r�)r-rrr�test_vmem_total�sz&NetBSDSpecificTestCase.test_vmem_totalcCs |jtj�j|jd�td�dS)NzMemFree:)rt)rvr)rAr7r�r)r-rrrr�sz%NetBSDSpecificTestCase.test_vmem_freecCs |jtj�j|jd�td�dS)NzBuffers:)rt)rvr)rAr�r�r)r-rrrr��sz(NetBSDSpecificTestCase.test_vmem_bufferscCs |jtj�j|jd�td�dS)Nz
MemShared:)rt)rvr)rAZsharedr�r)r-rrr�test_vmem_shared�sz'NetBSDSpecificTestCase.test_vmem_sharedcCs |jtj�j|jd�td�dS)Nz
SwapTotal:)rt)rvr)�swap_memoryr5r�r)r-rrr�test_swapmem_total�sz)NetBSDSpecificTestCase.test_swapmem_totalcCs |jtj�j|jd�td�dS)Nz	SwapFree:)rt)rvr)r�r7r�r)r-rrr�test_swapmem_free�sz(NetBSDSpecificTestCase.test_swapmem_freecCs"tj�}|j|j|j|j�dS)N)r)r�r,r6r5r7)r-Zsmemrrr�test_swapmem_used�sz(NetBSDSpecificTestCase.test_swapmem_usedcCsbtdd��8}x0|D] }|jd�rt|j�d�}PqWtd��WdQRX|jtj�j|dd�dS)Nz
/proc/statr�sintrrzcouldn't find linei�)rt)	r�rrrrrvr)r�r�)r-r�r r�rrrr��s

z0NetBSDSpecificTestCase.test_cpu_stats_interruptscCsbtdd��8}x0|D] }|jd�rt|j�d�}PqWtd��WdQRX|jtj�j|dd�dS)Nz
/proc/statr�sctxtrzcouldn't find linei�)rt)	r�rrrrrvr)r�r�)r-r�r r�rrrr��s

z2NetBSDSpecificTestCase.test_cpu_stats_ctx_switchesN)rLrMrN�staticmethodr�r�rr�r�r�r�r�r�r�rrrrr��sr��__main__)"rOr��osrHr+r)rrrrZpsutil.testsrrrr	r
rrr
r�sysconfru�getuidr�rrrQZTestCaser!rRr�r�rL�__file__rrrr�<module>	sL


K


B
tests/__pycache__/test_system.cpython-36.opt-1.pyc000064400000060772150466730540016114 0ustar003

��JZ/��@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlm
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+dd lm,Z,dd!lm-Z-Gd"d#�d#e-j.�Z/e0d$k�r�e(e1�dS)%zTests for system APIS.�N)�AIX)�BSD)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�long)�APPVEYOR)�ASCII_FS)�check_net_address)�DEVNULL)�enum)�get_test_subprocess)�HAS_BATTERY)�HAS_CPU_FREQ)�HAS_SENSORS_BATTERY)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�mock)�
reap_children)�retry_before_failing)�run_test_module_by_name)�safe_rmpath)�TESTFN)�TESTFN_UNICODE)�TRAVIS)�unittestc@sBeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
eje
d�dd��Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Z d7d8�Z!d9d:�Z"d;d<�Z#d=d>�Z$d?d@�Z%dAdB�Z&dCdD�Z'dEdF�Z(dGdH�Z)eje*dI�dJdK��Z+eje,�o\e-j.j/dL�dM�eje0�ote1j2�dNkdO�dPdQ���Z3dRdS�Z4eje0�p�e*�o�e1j5�dT�dUdV��Z6dWdX�Z7eje8dY�dZd[��Z9d\d]�Z:eje;d^�d_d`��Z<eje;d^�dadb��Z=eje>d^�eje?dc�ddde���Z@ejeAd^�dfdg��ZBdNS)h�TestSystemAPIszTests for system-related APIs.cCstt�dS)N)rr)�self�r#�#/usr/lib64/python3.6/test_system.py�setUp>szTestSystemAPIs.setUpcCs
t�dS)N)r)r"r#r#r$�tearDownAszTestSystemAPIs.tearDowncCs�|jtj�dd�tj�D��t�}|j|jdd�tj�D��tj|j�}|j�|j	�|j
|jdd�tj�D��tjdtj
tj��d��|jttj��g�WdQRXtjdtjtj��d��*|jtj��ttj��WdQRXWdQRXdS)NcSsg|]
}|j�qSr#)�pid)�.0�xr#r#r$�
<listcomp>Esz4TestSystemAPIs.test_process_iter.<locals>.<listcomp>cSsg|]
}|j�qSr#)r')r(r)r#r#r$r*GscSsg|]
}|j�qSr#)r')r(r)r#r#r$r*Kszpsutil.Process)�side_effect)�assertIn�os�getpid�psutil�process_iterrr'�Process�kill�wait�assertNotInr�patchZ
NoSuchProcess�assertEqual�list�AccessDenied�assertRaises)r"�sproc�pr#r#r$�test_process_iterDsz TestSystemAPIs.test_process_itercCs"x.tjdgd�D]}|jt|jj��dg�qW|jt��ttjdgd��WdQRXtj	dtj
dd�d��B}x:tjddgd�D]&}|j|jd�|j|jdd�q�WWdQRXtj	dtj
dd�d��L}t
�}x>tjddg|d	�D](}|j|jd|�|j|jdd�q�WWdQRXdS)
Nr')�attrsZfooz$psutil._psplatform.Process.cpu_timesr�)r+�	cpu_times)r=Zad_value)r/r0r6r7�info�keysr9�
ValueErrorrr5r8�assertIsNone�assertGreaterEqual�object�assertIs)r"r;�m�flagr#r#r$�test_prcess_iter_w_paramsUs$
z(TestSystemAPIs.test_prcess_iter_w_paramscs��fdd�}g�t�}t�}t�}dd�|||fD�}�jttj|dd��jttj|dd�tj�}tj|d|d	�\}}�jtj�|d
��j|g��jt	|�d��j�g�x|D]}	�j
t|	d��q�Wtd
��fdd��}
|j
�|
||�\}}�j|jdd�|D��t�r4�j|j�jtj�n�j|j�jd��j�|jg�x|D]}	�j
t|	d���q\Wtd
��fdd��}
|j
�|j
�|
||�\}}�jt��t|j|j|jg��x|D]}	�jt|	d���q�WdS)Ncs�j|j�dS)N)�appendr')r;)�pidsr#r$�callbackjsz0TestSystemAPIs.test_wait_procs.<locals>.callbackcSsg|]}tj|j��qSr#)r/r1r')r(r)r#r#r$r*qsz2TestSystemAPIs.test_wait_procs.<locals>.<listcomp>�)�timeout)rLg{�G�z�?)rNrLg�?��
returncode�cs<tj|d|d�\}}�jt|�d��jt|�d�||fS)Ng���Q��?)rNrLrM�)r/�
wait_procsr6�len)�procsrL�gone�alive)r"r#r$�test~s
z,TestSystemAPIs.test_wait_procs.<locals>.testcSsg|]
}|j�qSr#)r')r(r)r#r#r$r*�scs<tj|d|d�\}}�jt|�d��jt|�d�||fS)Ng���Q��?)rNrLrOr)r/rSr6rT)rUrLrVrW)r"r#r$rX�s
���)rr9rBr/rS�	TypeError�time�
assertLessr6rT�assertFalse�hasattrr�	terminater,r'r	�poprP�signal�SIGTERM�set�
assertTrue)r"rL�sproc1�sproc2�sproc3rU�trVrWr;rXr#)rKr"r$�test_wait_procsisB

 
zTestSystemAPIs.test_wait_procscCsNt�}t�}t�}dd�|||fD�}x|D]}|j�q,Wtj|�\}}dS)NcSsg|]}tj|j��qSr#)r/r1r')r(r)r#r#r$r*�sz=TestSystemAPIs.test_wait_procs_no_timeout.<locals>.<listcomp>)rr_r/rS)r"rerfrgrUr;rVrWr#r#r$�test_wait_procs_no_timeout�s
z)TestSystemAPIs.test_wait_procs_no_timeoutcCs4tj�}|j|t�|j|d�|j|tj��dS)Nr)r/Z	boot_time�assertIsInstance�float�
assertGreaterr\r[)r"Zbtr#r#r$�test_boot_time�szTestSystemAPIs.test_boot_timez
POSIX onlycCs"ddl}|jtjd�|j��dS)Nr�SC_PAGE_SIZE)�resourcer6r-�sysconfZgetpagesize)r"rpr#r#r$�
test_PAGESIZE�szTestSystemAPIs.test_PAGESIZEcCs�tj�}xt|jD]j}t||�}|dkr6|j|ttf�|dkr|dksX|jd||f�||jkr|jd||j||f�qWdS)N�percent�totalrz%r < 0 (%s)z%r > total (total=%s, %s=%s))	r/Zvirtual_memory�_fields�getattrrk�intr�failrt)r"�mem�name�valuer#r#r$�test_virtual_memory�s

z"TestSystemAPIs.test_virtual_memorycCs&tj�}|j|jd�|jdkr"ndS)	Nrt�used�freers�sin�soutr)rtr}r~rsrr�)r/Zswap_memoryr6rurt)r"ryr#r#r$�test_swap_memory�s

zTestSystemAPIs.test_swap_memorycCstt�}|jtj|j��tj|j�}|j�|j�|jtj|j��|jtjd��|j	tjd�dtj
�k�dS)NrMrrY)rrdr/�
pid_existsr'r1r2r3r]r6rK)r"r:r;r#r#r$�test_pid_exists�szTestSystemAPIs.test_pid_existscCs�t�tj�}xF|D]>}yWqtk
rPtjd�|tj�krL|j|�YqXqWtt|�dt|�d�}x |D]}|j	tj
|�|d�qvWdS)Ng�������?i�ip)�msg)rr/rK�AssertionErrorr[�sleeprx�range�maxr]r�)r"rKr'r#r#r$�test_pid_exists_2�s


z TestSystemAPIs.test_pid_exists_2cCsJdd�tj�D�}tj�}|j|j�|j��|jt|�tt|���dS)NcSsg|]
}|j�qSr#)r')r(r)r#r#r$r*�sz,TestSystemAPIs.test_pids.<locals>.<listcomp>)r/r0rKr6�sortrTrc)r"ZplistZpidlistr#r#r$�	test_pids�szTestSystemAPIs.test_pidscCs&tj}tt_ztj�Wd|t_XdS)N)�sys�stdoutrr/rX)r"r�r#r#r$�	test_test�s
zTestSystemAPIs.test_testc
Cs�tj�}|j|ttjdd���|j|d�tjjd�rft	d��}|j
�}WdQRXd|krftjd��tjdd�}|j|d�|j||�dS)	NT)�percpurMz
/proc/cpuinfozphysical idz#cpuinfo doesn't include physical idF)�logical)
r/�	cpu_countr6rTr?rDr-�path�exists�open�readr ZSkipTest)r"r��fdZcpuinfo_dataZphysicalr#r#r$�test_cpu_counts

zTestSystemAPIs.test_cpu_countcCsfx`d	D]X}tjd|d��}|jtj��WdQRXtjd|d��}|jtjdd��WdQRXqWdS)
NrMrz$psutil._psplatform.cpu_count_logical)�return_valuez%psutil._psplatform.cpu_count_physicalF)r�rY)rYrN)rr5rCr/r�)r"�valrGr#r#r$�test_cpu_count_nones



z"TestSystemAPIs.test_cpu_count_nonecCs^d}tj�}t|�x,|D]$}|j|t�|j|d�||7}qW|j|t|��t|�dS)Nrg)r/r?�sumrkrlrDr6�str)r"rt�times�cp_timer#r#r$�test_cpu_timess
zTestSystemAPIs.test_cpu_timescCsDttj��}tjd�ttj��}||}|dks@|jd|�dS)Ng�������?g�������?z
difference %s)r�r/r?r[r�rx)r"�t1�t2�
differencer#r#r$�test_cpu_times_time_increases:s
z,TestSystemAPIs.test_cpu_times_time_increasescCs�xftjdd�D]V}d}t|�x,|D]$}|j|t�|j|d�||7}q$W|j|t|��t|�qW|jttjdd�d�ttjdd���dS)NT)r�rgF)	r/r?r�rkrlrDr6r�rT)r"r�rtr�r#r#r$�test_per_cpu_timesCs
z!TestSystemAPIs.test_per_cpu_timescCs�tjdd�}tj�d}xtj�|krPqWtjdd�}x<t||�D].\}}t|�t|�}}||}|dkrDdSqDW|j�dS)NT)r�g�������?g�������?)r/r?r[�zipr�rx)r"Ztot1Zstop_atZtot2r�r�r�r#r#r$�test_per_cpu_times_2dsz#TestSystemAPIs.test_per_cpu_times_2cCs\tj�}tjdd�}|jdd�t|�D��}x*|jD] }|jt||�t||�dd�q4WdS)NT)r�cSsg|]}t|��qSr#)r�)r(Znumr#r#r$r*ysz<TestSystemAPIs.test_cpu_times_comparison.<locals>.<listcomp>rM)�delta)r/r?�_maker�ru�assertAlmostEqualrv)r"�baseZper_cpuZ
summed_valuesZfieldr#r#r$�test_cpu_times_comparisontsz(TestSystemAPIs.test_cpu_times_comparisoncCs�y<|j|t�|j|d�|j|d�|j|dtj��Wn@tk
r|}z$td|tj	|�tj	|�f��WYdd}~XnXdS)NggY@z
%s
last=%s
new=%sg�)
rkrlrDZassertIsNot�assertLessEqualr/r�r��pprintZpformat)r"rsZlast_retZnew_ret�errr#r#r$�_test_cpu_percent~sz TestSystemAPIs._test_cpu_percentc
Csbtjdd�}x.td�D]"}tjdd�}|j|||�|}qW|jt��tjdd�WdQRXdS)Ng����MbP?)�interval�drMrY)r/�cpu_percentr�r�r9rB)r"�lastr)�newr#r#r$�test_cpu_percent�szTestSystemAPIs.test_cpu_percentcCs�tjddd�}|jt|�tj��x>td�D]2}tjddd�}x|D]}|j|||�qDW|}q,W|jt��tjddd�WdQRXdS)Ng����MbP?T)r�r�r�rMrY)	r/r�r6rTr�r�r�r9rB)r"r�r)r�rsr#r#r$�test_per_cpu_percent�s
z#TestSystemAPIs.test_per_cpu_percentcCs`tjdd�}xNtd�D]B}tjdd�}x|D]}|j|||�q,W|jt|�||�|}qWdS)Ng����MbP?)r�r�)r/�cpu_times_percentr�r�r�)r"r�r)r�rsr#r#r$�test_cpu_times_percent�s
z%TestSystemAPIs.test_cpu_times_percentcCs�tjddd�}|jt|�tj��x^td�D]R}tjddd�}x:|D]2}x|D]}|j|||�qNW|jt|�||�qDW|}q,WdS)Ng����MbP?T)r�r�r�)r/r�r6rTr�r�r�r�)r"r�r)r��cpursr#r#r$�test_per_cpu_times_percent�s

z)TestSystemAPIs.test_per_cpu_times_percentc
Csrtjdd�dd�tjdd�D�}tjd|d��8x0tjdd�D] }x|D]}|j|dd�qJWq@WWdQRXdS)NT)r�cSs*g|]"}|jdd�tt|j��D���qS)cSsg|]}d�qS)rr#)r(r)r#r#r$r*�szQTestSystemAPIs.test_per_cpu_times_percent_negative.<locals>.<listcomp>.<listcomp>)r�r�rTru)r(r)r#r#r$r*�szFTestSystemAPIs.test_per_cpu_times_percent_negative.<locals>.<listcomp>zpsutil.cpu_times)r�)r/r�r?rr5r�)r"Z
zero_timesr�rsr#r#r$�#test_per_cpu_times_percent_negative�s
z2TestSystemAPIs.test_per_cpu_times_percent_negativec
Cs�tjtj��}|j|jd	�ttd�rptjtj��}d}|j|j|j�|j	|j
|j
|d�|j	|j|j|d�tj
�}|jt��}tj|�WdQRX|j|jjtj�dS)Nrtr}r~rs�
disk_usage�i)r�)rtr}r~rsiiP)r/r�r-�getcwdr6rur^�shutilrtr�r~r}�tempfileZmktempr9�OSErrorZ	exception�errno�ENOENT)r"ZusageZshutil_usageZ	toleranceZfname�excr#r#r$�test_disk_usage�s
zTestSystemAPIs.test_disk_usagec	Cs(tr$|jt��tjt�WdQRXdS)N)rr9�UnicodeEncodeErrorr/r�r)r"r#r#r$�test_disk_usage_unicode�sz&TestSystemAPIs.test_disk_usage_unicodecCstjd�dS)N�.)r/r�)r"r#r#r$�test_disk_usage_bytes�sz$TestSystemAPIs.test_disk_usage_bytescCs�tjdd�}|j||d�xj|D]b}|j|jt�|j|jt�|j|jt�|j|jt�t	rld|jkrlq t
srn|jts�tr q q Wtjdd�}|j||d�x�tjdd�D]�}t	�s(yt
j|j�WnPtk
�r}z2tr�tr�|jtjkr�w�|jtjtjfk�r�WYdd}~XnXt�s(t�r(n|j|jt�|j|jt�q�Wdd�}|t�}dd	�tjdd�D�}|j||�tj|�dS)
NF)�all)r�ZcdromTcSs2tjj|�}xtjj|�s(tjj|�}qW|j�S)N)r-r��abspath�ismount�dirname�lower)r�r#r#r$�find_mount_pointsz=TestSystemAPIs.test_disk_partitions.<locals>.find_mount_pointcSsg|]}|jj��qSr#)�
mountpointr�)r(r)r#r#r$r*sz7TestSystemAPIs.test_disk_partitions.<locals>.<listcomp>)r/Zdisk_partitionsrdrkZdevicer�r�ZfstypeZoptsrr	r
rr-�statr�rr�ZEIOZEPERMZEACCES�__file__r,r�)r"�lsZdiskr�r�ZmountZmountsr#r#r$�test_disk_partitions�sH
z#TestSystemAPIs.test_disk_partitionscsl�fdd�}tjdd�}||�tjdd�}�j|g�x.|D]&}�j|��j|t�|||�q>WdS)Ncs��j|d|j��j|d|j��j|d|j��j|d|j��j|d|j��j|d|j��j|d|j��j|d|j�dS)	NrrMrRrO�r���)	r6Z
bytes_sentZ
bytes_recvZpackets_sentZpackets_recvZerrinZerroutZdropinZdropout)�nt)r"r#r$�check_ntuplesz9TestSystemAPIs.test_net_io_counters.<locals>.check_ntupleF)�pernicT)r/�net_io_counters�assertNotEqualrdrkr�)r"r��ret�keyr#)r"r$�test_net_io_counterss

z#TestSystemAPIs.test_net_io_counterscCsDtjdid��,}|jtjdd��|jtjdd�i�WdQRXdS)Nz"psutil._psplatform.net_io_counters)r�F)r�T)rr5rCr/r�r6)r"rGr#r#r$�test_net_io_counters_no_nics8s

z+TestSystemAPIs.test_net_io_counters_no_nicsc
Cshtj�}tj�}ttjtjtjg�}�x�|j�D�]�\}}|j	|t
�|jtt|��t|���x�|D�]�}|j	|j
t�|j	|jt
�|j	|jt
td�f�|j	|jt
td�f�|j|j
|�tjdkr�|j	|j
tj�||j�r�|j
tjk�r*tj|j
�}tj|��|j|jdf�WdQRXnj|j
tjk�r�tj|jdtjtjdtj�d}|\}	}
}}}
tj|	|
|�}tj|��|j|
�WdQRXxB|j|j|j|jfD]*}|dk	�r�|j
tjk�r�t ||j
��q�W|j�r�|j!|j�qf|jrf|j!|j�qfWq0Wt"�st#�st$�r8t%td��rd|jtjtj�n,t&�rP|jtjtj'�nt(�rd|jtjd�dS)NrOr�r�AF_LINKrM)rOr�rY))r/�net_if_addrs�net_if_statsrc�socketZAF_INETZAF_INET6r��itemsrkr�r6rTZfamilyrw�addressZnetmask�typeZ	broadcastr,r��version_infor�IntEnum�isup�
contextlib�closingZbindZgetaddrinfoZSOCK_STREAMZ
AI_PASSIVEZptprrCrrr
r^rZ	AF_PACKETr)r"�nicsZ	nic_statsZfamiliesZnicZaddrs�addr�sr@ZafZsocktype�protoZ	canonnameZsaZipr#r#r$�test_net_if_addrsAsV


z TestSystemAPIs.test_net_if_addrsc
Csptrdtjddddfg}ndg}tjd|d��8}tj�dd}trT|j|jd�n|j|jd	�WdQRXdS)N�em1z06:3d:29rM�06-3d-29zpsutil._psplatform.net_if_addrs)r�rz06:3d:29:00:00:00z06-3d-29-00-00-00rY)r�rYr�NNN)r	r/r�rr5r�r6r�)r"r�rGr�r#r#r$� test_net_if_addrs_mac_null_bytes}s
z/TestSystemAPIs.test_net_if_addrs_mac_null_byteszunreliable on TRAVISc	Cs�tj�}tjtjtjf}xh|j�D]\\}}|j|t�|\}}}}|j|t�|j	||�|j	||�|j
|d�|j
|d�q"WdS)Nr)r/r�ZNIC_DUPLEX_FULLZNIC_DUPLEX_HALFZNIC_DUPLEX_UNKNOWNr�rkr��boolr,rD)	r"r�Zall_duplexesrzZstatsr�ZduplexZspeedZmtur#r#r$�test_net_if_stats�sz TestSystemAPIs.test_net_if_statsz/proc/diskstatsz3/proc/diskstats not available on this linux versionNzunreliable on APPVEYORcs��fdd�}tjdd�}||�tjdd�}�jt|�tt|���xV|D]N}|||�trJ|dj�rJx|dj�r�|dd	�}qlW�j||j��qJWdS)
Ncs��j|d|j��j|d|j��j|d|j��j|d|j�tpNtsƈj|d|j��j|d|j�t	r��j|d|j
��j|d|j��j|d	|j�nt
rƈj|d|j�x|jD]}q�WdS)
NrrMrRrOr�r�r�r��)r6Z
read_countZwrite_countZ
read_bytesZwrite_bytesrrZ	read_timeZ
write_timerZread_merged_countZwrite_merged_countZ	busy_timerru)r�rz)r"r#r$r��sz:TestSystemAPIs.test_disk_io_counters.<locals>.check_ntupleF)�perdiskTrMrYrYrY)	r/�disk_io_countersr6rTrcr�isdigitr4rA)r"r�r�r�r#)r"r$�test_disk_io_counters�s
z$TestSystemAPIs.test_disk_io_counterscCsDtjdid��,}|jtjdd��|jtjdd�i�WdQRXdS)Nz#psutil._psplatform.disk_io_counters)r�F)r�T)rr5rCr/r�r6)r"rGr#r#r$�test_disk_io_counters_no_disks�s

z-TestSystemAPIs.test_disk_io_counters_no_disksz unreliable on APPVEYOR or TRAVIScCs�tj�}|j|g�x�|D]�}|j|jt�|j|jttd�f�|jdk	rb|j|jttd�f�|j|jt	j	j
|j�ts�t
r�|j|j�qtj|j�qWdS)N)r/�usersr�rkrzr�Zterminalr��host�datetimeZ
fromtimestampZstartedrrrCr'r1)r"r��userr#r#r$�
test_users�s

zTestSystemAPIs.test_userscCsZtj�}|j|jd�x>|jD]4}t||�}|j|d�tr|dkr|j|d�qWdS)N�ctx_switches�
interrupts�soft_interrupts�syscallsr)rrrr)rr)r/Z	cpu_statsr6rurvrDrrm)r"Zinfosrzr{r#r#r$�test_cpu_stats�s
zTestSystemAPIs.test_cpu_statsznot suportedcsT�fdd�}tjdd�}tr&|r&dS|tjdd�g�trP�jt|�tj��dS)Ncshxb|D]Z}�j|jd��j|j|j�x6|jD],}t||�}�j|ttt	f��j
|d�q0WqWdS)N�current�minr�r)rrr�)r6rur�rr�rvrkrwrrlrD)r�r�rzr{)r"r#r$�check_ls�s

z.TestSystemAPIs.test_cpu_freq.<locals>.check_lsT)r�F)r/Zcpu_freqrrr6rTr�)r"r	r�r#)r"r$�
test_cpu_freq�s	
zTestSystemAPIs.test_cpu_freqc	Cs8ddddddddd	g	}x"|D]}|jtt|�t|d
�qWtjdk�r|jd�dtjj	�krj|jd�n�d
tjj	�kr�|j
tjtjtj
gjd�d�|jd�|jd�|jd�|jd�nBdtjj	�ks�dtjj	�kr�|jd	�ndtjj	�k�r|jd�n
|jd�x$|D]}|jtt|�d|d
��qWdS)Nr	rrrrrrrr
)r��posix�linuxZbsdTrM�sunos�solaris�darwinF)rkrvr/r�r-rz�remover��platformr�r6rrr�countrF)r"�namesrzr#r#r$�test_os_constantss.







z TestSystemAPIs.test_os_constantsz
not supportedcCs�tj�}x�|j�D]x\}}|j|t�xb|D]Z}|j|jt�|jdk	rV|j|jd�|jdk	rn|j|jd�|j	dk	r,|j|j	d�q,WqWdS)Nr)
r/�sensors_temperaturesr�rkr��labelrrD�high�critical)r"�tempsrz�entries�entryr#r#r$�test_sensors_temperatures)s



z(TestSystemAPIs.test_sensors_temperaturesc
Csfddgi}tjd|d��D}tjdd	�dd
}|j|jd�|j|jd�|j|jd
�WdQRXdS)NZcoretempr�I@�N@��Q@z'psutil._psplatform.sensors_temperatures)r�T)Z
fahrenheitrg�^@g�a@g�c@)rrrr)rr5r/rr6rrr)r"�drGrr#r#r$�#test_sensors_temperatures_fahreneit7s

z2TestSystemAPIs.test_sensors_temperatures_fahreneitz
no batterycCsptj�}|j|jd�|j|jd�|jtjtjfkrF|j|jd�n|jtjkr^|j|j	�|j
|j	t�dS)Nrr�)r/Zsensors_batteryrDrsr�ZsecsleftZPOWER_TIME_UNKNOWNZPOWER_TIME_UNLIMITEDrdZ
power_pluggedrkr�)r"r�r#r#r$�test_sensors_batteryCs
z#TestSystemAPIs.test_sensors_batterycCsjtj�}x\|j�D]P\}}|j|t�x:|D]2}|j|jt�|j|jttf�|j	|jd�q,WqWdS)Nr)
r/Zsensors_fansr�rkr�rrrwrrD)r"Zfansrzrrr#r#r$�test_sensors_fansQs
z TestSystemAPIs.test_sensors_fans)C�__name__�
__module__�__qualname__�__doc__r%r&r<rIrirjrnr ZskipIfr	rrr|r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�rr-r�r�r
r/r�r�r�r�rrrr
rrrr!rrr"rr#r#r#r#r$r!;sh7	
		!

		
>	<#

%
r!�__main__)2r'r�r�r�r-r�r�rar�r�r�r[r/rrrrrrrr	r
rZpsutil._compatrZpsutil.testsr
rrrrrrrrrrrrrrrrrrr ZTestCaser!r$r�r#r#r#r$�<module>sh'
tests/__pycache__/test_misc.cpython-36.opt-1.pyc000064400000100354150466730540015512 0ustar003

��JZ���@s|dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*dd lm+Z+dd!lm,Z,dd"lm-Z-dd#lm.Z.dd$lm/Z/dd%lm0Z0dd&lm1Z1dd'lm2Z2dd(lm3Z3dd)lm4Z4dd*lm5Z5dd+lm6Z6dd,lm7Z7dd-lm8Z8dd.lm9Z9dd/lm:Z:dd0lm;Z;dd1lm<Z<ddl
Z
ddlZ
Gd2d3�d3e8j=�Z>ej?d4d5�Z@Gd6d7�d7e8j=�ZAe8jBe6d8�e8jBe7�o�ejCjDe2�d9�Gd:d;�d;e8j=���ZEGd<d=�d=e8j=�ZFGd>d?�d?e8j=�ZGGd@dA�dAe8j=�ZHGdBdC�dCe8j=�ZIGdDdE�dEe8j=�ZJGdFdG�dGe8j=�ZKeLdHk�rxe0eM�dS)Iz
Miscellaneous tests.
�N)�LINUX)�POSIX)�WINDOWS)�memoize)�memoize_when_activated)�
supports_ipv6)�wrap_numbers)�PY3)�APPVEYOR)�bind_socket)�bind_unix_socket)�
call_until)�chdir)�create_proc_children_pair)�create_sockets)�create_zombie_proc)�DEVNULL)�
get_free_port)�get_test_subprocess)�HAS_BATTERY)�HAS_CONNECTIONS_UNIX)�HAS_MEMORY_FULL_INFO)�HAS_MEMORY_MAPS)�HAS_SENSORS_BATTERY)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�import_module_by_path)�
is_namedtuple)�mock)�
PYTHON_EXE)�
reap_children)�
reload_module)�retry)�ROOT_DIR)�run_test_module_by_name)�safe_rmpath)�SCRIPTS_DIR)�sh)�tcp_socketpair)�TESTFN)�TOX)�TRAVIS)�unittest)�unix_socket_path)�unix_socketpair)�
wait_for_file)�wait_for_pidc@s�eZdZefdd�Zdd�Zefdd�Zefdd�Zefd	d
�Zefdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)S)*�TestMisccCsntj�}||�}|jd|�|jd|j|�|jd|�|j|j�|�tjjtjdtjt	j
��d��@tj�}||�}|jd|j|�|jd|�|jd|�WdQRXtjjtjdtjt	j
��d��@tj�}||�}|jd|j|�|jd|�|jd|�WdQRXtjjtjdtj
t	j
��d��4tj�}||�}|jd|j|�|jd|�WdQRXdS)Nzpsutil.Processzpid=%szname=�name)�side_effectZzombieZ
terminated)�psutil�Process�assertIn�pidr2r�patch�object�
ZombieProcess�os�getpid�assertNotIn�
NoSuchProcess�AccessDenied)�self�func�p�r�rD�!/usr/lib64/python3.6/test_misc.py�test_process__repr__Os4zTestMisc.test_process__repr__cCs|jtd�dS)N)rA)rF�str)r@rDrDrE�test_process__str__kszTestMisc.test_process__str__cCsN|jttjd��d�|jttjddd��d�|jttjddd��d�dS)NiAz7psutil.NoSuchProcess process no longer exists (pid=321)�foo)r2zCpsutil.NoSuchProcess process no longer exists (pid=321, name='foo'))�msgzpsutil.NoSuchProcess foo)�assertEqual�reprr4r>)r@rArDrDrE�test_no_such_process__repr__nsz%TestMisc.test_no_such_process__repr__cCsj|jttjd��d�|jttjddd��d�|jttjdddd��d�|jttjddd	��d
�dS)NiAzEpsutil.ZombieProcess process still exists but it's a zombie (pid=321)rI)r2zQpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo')�)r2�ppidzYpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo', ppid=1))rJzpsutil.ZombieProcess foo)rKrLr4r:)r@rArDrDrE�test_zombie_process__repr__zsz$TestMisc.test_zombie_process__repr__cCsN|jttjd��d�|jttjddd��d�|jttjddd��d�dS)NiAzpsutil.AccessDenied (pid=321)rI)r2z)psutil.AccessDenied (pid=321, name='foo'))rJzpsutil.AccessDenied foo)rKrLr4r?)r@rArDrDrE�test_access_denied__repr__�sz#TestMisc.test_access_denied__repr__cCsP|jttjd��d�|jttjddd��d�|jttjdddd��d�dS)	NiAz/psutil.TimeoutExpired timeout after 321 seconds�o)r7z9psutil.TimeoutExpired timeout after 321 seconds (pid=111)rI)r7r2zEpsutil.TimeoutExpired timeout after 321 seconds (pid=111, name='foo'))rKrLr4ZTimeoutExpired)r@rArDrDrE�test_timeout_expired__repr__�sz%TestMisc.test_timeout_expired__repr__cCs>tj�}tj�}|j||�d|_|j||�|j|d�dS)NrrI)rr)r4r5rKZ_ident�assertNotEqual)r@�p1�p2rDrDrE�test_process__eq__�szTestMisc.test_process__eq__cCs(ttj�tj�g�}|jt|�d�dS)NrN)�setr4r5rK�len)r@�srDrDrE�test_process__hash__�szTestMisc.test_process__hash__cCs�tt�}x�|D]~}|d
krq|jd
�syt|�Wqtk
r�|tjkr�tt|�}|dkr`w|jdk	r�d|jj�kr�|j	d|�YqXqWxtjD]}|j
||�q�WdS)N�callable�error�
namedtuple�tests�long�test�NUM_CPUS�	BOOT_TIME�TOTAL_PHYMEM�_Z
deprecatedz%r not in psutil.__all__)	r\r]r^r_r`rarbrcrd)�dirr4�
startswith�
__import__�ImportError�__all__�getattr�__doc__�lower�failr6)r@Z
dir_psutilr2ZfunrDrDrE�test__all__�s&




zTestMisc.test__all__cCs$|jdjdd�tjD��tj�dS)N�.cSsg|]}t|��qSrD)rG)�.0�xrDrDrE�
<listcomp>�sz)TestMisc.test_version.<locals>.<listcomp>)rK�joinr4�version_info�__version__)r@rDrDrE�test_version�szTestMisc.test_versioncCs"tj�}d|_|jd|j��dS)N�1rI)r4r5rIr=�as_dict)r@rBrDrDrE�!test_process_as_dict_no_new_names�sz*TestMisc.test_process_as_dict_no_new_namescst�fdd��}g�x:td�D].}|�}fif}|j||�|jt��d�qWx<td�D]0}|d�}d
if}|j||�|jt��d�qZWxDtd�D]8}|ddd�}dddif}|j||�|jt��d�q�W|j�|�}fif}|j||�|jt��d�|j|jd	�dS)Ncs�jd�||fS)z
foo docstringN)�append)�args�kwargs)�callsrDrErI�s
z"TestMisc.test_memoize.<locals>.foo�rN)�barr���z
foo docstring)rN)rN)r�rangerKrY�cache_clearrl)r@rIrr�retZexpectedrD)r~rE�test_memoize�s.zTestMisc.test_memoizecs�G�fdd�d�}|�}g�|j�|j�|jt��d�g�|jj�|j�|j�|jt��d�g�|jj�|j�|j�|jt��d�dS)NcseZdZe�fdd��ZdS)z1TestMisc.test_memoize_when_activated.<locals>.Foocs�jd�dS)N)r{)r@)r~rDrErI�sz5TestMisc.test_memoize_when_activated.<locals>.Foo.fooN)�__name__�
__module__�__qualname__rrIrD)r~rDrE�Foo�sr�rrN)rIrKrYZcache_activateZcache_deactivate)r@r��frD)r~rE�test_memoize_when_activated�s 

z$TestMisc.test_memoize_when_activatedcCs�ddlm}dd�}|j|d�|d�di�|j|d�|d�d|d	�d
i�|j|d�|d�d|d	�di�|j|d
�|d�d|d	�d
i�|j|d�|d�di�|j|d�|d�di�|j|d�|d�di�dS)Nr)�parse_environ_blockcSstr|j�S|S)N)r�upper)rZrDrDrE�ksz,TestMisc.test_parse_environ_block.<locals>.kza=1�arxz	a=1b=2�b�2za=1b=�z
a=1b=2c=3zxxxa=1z	a=1=b=2za=1b=2)�psutil._commonr�rK)r@r�r�rDrDrE�test_parse_environ_blocks



z!TestMisc.test_parse_environ_blockcCs�|jtj�t�r�tjd��}d|_tj�WdQRXtj�tjdtjd��}WdQRXtj�tjdtjd��}tj�WdQRXtj�tjdtjd��}tj�WdQRXn0|j	t
�� tjtjtj�}|j
d�WdQRXdS)	Nzpsutil._common.socketFzpsutil._common.socket.socket)r3z!psutil._common.socket.socket.bind�::1r)r�r)�
addCleanuprr�rr8Zhas_ipv6�socketr]Zgaierror�assertRaises�	Exception�AF_INET6�SOCK_STREAMZbind)r@rZ�sockrDrDrE�test_supports_ipv6%s.


zTestMisc.test_supports_ipv6cCs�ddlm}tjjt�}tjdtt	j
d�d��|jt||�WdQRXtjdtt	jd�d��|jt||�WdQRXtjdtt	j
d�d��WdQRXtjddd��WdQRXdS)	Nr)�
isfile_strictzpsutil._common.os.statrI)r3zpsutil._common.stat.S_ISREGF)�return_value)r�r�r;�path�abspath�__file__rr8�OSError�errnoZEPERMr�ZEACCES�EINVAL)r@r�Z	this_filerDrDrE�test_isfile_strictEs
zTestMisc.test_isfile_strictcs��fdd�}|tj�j��|tj��|tj��|tj��|tjdd��|tj��trpt	j
jd�rpnts�|tj
��|tj��|tjt	j���|tj��dS)Ncs<tdk	rtjtj|��tj|�}tj|�}�j||�dS)N)�json�loads�dumps�picklerK)r�r�r�)r@rDrE�checkWs


z*TestMisc.test_serialization.<locals>.checkr)�intervalz/proc/diskstats)r4r5ryZvirtual_memoryZswap_memoryZ	cpu_timesZcpu_times_percent�net_io_countersrr;r��existsr
�disk_io_countersZdisk_partitionsZ
disk_usage�getcwd�users)r@r�rD)r@rE�test_serializationVszTestMisc.test_serializationcCsVtjjtd�}tr*tjj|�r*|jd�St|�}|jt	|j
�|j|j�t
j�dS)Nzsetup.pyzcan't find setup.py)r;r�rtr#r+r�ZskipTestrr��
SystemExitZsetuprKZget_versionr4rv)r@Zsetup_py�modulerDrDrE�test_setup_scriptms
zTestMisc.test_setup_scriptcCs�tjjtjdtjd��}tj�WdQRXtjjtjdtjd�d��}tj�WdQRXtjjtjdtd��$}|jt��tj�WdQRXWdQRXdS)NZcreate_time)r3rN)	rr8r9r4r5r?r:�
ValueErrorr�)r@�methrDrDrE�test_ad_on_process_creationus


z$TestMisc.test_ad_on_process_creationcCsRtjddd��:|jt��}tt�WdQRX|jdt|j�j	��WdQRXdS)Nzpsutil._psplatform.cext.versionz0.0.0)r�zversion conflict)
rr8r�rir!r4r6rG�	exceptionrm)r@�cmrDrDrE�test_sanity_version_check�s
z"TestMisc.test_sanity_version_checkN)r�r�r�rLrFrHrMrPrQrSrWr[rorwrzr�r�r�r�r�r�r�r�r�rDrDrDrEr1Ms(# r1rIza b cc@s�eZdZdd�ZeZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zejej�p�ej�d�dd��ZdS)�TestWrapNumberscCstj�dS)N)rr�)r@rDrDrE�setUp�szTestWrapNumbers.setUpcCs&dtddd�i}|jt|d�|�dS)N�disk1��disk_io)�ntrKr)r@�inputrDrDrE�test_first_call�szTestWrapNumbers.test_first_callcCs8dtddd�i}|jt|d�|�|jt|d�|�dS)Nr�r�r�)r�rKr)r@r�rDrDrE�test_input_hasnt_changed�sz(TestWrapNumbers.test_input_hasnt_changedcCs�dtddd�i}|jt|d�|�dtddd�i}|jt|d�|�dtddd�i}|jt|d�|�dtddd�i}|jt|d�|�dS)	Nr�r�r��
����)r�rKr)r@r�rDrDrE�test_increase_but_no_wrap�sz)TestWrapNumbers.test_increase_but_no_wrapcCs�dtddd�i}|jt|d�|�dtddd�i}|jt|d�dtddd�i�dtddd�i}|jt|d�dtddd�i�dtddd�i}|jt|d�dtddd�i�dtddd�i}|jt|d�dtddd	�i�dtddd�i}|jt|d�dtddd	�i�dtd
dd�i}|jt|d�dtddd	�i�dtddd�i}|jt|d�dtddd	�i�dtddd�i}|jt|d�dtddd	�i�dS)
Nr��dr�r��n�Z�r����2��()r�rKr)r@r�rDrDrE�	test_wrap�s4zTestWrapNumbers.test_wrapcCstdtddd�i}|jt|d�|�tddd�tddd�d�}|jt|d�|�dtddd�i}|jt|d�|�dS)Nr�r�r��)r��disk2�)r�rKr)r@r�rDrDrE�test_changing_keys�s
z"TestWrapNumbers.test_changing_keyscCs.tddd�tddd�d�}|jt|d�|�tddd�tddd�d�}|jt|d�tddd�tddd�d��dtddd�i}|jt|d�|�tddd�tddd�d�}|jt|d�|�tddd�tddd�d�}|jt|d�|�tddd�tddd�d�}|jt|d�tddd�tddd�d��dS)Nr�r�)r�r�r�r�r�r�)r�rKr)r@r�rDrDrE�test_changing_keys_w_wrap�s*






z)TestWrapNumbers.test_changing_keys_w_wrapcCsbd'd(d)d*d"�}|jt|d#�|�|jt|d#�|�d+d,d-d.d"�}t|d#�}|j|d%dd&�dS)/N�,���#�R������ȷ�r�tU��rr��6��$��Nr��r����U	��"r����4����\)�nvme0n1Z	nvme0n1p1Z	nvme0n1p2Z	nvme0n1p3r�r�r�i�)	r�r�r�r�r�r�r�r�r�)	r�rr�r�r�rrrr�)	r�r�r�r�r�r�r�r�r�)	r�r�r�r�r�r�r�r�r�)	r�r�r�r�r�r�r�r�r�)	r�rr�r�r�rrrr�)	r�r�r�r�r�r�r�r�r�)	r�r�r�r�r�r�r�r�r�)rKr)r@�d�outrDrDrE�test_real_datas
zTestWrapNumbers.test_real_datacCsbdtddd�i}t|d�tj�}|j|dd|i�|j|ddii�|j|ddii�dS)Nr�r�r�rrNr)r�r�
cache_inforK)r@r��cacherDrDrE�test_cache_first_calls
z%TestWrapNumbers.test_cache_first_callc	Cs�dtddd�i}t|d�dtddd�i}t|d�tj�}|j|dd|i�|j|ddddd	dd
dii�|j|ddii�dS)Nr�r�r�r�rrNr)r�r)r�rN)r�r)r�rr�rK)r@r�r�rDrDrE�test_cache_call_twices

z%TestWrapNumbers.test_cache_call_twicec	s�dtddd�i}t|d�dtddd�i}t|d�tj�}�j|dd|i��j|ddd
dddddii��j|dddtdg�ii��fdd	�}dtddd�i}t|d�tj�}�j|dd|i�|�dtddd
�i}t|d�tj�}�j|dd|i�|�dtddd�i}t|d�tj�}�j|dd|i��j|ddddddddii��j|dddtdg�ii�dS)Nr�r�r�r�rrNrc	sJtj�}�j|ddddddd	dii��j|dddtd
g�ii�dS)NrNr�r�rrr�)r�r)r�rN)r�r)r�r)rr�rKrX)r�)r@rDrE�assert_4s

z0TestWrapNumbers.test_cache_wrap.<locals>.assert_r�r�r�)r�r)r�rN)r�r)r�r)r�r)r�rN)r�r)r�r)r�rr�rKrX)r@r�r�r�rD)r@rE�test_cache_wrap%s:





zTestWrapNumbers.test_cache_wrapc	Cs�dtddd�i}t|d�tddd�tddd�d�}t|d�tj�}|j|dd|i�|j|ddd	dd
dddii�|j|ddii�dS)Nr�r�r�r�)r�r�rrNr)r�r)r�rN)r�r)r�rr�rK)r@r�r�rDrDrE�test_cache_changing_keysUs


z(TestWrapNumbers.test_cache_changing_keyscCs\dtddd�i}t|d�t|d�tjd�|jtj�iiif�tjd�tjd�dS)Nr�r�r�z?!?)r�rr�rKr�)r@r�rDrDrE�test_cache_clearbs



z TestWrapNumbers.test_cache_clearzno disks or NICs availablecCs�tj�tj�tj�}x$|D]}|jd|�|jd|�qWtjj�tj�}x$|D]}|jd|�|jd|�qVWtjj�tj�}|j|iiif�dS)Nzpsutil.disk_io_counterszpsutil.net_io_counters)	r4r�r�rr�r6r�r=rK)r@Zcachesr�rDrDrE�test_cache_clear_public_apisks



z,TestWrapNumbers.test_cache_clear_public_apisN)r�r�r�r��tearDownr�r�r�r�r�r�r�r�r�r�r�rr,�skipIfr4r�r�rrDrDrDrEr��s"
%0
	r�zcan't test on TOXzcan't locate scripts directoryc@s�eZdZdZedd��Zed=dd��Zdd�Zej	e
d	�d
d��Zdd
�Zdd�Z
dd�Zdd�Zej	epxeoxej�d�dd��Zdd�Zdd�Zdd�Zej	ed�dd��Zej	ed �d!d"��Zej	ed �d#d$��Zd%d&�Zd'd(�Zd)d*�Zd+d,�Z d-d.�Z!ej	e"d/�d0d1��Z#d2d3�Z$ej	e%d �ej	ed�d4d5���Z&ej	e'd �ej	ed�d6d7���Z(ej	e)d �ej	e*d8�d9d:���Z+d;d<�Z,dS)>�TestScriptsz-Tests for scripts in the "scripts" directory.cOs�dtjjt|�}t|g}x|D]}|j|�q Wyt|f|�j�}Wn8tk
r~}zdt	|�krlt	|�S�WYdd}~XnX|S)Nz%sr?)
r;r�rtr&rr{r'�strip�RuntimeErrorrG)�exer|r}�cmd�argr��errrDrDrE�
assert_stdout�s
zTestScripts.assert_stdoutNc	CsRtjjt|�}tr"t|ddd�}n
t|d�}|�|j�}WdQRXtj|�dS)NZrt�utf8)�encoding)	r;r�rtr&r	�open�read�ast�parse)rr|r��srcrDrDrE�
assert_syntax�s
zTestScripts.assert_syntaxcCsZt|�}xLtjt�D]>}|jd�rdtjj|�d|kr|jdtjjt|��qWdS)Nz.pyZtest_rzno test defined for %r script)	rfr;�listdirr&�endswithr��splitextrnrt)r@Zmethsr2rDrDrE�
test_coverage�s
zTestScripts.test_coveragez
POSIX onlycCsTxNtjt�D]@}|jd�rtjjt|�}tjtj|�tj@s|j	d|�qWdS)Nz.pyz%r is not executable)
r;rr&rr�rt�stat�S_IXUSR�ST_MODErn)r@r2r�rDrDrE�test_executable�s

zTestScripts.test_executablecCs|jd�dS)Nz
disk_usage.py)r)r@rDrDrE�test_disk_usage�szTestScripts.test_disk_usagecCs|jd�dS)Nzfree.py)r)r@rDrDrE�	test_free�szTestScripts.test_freecCs|jd�dS)Nz
meminfo.py)r)r@rDrDrE�test_meminfo�szTestScripts.test_meminfocCs|jdttj���dS)Nzprocinfo.py)rrGr;r<)r@rDrDrE�
test_procinfo�szTestScripts.test_procinfoz unreliable on APPVEYOR or TRAVIScCs|jd�dS)Nzwho.py)r)r@rDrDrE�test_who�szTestScripts.test_whocCs|jd�dS)Nzps.py)r)r@rDrDrE�test_ps�szTestScripts.test_pscCs|jd�dS)Nz	pstree.py)r)r@rDrDrE�test_pstree�szTestScripts.test_pstreecCs|jd�dS)Nz
netstat.py)r)r@rDrDrE�test_netstat�szTestScripts.test_netstatzunreliable on TRAVIScCs|jd�dS)Nzifconfig.py)r)r@rDrDrE�
test_ifconfig�szTestScripts.test_ifconfigz
not supportedcCs|jdttj���dS)Nzpmap.py)rrGr;r<)r@rDrDrE�	test_pmap�szTestScripts.test_pmapcCs|jdtd�dS)Nzprocsmem.py)�stderr)rr)r@rDrDrE�
test_procsmem�szTestScripts.test_procsmemcCs|jd�dS)Nz
killall.py)r)r@rDrDrE�test_killall�szTestScripts.test_killallcCs|jd�dS)Nz	nettop.py)r)r@rDrDrE�test_nettop�szTestScripts.test_nettopcCs|jd�dS)Nztop.py)r)r@rDrDrE�test_top�szTestScripts.test_topcCs|jd�dS)Nziotop.py)r)r@rDrDrE�
test_iotop�szTestScripts.test_iotopcCs,|jdtj�j��}|jttj��|�dS)Nzpidof.py)rr4r5r2r6rGr;r<)r@�outputrDrDrE�
test_pidof�szTestScripts.test_pidofzWINDOWS onlycCs|jd�dS)Nzwinservices.py)r)r@rDrDrE�test_winservices�szTestScripts.test_winservicescCs|jd�dS)Nzcpu_distribution.py)r)r@rDrDrE�test_cpu_distribution�sz!TestScripts.test_cpu_distributioncCs|jd�dS)Nztemperatures.py)r)r@rDrDrE�test_temperatures�szTestScripts.test_temperaturescCs|jd�dS)Nzfans.py)r)r@rDrDrE�	test_fans�szTestScripts.test_fansz
no batterycCs|jd�dS)Nz
battery.py)r)r@rDrDrE�test_batteryszTestScripts.test_batterycCs|jd�dS)Nz
sensors.py)r)r@rDrDrE�test_sensorsszTestScripts.test_sensors)N)-r�r�r�rl�staticmethodrrrr,rrrrrrrr
r+r4r�r r!r"r#r$rr%rr'r(r)r*r+r-rr.r/rr0rr1rrr2r3rDrDrDrEr�s@

rc@sxeZdZejd�dd��Zejd�dd��Zejd�dd��Zejd�dd	��Zejd�d
d��Z	ejd�dd
��Z
dS)�TestRetryDecoratorz
time.sleepcsFtdddd��fdd��}ttd���|j|�d�|j|jd�dS)Nr�rN)�retriesr��logfuncsx�r�j�ddqWdS)NrNr)�poprD)�queuerDrErIsz2TestRetryDecorator.test_retry_success.<locals>.foor�)r"�listr�rK�
call_count)r@�sleeprIrD)r9rE�test_retry_successsz%TestRetryDecorator.test_retry_successcsDtdddd��fdd��}ttd���|jt|�|j|jd�dS)Nr�rN)r6r�r7csx�r�j�ddqWdS)NrNr)r8rD)r9rDrErI&sz2TestRetryDecorator.test_retry_failure.<locals>.foo�)r"r:r�r��ZeroDivisionErrorrKr;)r@r<rIrD)r9rE�test_retry_failure"sz%TestRetryDecorator.test_retry_failurecCs2ttdd�dd��}|jt|�|j|jd�dS)NrN)r�r�cSst�dS)N)�	TypeErrorrDrDrDrErI3sz2TestRetryDecorator.test_exception_arg.<locals>.foor)r"r�r�rArKr;)r@r<rIrDrDrE�test_exception_arg1sz%TestRetryDecorator.test_exception_argcCs4tdddd�dd��}|jt|�|j|jd�dS)Nr�)r6r�r7cSsdddS)NrNrrDrDrDrDrErI>sz4TestRetryDecorator.test_no_interval_arg.<locals>.foor)r"r�r?rKr;)r@r<rIrDrDrE�test_no_interval_arg:sz'TestRetryDecorator.test_no_interval_argcCs4tdddd�dd��}|jt|�|j|jd�dS)Nr�rN)r6r�r7cSsdddS)NrNrrDrDrDrDrErIHsz0TestRetryDecorator.test_retries_arg.<locals>.foo)r"r�r?rKr;)r@r<rIrDrDrE�test_retries_argEsz#TestRetryDecorator.test_retries_argcCs|jttddd�dS)Nr�rN)r6Ztimeout)r�r�r")r@r<rDrDrE�test_retries_and_timeout_argsOsz0TestRetryDecorator.test_retries_and_timeout_argsN)r�r�r�rr8r=r@rBrCrDrErDrDrDrEr5s	
r5c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�TestSyncTestUtilscCstt�dS)N)r%r))r@rDrDrErVszTestSyncTestUtils.tearDowncCsPttj��ttj��d}tjdtdg�d��|j	tj
t|�WdQRXdS)Ni��zpsutil.tests.retry.__iter__r)r�)r0r;r<�maxr4Zpidsrr8�iterr�r>)r@ZnopidrDrDrE�test_wait_for_pidYsz#TestSyncTestUtils.test_wait_for_pidc	Cs,ttd��}|jd�WdQRXtt�dS)N�wrI)rr)�writer/)r@r�rDrDrE�test_wait_for_file_sz$TestSyncTestUtils.test_wait_for_filecCs&ttd��WdQRXttdd�dS)NrJT)�empty)rr)r/)r@rDrDrE�test_wait_for_file_emptyes
z*TestSyncTestUtils.test_wait_for_file_emptycCs2tjdtdg�d��|jttt�WdQRXdS)Nzpsutil.tests.retry.__iter__r)r�)rr8rHr��IOErrorr/r))r@rDrDrE�test_wait_for_file_no_fileksz,TestSyncTestUtils.test_wait_for_file_no_filecCs0ttd��}|jd�WdQRXttdd�dS)NrJrIF)�delete)rr)rKr/)r@r�rDrDrE�test_wait_for_file_no_deleteosz.TestSyncTestUtils.test_wait_for_file_no_deletecCstdd�d�}|j|d�dS)NcSsdS)NrNrDrDrDrDrE�<lambda>vsz3TestSyncTestUtils.test_call_until.<locals>.<lambda>zret == 1rN)r
rK)r@r�rDrDrE�test_call_untilusz!TestSyncTestUtils.test_call_untilN)
r�r�r�rrIrLrNrPrRrTrDrDrDrErFTsrFc@s(eZdZdd�ZeZdd�Zdd�ZdS)�TestFSTestUtilscCstt�dS)N)r%r))r@rDrDrEr�|szTestFSTestUtils.setUpcCstttd�j�tt�tt�tjt�tt�tjdtt	j
d�d��$}|jt��tt�WdQRXWdQRXdS)NrJzpsutil.tests.os.statr�)r3)rr)�closer%r;�mkdirrr8r�r�r�r�)r@�mrDrDrE�test_safe_rmpath�s
z TestFSTestUtils.test_safe_rmpathcCsTtj�}tjt�tt�� |jtj�tjj|t��WdQRX|jtj�|�dS)N)r;r�rWr)rrKr�rt)r@�baserDrDrE�
test_chdir�s


$zTestFSTestUtils.test_chdirN)r�r�r�r�rrYr[rDrDrDrErUzsrUc@s2eZdZdd�Zdd�Zejed�dd��ZdS)	�TestProcessUtilscCst�}tj|j�}t�dS)N)rr4r5r7r )r@ZsubprBrDrDrE�test_reap_children�sz#TestProcessUtils.test_reap_childrencCs�t�\}}|j|j|j�tj�jdd�}|jt|�d�|j||�|j||�|j|j	�t
j��|j|j	�|j�t�dS)NT)�	recursiver)
rrTr7r4r5�childrenrKrYr6rOr;r<r )r@rUrVr_rDrDrE�test_create_proc_children_pair�s
z/TestProcessUtils.test_create_proc_children_pairz
POSIX onlycCs4t�}|jtdd�tj|�}|j|j�tj�dS)NT)r^)rr�r r4r5rKZstatusZ
STATUS_ZOMBIE)r@ZzpidrBrDrDrE�test_create_zombie_proc�s
z(TestProcessUtils.test_create_zombie_procN)	r�r�r�r]r`r,rrrarDrDrDrEr\�s	r\c@sPeZdZdd�Zejed�dd��Zdd�Zejed�dd	��Z	d
d�Z
dS)
�TestNetUtilsc
Cs>t�}tjtd|fd���}|j|j�d|�WdQRXdS)Nr�)�addrrN)r�
contextlib�closingrrK�getsockname)r@ZportrZrDrDrEr�szTestNetUtils.bind_socketz
POSIX onlycCs�t��T}t|�}tj|��6|j|jtj�|j|jtj	�|j|j
�|�WdQRXWdQRXt��:}t|tjd�}tj|��|j|jtj�WdQRXWdQRXdS)N)�type)r-rrdrerK�familyr��AF_UNIXrgr�rf�
SOCK_DGRAM)r@r2r�rDrDrE�test_bind_unix_socket�sz"TestNetUtils.test_bind_unix_socketcCs|dt�f}ttj|d�\}}tj|��Ltj|��6|j|j�|�|j|j�|�|j	|j�|�WdQRXWdQRXdS)Nz	127.0.0.1)rc)
rr(r��AF_INETrdrerKrf�getpeernamerT)r@rc�server�clientrDrDrE�tcp_tcp_socketpair�s
zTestNetUtils.tcp_tcp_socketpaircCs�tj�}|j�}t��v}t|�\}}zP|j|j�|d�|jt|jdd��d�|j|j�|�|j|j	�|�Wd|j
�|j
�XWdQRXdS)NrZunix)Zkind)r4r5�num_fdsr-r.rKrYZconnectionsrfrmrV)r@rBrqr2rnrorDrDrE�test_unix_socketpair�sz!TestNetUtils.test_unix_socketpaircCs�t���}tjt�}tjt�}x:|D]2}||jd7<||jtjtj�d7<q"W|j	|tj
d�t�r�|j	|tjd�t
r�tr�|j	|tjd�|j	|tjd�|j	|tjd�WdQRXdS)NrNr)r�collections�defaultdict�intrhZ
getsockoptr�Z
SOL_SOCKETZSO_TYPEZassertGreaterEqualrlrr�rrrir�rj)r@ZsocksZfams�typesrZrDrDrE�test_create_sockets�s


 z TestNetUtils.test_create_socketsN)r�r�r�rr,rrrkrprrrwrDrDrDrErb�s
rbc@seZdZdd�ZdS)�TestOtherUtilscCsdS)NrD)r@rDrDrE�test_is_namedtuplesz!TestOtherUtils.test_is_namedtupleN)r�r�r�ryrDrDrDrErxsrx�__main__)Nrlrrsrdr�r�r;r�r�rr4rrrr�rrrrZpsutil._compatr	Zpsutil.testsr
rrr
rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0ZTestCaser1r^r�r�rr�r�rr5rFrUr\rbrxr�r�rDrDrDrE�<module>	s�Ip
C&!&E
tests/__pycache__/test_unicode.cpython-36.opt-1.pyc000064400000025604150466730550016212 0ustar003

��JZ[2�@s�dZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddlm
Z
ddlmZdd	lm
Z
dd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&ddlZddlZd!d"�Zd#d$�Z'e
�r�e"j(d%�d&j)d%d'�Z*ne"d(Z*Gd)d*�d*e+�Z,e%j-e	�o�e$d+�e%j-ed,�e%j-e'e#�d-�Gd.d/�d/e,e%j.����Z/e%j-e	�o*e$d+�e%j-e'e*�d0�Gd1d2�d2e,e%j.���Z0e%j-ed3�Gd4d5�d5e%j.��Z1Gd6d7�d7e%j.�Z2e3d8k�r�ee4�dS)9a�
Notes about unicode handling in psutil
======================================

In psutil these are the APIs returning or dealing with a string
('not tested' means they are not tested to deal with non-ASCII strings):

* Process.cmdline()
* Process.connections('unix')
* Process.cwd()
* Process.environ()
* Process.exe()
* Process.memory_maps()
* Process.name()
* Process.open_files()
* Process.username()             (not tested)

* disk_io_counters()             (not tested)
* disk_partitions()              (not tested)
* disk_usage(str)
* net_connections('unix')
* net_if_addrs()                 (not tested)
* net_if_stats()                 (not tested)
* net_io_counters()              (not tested)
* sensors_fans()                 (not tested)
* sensors_temperatures()         (not tested)
* users()                        (not tested)

* WindowsService.binpath()       (not tested)
* WindowsService.description()   (not tested)
* WindowsService.display_name()  (not tested)
* WindowsService.name()          (not tested)
* WindowsService.status()        (not tested)
* WindowsService.username()      (not tested)

In here we create a unicode path with a funky non-ASCII name and (where
possible) make psutil return it back (e.g. on name(), exe(), open_files(),
etc.) and make sure that:

* psutil never crashes with UnicodeDecodeError
* the returned path matches

For a detailed explanation of how psutil handles unicode see:
- https://github.com/giampaolo/psutil/issues/1040
- http://psutil.readthedocs.io/#unicode
�N)�closing)�BSD)�OPENBSD)�OSX)�POSIX)�WINDOWS)�PY3)�u)�APPVEYOR)�ASCII_FS)�bind_unix_socket)�chdir)�copyload_shared_lib)�
create_exe)�get_test_subprocess)�HAS_CONNECTIONS_UNIX)�HAS_ENVIRON)�HAS_MEMORY_MAPS)�mock)�
reap_children)�run_test_module_by_name)�
safe_mkdir)�safe_rmpath)�skip_on_access_denied)�TESTFILE_PREFIX)�TESTFN)�TESTFN_UNICODE)�TRAVIS)�unittest)�unix_socket_pathcCs8tr,yt|�Stk
r(tj�Yq4Xnt|�SdS)N)r
�_safe_rmpathZWindowsError�	traceback�	print_exc)�path�r$�$/usr/lib64/python3.6/test_unicode.pyr\srcCsTtrdSz>y t|�t|�t|gd�Wntk
r>dSXdSWdt�XdS)z`Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    T)�cmdFN)rrrr�UnicodeEncodeErrorr)�namer$r$r%�subprocess_supports_unicodepsr)�utf8sf���surrogateescapeufc@s�eZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
ejed�dd��Zejed�ejed�e�dd����Zdd�Zejed�ejed�dd���ZdS) �_BaseFSAPIsTestsNcCst|j�t|j�dS)N)r�
funky_namer)�clsr$r$r%�
setUpClass�s
z_BaseFSAPIsTests.setUpClasscCst�t|j�dS)N)rrr-)r.r$r$r%�
tearDownClass�sz_BaseFSAPIsTests.tearDownClasscCs
t�dS)N)r)�selfr$r$r%�tearDown�sz_BaseFSAPIsTests.tearDowncCstd��dS)Nzmust be implemented in subclass)�NotImplementedError)r1r$r$r%�expect_exact_path_match�sz(_BaseFSAPIsTests.expect_exact_path_matchcCsHt|jgd�}tj|j�}|j�}|j|t�|j�rD|j	||j�dS)N)r&)
rr-�psutil�Process�pid�exe�assertIsInstance�strr4�assertEqual)r1�subp�pr8r$r$r%�
test_proc_exe�sz_BaseFSAPIsTests.test_proc_execCs�t|jgd�}trHtjdtjtj��d��}tj	|j
�j�}WdQRXntj	|j
�j�}|j|t
�|j�r�|j|tjj|j��dS)N)r&z psutil._psplatform.cext.proc_exe)�side_effect)rr-rr�patchr5�AccessDenied�os�getpidr6r7r(r9r:r4r;r#�basename)r1r<�mr(r$r$r%�test_proc_name�sz_BaseFSAPIsTests.test_proc_namecCsXt|jgd�}tj|j�}|j�}x|D]}|j|t�q(W|j�rT|j	||jg�dS)N)r&)
rr-r5r6r7�cmdliner9r:r4r;)r1r<r=rG�partr$r$r%�test_proc_cmdline�s
z"_BaseFSAPIsTests.test_proc_cmdlinec
Csj|jd}|jt|�t|�t|��tj�}|j�}WdQRX|j|j�t	�|j
�rf|j||�dS)N�2)r-�
addCleanuprrr
r5r6�cwdr9r:r4r;)r1�dnamer=rLr$r$r%�
test_proc_cwd�s

z_BaseFSAPIsTests.test_proc_cwdcCs�tj�}t|j��}t|jd��t|j��}WdQRX||j�j}|j|t	�t
rf|rf|jd�S|j�r�|j
tjj|�tjj|j��dS)N�rbzopen_files on BSD is broken)r5r6�setZ
open_files�openr-�popr#r9r:rZskipTestr4r;rB�normcase)r1r=�start�newr#r$r$r%�test_proc_open_files�s

z%_BaseFSAPIsTests.test_proc_open_filesz
POSIX onlycCs�tjj|j�}t|d���}yt|�}Wn&tk
rLtr>�n
tj	d��YnXt
|��8tj�j
d�d}|j|jt�ts�|j|j|�WdQRXWdQRXdS)N)�suffixz
not supported�unixr)rBr#rDr-rrr'rr�SkipTestrr5r6Zconnectionsr9�laddrr:rr;)r1rWr(�sock�connr$r$r%�test_proc_connections�s
z&_BaseFSAPIsTests.test_proc_connectionszcan't list UNIX socketscCs�dd�}tjj|j�}t|d���}yt|�}Wn&tk
rTtrF�n
tj	d��YnXt
|��:tjdd�}t
s�||�}|j|jt�|j|j|�WdQRXWdQRXdS)NcSs2x$|D]}tjj|j�jt�r|SqWtd��dS)Nzconnection not found)rBr#rDrZ�
startswithr�
ValueError)�consr\r$r$r%�	find_sock�s
z8_BaseFSAPIsTests.test_net_connections.<locals>.find_sock)rWz
not supportedrX)Zkind)rBr#rDr-rrr'rrrYrr5Znet_connectionsrr9rZr:r;)r1rarWr(r[r`r\r$r$r%�test_net_connections�s
z%_BaseFSAPIsTests.test_net_connectionscCs,|jd}|jt|�t|�tj|�dS)NrJ)r-rKrrr5Z
disk_usage)r1rMr$r$r%�test_disk_usage	s
z _BaseFSAPIsTests.test_disk_usagez
not supportedz&ctypes does not support unicode on PY2csvt|jd��`}dd���fdd�tj�j�D�}dd�|D�}|j�|�|�x|D]}|j|t�qTWWdQRXdS)N)Z
dst_prefixcSstjjtjj|��S)N)rBr#�realpathrS)r=r$r$r%�normpathsz3_BaseFSAPIsTests.test_memory_maps.<locals>.normpathcsg|]}�|j��qSr$)r#)�.0�x)rer$r%�
<listcomp>sz5_BaseFSAPIsTests.test_memory_maps.<locals>.<listcomp>cSsg|]}t|kr|�qSr$)r)rfrgr$r$r%rhs)rr-r5r6Zmemory_mapsZassertInr9r:)r1Z
funky_pathZlibpathsr#r$)rer%�test_memory_mapss

z!_BaseFSAPIsTests.test_memory_maps)�__name__�
__module__�__qualname__r-�classmethodr/r0r2r4r>rFrIrNrVr�skipIfrr]rrrbrcrrrir$r$r$r%r,�s"	r,zunreliable on TRAVISzASCII fsz"subprocess can't deal with unicodec@s eZdZdZeZedd��ZdS)�
TestFSAPIsz1Test FS APIs with a funky, valid, UTF8 path name.c
CsNtrdSt|jt�rdntd�}tj��tjd�|jtj	|�kSQRXdS)NT�.�ignore)
r�
isinstancer-r:r	�warnings�catch_warnings�simplefilterrB�listdir)r.�herer$r$r%r4(s

z"TestFSAPIs.expect_exact_path_matchN)rjrkrl�__doc__rr-rmr4r$r$r$r%ro sroz*subprocess can't deal with invalid unicodec@s eZdZdZeZedd��ZdS)�TestFSAPIsWithInvalidPathz-Test FS APIs with a funky, invalid path name.cCsdS)NTr$)r.r$r$r%r4<sz1TestFSAPIsWithInvalidPath.expect_exact_path_matchN)rjrkrlrx�INVALID_NAMEr-rmr4r$r$r$r%ry5sryzWINDOWS onlyc@seZdZdd�ZdS)�TestWinProcessNamec
Cs<tjdtjtj��d��}|jtj�j�t	�WdQRXdS)Nz psutil._psplatform.cext.proc_exe)r?)
rr@r5rArBrCr9r6r(r:)r1rEr$r$r%�test_name_typeEsz!TestWinProcessName.test_name_typeN)rjrkrlr|r$r$r$r%r{Bsr{c@s.eZdZdZdd�Zejed�dd��ZdS)�
TestNonFSAPISz&Unicode tests for non fs-related APIs.cCs
t�dS)N)r)r1r$r$r%r2WszTestNonFSAPIS.tearDownz
not supportedcCs~tjj�}trtnd}||d<t|d�}tj|j�}|j�}x,|j	�D] \}}|j
|t�|j
|t�qFW|j|d|�dS)N�èZ	FUNNY_ARG)�env)
rB�environ�copyrrrr5r6r7�itemsr9r:r;)r1rZ	funky_strZsprocr=�k�vr$r$r%�test_proc_environZs

zTestNonFSAPIS.test_proc_environN)	rjrkrlrxr2rrnrr�r$r$r$r%r}Tsr}�__main__)5rxrBr!rs�
contextlibrr5rrrrrZpsutil._compatrr	Zpsutil.testsr
rrr
rrrrrrrrrrrr rrrrrrrr)�encode�decoderz�objectr,rnZTestCaseroryr{r}rj�__file__r$r$r$r%�<module>4sr




tests/__pycache__/test_windows.cpython-36.pyc000064400000067407150466730550015326 0ustar003

��JZK�@s`dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlm
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZej��Zejd�y$ddlZddlZddlZddlZWn$e k
�rDej!dk�r@�YnXWdQRXej"j#Z#e	j$d$kZ%dd�Z&ej'e
d�Gdd�dej(��Z)ej'e
d�Gdd�dej(��Z*ej'e
d�Gdd�dej(��Z+ej'e
d�Gdd�dej(��Z,ej'e
d�Gdd�dej(��Z-ej'e
d�Gdd �d ej(��Z.ej'e
d�Gd!d"�d"ej(��Z/e0d#k�r\ee1�dS)%zWindows specific tests.�N)�WINDOWS)�callable)�APPVEYOR)�get_test_subprocess)�HAS_BATTERY)�mock)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�unittest�ignore�nt�� cs�fdd�}|S)Ncsty�|f|�|�Stk
rn}zBddlm}|j|krDtjdd��|jtjkr\tjdd���WYdd}~XnXdS)Nr)�ACCESS_DENIED_SET)�OSErrorZpsutil._pswindowsr�errno�psutil�AccessDeniedZESRCH�
NoSuchProcess)�self�args�kwargs�errr)�fun��$/usr/lib64/python3.6/test_windows.py�wrapper5s
z wrap_exceptions.<locals>.wrapperr)rrr)rr�wrap_exceptions4s
rzWINDOWS onlyc@s�eZdZdd�Zejdejkd�dd��Zdd�Z	d	d
�Z
dd�Zejed
�e
�dd���Ze
�dd��Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)�TestSystemAPIscCsVtd�}tjdd�j�}x8|D]0}d|jdd�j�kr8q||kr|jd|�qWdS)Nz
ipconfig /allT)Zperniczpseudo-interface� �-z-%r nic wasn't found in 'ipconfig /all' output)rrZnet_io_counters�keys�replace�lower�fail)r�outZnicsZnicrrr�test_nic_namesJs
zTestSystemAPIs.test_nic_names�NUMBER_OF_PROCESSORSz-NUMBER_OF_PROCESSORS env var is not availablecCs"ttjd�}|j|tj��dS)Nr))�int�os�environ�assertEqualr�	cpu_count)rZnum_cpusrrr�test_cpu_countTszTestSystemAPIs.test_cpu_countcCs$tj�d}tj�}|j||�dS)N�)�win32apiZ
GetSystemInforr.r-)r�	sys_value�psutil_valuerrr�test_cpu_count_2ZszTestSystemAPIs.test_cpu_count_2cCs@tj�}|j�d}|j|jtj�j�|j|jtj�j	�dS)Nr)
�wmi�WMIZWin32_Processorr-ZCurrentClockSpeedrZcpu_freqZcurrentZ
MaxClockSpeed�max)r�w�procrrr�
test_cpu_freq_szTestSystemAPIs.test_cpu_freqcCs,tj�j�d}|jt|j�tj�j�dS)Nr)	r5r6ZWin32_ComputerSystemr-r*ZTotalPhysicalMemoryrZvirtual_memory�total)rr8rrr�test_total_phymemesz TestSystemAPIs.test_total_phymemztest not relieable on appveyorcCs:tj�j�}tdd�|D��}ttj��}|j||�dS)NcSsg|]
}|j�qSr)�	ProcessId)�.0�xrrr�
<listcomp>|sz,TestSystemAPIs.test_pids.<locals>.<listcomp>)r5r6�
Win32_Process�setrZpidsr-)rr8Zwmi_pidsZpsutil_pidsrrr�	test_pidsvszTestSystemAPIs.test_pidscCstjdd�}tj�j�}x�|D]�}x�|D]�}|jjdd�|jkr(|jsHPytj	|j�}Wn4t
k
r�}z|jtjkrzPn�WYdd}~XnX|j
|jt|j��t|j�}|j
|j|�t|j|�d
kr�|jd|j|f�Pq(W|jdt|��qWdS)NT)�all�\��
izpsutil=%s, wmi=%szcan't find partition %si(i�)r�disk_partitionsr5r6ZWin32_LogicalDiskZdevicer$ZDeviceID�
mountpoint�
disk_usagerr�ENOENTr-r;r*ZSizeZ	FreeSpace�free�absr&�repr)rZps_partsZ	wmi_partsZps_partZwmi_partZusagerZwmi_freerrr�
test_disks�s*


zTestSystemAPIs.test_diskscCspxjtj�D]^}tj|j�}tj|j�}|j|d|jdd�|j|d|jdd�|j	|j
|j|j�q
WdS)Nri)�delta�ii)rrHr1ZGetDiskFreeSpaceExrIrJ�assertAlmostEqualrLr;r-Zused)rZdiskr2r3rrr�test_disk_usage�szTestSystemAPIs.test_disk_usagecCs>dd�tj�jd�D�}dd�tjdd�D�}|j||�dS)NcSs$g|]}|r|jd�r|d�qS)zA:rE)�
startswith)r>r?rrrr@�sz7TestSystemAPIs.test_disk_partitions.<locals>.<listcomp>z\cSsg|]
}|j�qSr)rI)r>r?rrrr@�sT)rD)r1ZGetLogicalDriveStrings�splitrrHr-)rr2r3rrr�test_disk_partitions�sz#TestSystemAPIs.test_disk_partitionscCs`ttj��}tj�j�}t�}x$|D]}|j|j�|j|j�q$W|j	||@d||f�dS)Nzno common entries in %s, %s)
rB�cextZnet_if_statsr5r6ZWin32_NetworkAdapter�add�NameZNetConnectionID�
assertTrue)rZps_namesZwmi_adaptersZ	wmi_namesZwmi_adapterrrr�test_net_if_stats�s

z TestSystemAPIs.test_net_if_statscCs^tj�j�}|djjd�d}tjj|d�}tjjtj	��}t
||j��}|j|d�dS)Nr�.z%Y%m%d%H%M%S�)
r5r6ZWin32_OperatingSystemZLastBootUpTimerU�datetimeZstrptimeZ
fromtimestampr�	boot_timerMZ
total_secondsZassertLessEqual)rZwmi_osZ
wmi_btime_strZwmi_btime_dtZ	psutil_dtZdiffrrr�test_boot_time�szTestSystemAPIs.test_boot_timecCs�tjddd��|jtj�d�WdQRXtjddd��|jtj�d�WdQRXtjddd��|jtj�d�WdQRXtjddd��|jtj�d�WdQRXdS)Nz psutil._pswindows.cext.boot_timer0)�return_value��iM)r�patchr-rr_)rrrr�test_boot_time_fluctuation�sz)TestSystemAPIs.test_boot_time_fluctuationN)�__name__�
__module__�__qualname__r(r�skipIfr+r,r/r4r:r<rr	rCrOrSrVr[r`rerrrrr Gs

	

r c@s`eZdZdd�Zejed�dd��Zejed�dd��Zdd	�Z	d
d�Z
dd
�Zdd�ZdS)�TestSensorsBatterycCs.tj�dr|jtj��n|jtj��dS)NZSystemBatteriesPresent)r1ZGetPwrCapabilitiesZassertIsNotNoner�sensors_battery�assertIsNone)rrrr�test_has_battery�sz#TestSensorsBattery.test_has_batteryz
no batterycCs6tj�}|jd�d}tj�}|j|j|jdd�dS)Nzselect * from Win32_BatteryrrQ)rP)r5r6�queryrrkrRZpercentZEstimatedChargeRemaining)rr8�battery_wmi�battery_psutilrrr�test_percent�szTestSensorsBattery.test_percentcCs6tj�}|jd�d}tj�}|j|j|jdk�dS)Nzselect * from Win32_Batteryrr)r5r6rnrrkr-Z
power_pluggedZ
BatteryStatus)rr8rorprrr�test_power_plugged�s
z%TestSensorsBattery.test_power_pluggedc	Cs6tjddd��}|jtj��|js(t�WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr�)ra)rrsrr)rrdrlrrk�called�AssertionError)r�mrrr�test_emulate_no_battery�s
z*TestSensorsBattery.test_emulate_no_batteryc
Cs<tjddd��$}|jtj�jtj�|js.t�WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrQr)ra)rQrrr)	rrdr-rrk�secsleft�POWER_TIME_UNLIMITEDrtru)rrvrrr�test_emulate_power_connected�s

z/TestSensorsBattery.test_emulate_power_connectedc
Cs<tjddd��$}|jtj�jtj�|js.t�WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr�)ra)rr{rr)	rrdr-rrkrxryrtru)rrvrrr�test_emulate_power_charging�s

z.TestSensorsBattery.test_emulate_power_chargingc
Cs<tjddd��$}|jtj�jtj�|js.t�WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrrQ)ra���)rrrr})	rrdr-rrkrxZPOWER_TIME_UNKNOWNrtru)rrvrrr�test_emulate_secs_left_unknowns

z1TestSensorsBattery.test_emulate_secs_left_unknownN)
rfrgrhrmrrirrqrrrwrzr|r~rrrrrj�s	
rjc@s�eZdZedd��Zedd��Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Ze
jejd+kd�dd��Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*S),�TestProcesscCst�j|_dS)N)r�pid)�clsrrr�
setUpClassszTestProcess.setUpClasscCs
t�dS)N)r)r�rrr�
tearDownClassszTestProcess.tearDownClasscCstjd�}|jtj|j�dS)Nr)r�Process�assertRaisesr�kill)r�prrr�
test_issue_24s
zTestProcess.test_issue_24cCs�tjd�}|j|j�d�t|�|j�|j|j�dk�y|j�dd�\}}Wn(tj	k
r|t
j�dd
krx�YnX|j|d	k�dS)NrbZSystemgrrQ�vista�win-7�win7r)r�r�r�)rr�r-�name�str�usernamerZ�create_time�memory_infor�platform�uname)rr��rss�vmsrrr�test_special_pid s
zTestProcess.test_special_pidcCs"tj|j�}|jt|jtj�dS)N)rr�r�r��
ValueError�send_signal�signal�SIGINT)rr�rrr�test_send_signal1szTestProcess.test_send_signalcCsNxHtj�D]<}y |jtjj|j��|j��Wq
tjk
rDYq
Xq
WdS)N)	r�process_iterr-r+�path�basename�exer��Error)rr�rrr�test_exe5s
 zTestProcess.test_execCsbtjtj��}|j�}tjtjtj	tj��}|j�}|j
||d�tj|�|j
|j�|�dS)NrQ)rr�r+�getpid�num_handlesr1�OpenProcess�win32con�PROCESS_QUERY_INFORMATION�FALSEr-�CloseHandle)rr�Zbefore�handle�afterrrr�test_num_handles_increment<s
z&TestProcess.test_num_handles_incrementc
s��fdd�}tj|j�}g}x�ttj�D]���jd�s(�dkrBq(q(y(||��|j�}||��|j�}Wntjtjfk
r�Yq(X||kr(d�||f}|j|�q(W|r�|j	ddj
|��dS)Ncs,t|�d�}|dk	r$t|�r$|�n|dS)N)�getattrr)r��attr)r�rr�callJsz+TestProcess.test_handles_leak.<locals>.call�_�	terminater��suspend�resume�nicer��wait�children�as_dict�memory_info_exz@failure while processing Process.%s method (before=%s, after=%s)�
)
r�r�r�r�r�r�r�r�r�r�)rr�r��dirrTr�rr�appendr&�join)rr�r�ZfailuresZnum1Znum2r&r)r�r�test_handles_leakFs,


zTestProcess.test_handles_leakcCs:x4tj�D](}y|j�Wq
tjk
r0Yq
Xq
WdS)N)rr�r�r)rr�rrr�test_name_always_availablejs
z&TestProcess.test_name_always_availabler�zCTRL_* signals not supportedcCsbtjt�j�}|jtj�|jtj�|j�|j	�|j
tj|jtj�|j
tj|jtj�dS)N)rr�rr�r�r�ZCTRL_C_EVENTZCTRL_BREAK_EVENTr�r�r�r)rr�rrr�test_ctrl_signalssszTestProcess.test_ctrl_signalsc
Cs\xVtj�D]J}ytjj|j��}|j�}Wntjtjfk
rFYq
X|j	||�q
WdS)N)
rr�r+r�r�r�r�rrr-)rr��a�brrr�test_compare_name_exe�sz!TestProcess.test_compare_name_execCs |jtj�j�tjtj��dS)N)r-rr�r�r1Z
GetUserNameExr�ZNameSamCompatible)rrrr�
test_username�szTestProcess.test_usernamecCs8tjddtj��j�}djtj�j��}|j	||�dS)Nz +r!)
�re�subr1ZGetCommandLine�stripr�rr��cmdliner-)rr2r3rrr�test_cmdline�szTestProcess.test_cmdlinecCsJtjtjtjtj��}|jtj|�t	j
|�}tj�j
�}|j||�dS)N)r1r�r�r�r�r+r��
addCleanupr��win32processZGetPriorityClassrr�r�r-)rr�r2r3rrr�	test_nice�s
zTestProcess.test_nicecCs�tjtjtj|j�}|jtj|�tj	|�}t
j|j�j�}|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|j|j�|j
|j|j�dS)	NZPeakWorkingSetSize�WorkingSetSizeZQuotaPeakPagedPoolUsageZQuotaPagedPoolUsageZQuotaPeakNonPagedPoolUsageZQuotaNonPagedPoolUsageZ
PagefileUsageZPeakPagefileUsage)r1r�r�r�r�r�r�r�r�ZGetProcessMemoryInforr�r�r-Z	peak_wsetZwsetZpeak_paged_poolZ
paged_poolZpeak_nonpaged_poolZ
nonpaged_poolZpagefileZ
peak_pagefiler�r�)rr�r2r3rrr�test_memory_info�s0
zTestProcess.test_memory_infocCsXtjtjtj|j�}|jtj|�tj	|j�}|j
�|j�}tj
|�}|j||�dS)N)r1r�r�r�r�r�r�r�rr�r�r�r�ZGetExitCodeProcessr-)rr�r�r3r2rrr�	test_wait�s
zTestProcess.test_waitcCs\dd�}tjtjtj|j�}|jtj|�|tj	|�d�}t
j|j�j�}|j
||�dS)Ncs�fdd�td�D�S)Ncsg|]}d|>�@r|�qS)rQr)r>�i)r?rrr@�szGTestProcess.test_cpu_affinity.<locals>.from_bitmask.<locals>.<listcomp>�@)�range)r?r)r?r�from_bitmask�sz3TestProcess.test_cpu_affinity.<locals>.from_bitmaskr)r1r�r�r�r�r�r�r�r�ZGetProcessAffinityMaskrr�Zcpu_affinityr-)rr�r�r2r3rrr�test_cpu_affinity�szTestProcess.test_cpu_affinitycCs�tjtjtjtj��}|jtj|�t	j
|�}tj�j
�}|j|j|d�|j|j|d�|j|j|d�|j|j|d�|j|j|d�|j|j|d�dS)NZReadOperationCountZWriteOperationCountZReadTransferCountZWriteTransferCountZOtherOperationCountZOtherTransferCount)r1r�r�r�r�r+r�r�r�r�ZGetProcessIoCountersrr��io_countersr-Z
read_countZwrite_countZ
read_bytesZwrite_bytes�other_countZother_bytes)rr�r2r3rrr�test_io_counters�s"
zTestProcess.test_io_counterscCs�ddl}ddl}d}|jjj|dtj��}|j|jjj|�|j	j
�}|jjj||j|��|j
}tj�j�}|jjj|�|j||d�dS)NrirQ)�ctypesZctypes.wintypesZwindllZkernel32r�r+r�r�r�ZwintypesZDWORDZGetProcessHandleCountZbyref�valuerr�r�r-)rr�r�r�Zhndcntr2r3rrr�test_num_handles�s
zTestProcess.test_num_handlesN)rr�)rfrgrh�classmethodr�r�r�r�r�r�r�r�r�rri�sys�version_infor�r�r�r�r�r�r�r�r�r�rrrrrs(
$	

rc@s`eZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dS)�TestProcessWMIz%Compare Process API results with WMI.cCst�j|_dS)N)rr�)r�rrrr�szTestProcessWMI.setUpClasscCs
t�dS)N)r)r�rrrr�szTestProcessWMI.tearDownClasscCs8tj�j|jd�d}tj|j�}|j|j�|j�dS)N)r=r)	r5r6rAr�rr�r-r�ZCaption)rr8r�rrr�	test_name
szTestProcessWMI.test_namecCs@tj�j|jd�d}tj|j�}|j|j�j�|j	j��dS)N)r=r)
r5r6rAr�rr�r-r�r%ZExecutablePath)rr8r�rrrr�szTestProcessWMI.test_execCsFtj�j|jd�d}tj|j�}|jdj|j��|j	j
dd��dS)N)r=rr!�"rF)r5r6rAr�rr�r-r�r�ZCommandLiner$)rr8r�rrrr�szTestProcessWMI.test_cmdlinecCsPtj�j|jd�d}tj|j�}|j�\}}}d||f}|j|j�|�dS)N)r=rz%s\%s)	r5r6rAr�rr�ZGetOwnerr-r�)rr8r�Zdomainr�r�rrrr�s
zTestProcessWMI.test_usernamecCsLtjd�tj�j|jd�d}tj|j�}|j�j	}|j
|t|j��dS)Ng�������?)r=r)
�time�sleepr5r6rAr�rr�r�r�r-r*r�)rr8r�r�rrr�test_memory_rss#s


zTestProcessWMI.test_memory_rsscCsjtjd�tj�j|jd�d}tj|j�}|j�j	}t
|j�}||krf||dkrf|jd||f�dS)Ng�������?)r=rizwmi=%s, psutil=%s)
r�r�r5r6rAr�rr�r�r�r*Z
PageFileUsager&)rr8r�r�Z	wmi_usagerrr�test_memory_vms*s


zTestProcessWMI.test_memory_vmscCs\tj�j|jd�d}tj|j�}t|jjd�d�}t	j
dt	j|j���}|j
||�dS)N)r=rr\z%Y%m%d%H%M%S)r5r6rAr�rr�r�ZCreationDaterUr�ZstrftimeZ	localtimer�r-)rr8r�Zwmic_createZ
psutil_createrrr�test_create_time7szTestProcessWMI.test_create_timeN)rfrgrh�__doc__r�r�r�r�r�r�r�r�r�r�rrrrr��s
r�c@sXeZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�ZdS)�TestDualProcessImplementationa{
    Certain APIs on Windows have 2 internal implementations, one
    based on documented Windows APIs, another one based
    NtQuerySystemInformation() which gets called as fallback in
    case the first fails because of limited permission error.
    Here we test that the two methods return the exact same value,
    see:
    https://github.com/giampaolo/psutil/issues/304
    cCst�j|_dS)N)rr�)r�rrrr�Lsz(TestDualProcessImplementation.setUpClasscCs
t�dS)N)r)r�rrrr�Psz+TestDualProcessImplementation.tearDownClassc
CsZtj|j�j�}tjdtjtj��d��(}|j	tj|j�j�|�|j
sLt�WdQRXdS)Nz psutil._psplatform.cext.proc_exe)�side_effect)rr�r�r�rrdrr+r�r-rtru)rr�rrrrr�Ws
z'TestDualProcessImplementation.test_namec
Cs�tj|j�j�}tjdttjd�d���}tj|j�j�}|j	t
|�t
|��xLtt
|��D]<}|j||d�|j||d�|j
||||dd�qZW|js�t�WdQRXdS)Nz(psutil._psplatform.cext.proc_memory_info�msg)r�ri)rP)rr�r�r�rrdrr�EPERMr-�lenr�ZassertGreaterEqualrRrtru)rZmem_1rZmem_2r�rrrr�^sz.TestDualProcessImplementation.test_memory_infoc
CsXtj|j�j�}tjdttjd�d��(}|j	tj|j�j�|�|j
sJt�WdQRXdS)Nz(psutil._psplatform.cext.proc_create_timer�)r�)rr�r�r�rrdrrr�r-rtru)rZctimerrrrr�js
z.TestDualProcessImplementation.test_create_timecCsxtj|j�j�}tjdttjd�d��H}tj|j�j�}|j	sBt
�|j|j|jdd�|j|j
|j
dd�WdQRXdS)Nz&psutil._psplatform.cext.proc_cpu_timesr�)r�g{�G�z�?)rP)rr�r�Z	cpu_timesrrdrrr�rtrurR�user�system)rZcpu_times_1rZcpu_times_2rrr�test_cpu_timesqs
z,TestDualProcessImplementation.test_cpu_timesc
Cs~tj|j�j�}tjdttjd�d��N}tj|j�j�}x,t	t
|��D]}|j||||dd�qFW|jspt
�WdQRXdS)Nz(psutil._psplatform.cext.proc_io_countersr�)r�r0)rP)rr�r�r�rrdrrr�r�r�rRrtru)rZ
io_counters_1rZ
io_counters_2r�rrrr�|sz.TestDualProcessImplementation.test_io_countersc
CsXtj|j�j�}tjdttjd�d��(}|j	tj|j�j�|�|j
sJt�WdQRXdS)Nz(psutil._psplatform.cext.proc_num_handlesr�)r�)rr�r�r�rrdrrr�r-rtru)rr�rrrrr��sz.TestDualProcessImplementation.test_num_handlesN)
rfrgrhr�r�r�r�r�r�r�r�r�r�rrrrr�@s

r�c@s|eZdZdZedd��Zedd��ZddgZdd	�Z	d
d�Z
edd
��Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdS)�RemoteProcessTestCasez�Certain functions require calling ReadProcessMemory.
    This trivially works when called on the current process.
    Check that this works on other processes, especially when they
    have a different bitness.
    cCsTd}xJtjd�D]<}tj|d|gtjtjd�}|j�\}}|tt�kr|SqWdS)Nz6import sys; sys.stdout.write(str(sys.maxsize > 2**32))zC:\Python*\python.exez-c)r�stdout�stderr)�glob�
subprocess�Popen�PIPEZSTDOUT�communicater��	IS_64_BIT)�code�filenamer9�outputr�rrr�find_other_interpreter�s
z,RemoteProcessTestCase.find_other_interpretercCs@|j�}|dkrtjd��tr.tj|_||_n||_tj|_dS)Nz0could not find interpreter with opposite bitness)r�rZSkipTestr�r��
executable�python64�python32)r�Zother_pythonrrrr��sz RemoteProcessTestCase.setUpClassz-czimport sys; sys.stdin.read()cCsVtjj�}ttj��|d<t|jg|j|tj	d�|_
t|jg|j|tj	d�|_dS)N�THINK_OF_A_NUMBER)�env�stdin)
r+r,�copyr�r�rr��	test_argsr�r��proc32r��proc64)rr�rrr�setUp�s
zRemoteProcessTestCase.setUpcCs|jj�|jj�t�dS)N)rr�rr)rrrr�tearDown�s

zRemoteProcessTestCase.tearDowncCs
t�dS)N)r)r�rrrr��sz#RemoteProcessTestCase.tearDownClasscCs@tj|jj�}|jt|j��d�|j|j�dd�|j�dS)Nr]rQ)rr�rr�r-r�r�r)rr�rrr�test_cmdline_32�sz%RemoteProcessTestCase.test_cmdline_32cCs@tj|jj�}|jt|j��d�|j|j�dd�|j�dS)Nr]rQ)rr�rr�r-r�r�r)rr�rrr�test_cmdline_64�sz%RemoteProcessTestCase.test_cmdline_64cCs&tj|jj�}|j|j�tj��dS)N)rr�rr�r-�cwdr+�getcwd)rr�rrr�test_cwd_32�sz!RemoteProcessTestCase.test_cwd_32cCs&tj|jj�}|j|j�tj��dS)N)rr�rr�r-rr+r	)rr�rrr�test_cwd_64�sz!RemoteProcessTestCase.test_cwd_64cCs>tj|jj�}|j�}|jd|�|j|dttj	���dS)Nr�)
rr�rr�r,�assertIn�assertEqualsr�r+r�)rr��errr�test_environ_32�sz%RemoteProcessTestCase.test_environ_32cCs>tj|jj�}|j�}|jd|�|j|dttj	���dS)Nr�)
rr�rr�r,rr
r�r+r�)rr�rrrr�test_environ_64�sz%RemoteProcessTestCase.test_environ_64N)rfrgrhr��staticmethodr�r�r�rrrr�rrr
rrrrrrrr��s
r�c@seZdZdd�Zdd�ZdS)�TestServicescCsntdddddddg�}tdd	d
g�}tddddd
ddg�}�x,tj�D�]}|j�}|j|dt�|j|dj�d�|j|dt�|j|dt�|j|d|�|ddk	r�tj	|d�|j|dt�|j|dt�|j|dt�|j|d|�|j|d|�|j|dt�|j
�}|dk	�rLtj	|�}|j|j��tj
|j��}|j||�qFWdS)NZrunningZpaused�start�pause�continue�stopZstoppedZ	automaticZmanualZdisabledZ
start_pendingZ
pause_pendingZcontinue_pendingZstop_pendingr�rF�display_namer��statusr�ZbinpathZ
start_type�description)rBr�win_service_iterr�ZassertIsInstancer�ZassertNotEqualr�rr�r�rZZ
is_running�win_service_getr�r-)rZvalid_statusesZvalid_start_typesZserv�datar�r��srrr�test_win_service_iter�sR

z"TestServices.test_win_service_iterc'Cspttj��j�}|jtj��}tj|d�WdQRX|j|jj|d�tj|�}t	tj
jjd�}t
jd|d��|jtj|j�WdQRXt
jd|d��|jtj|j�WdQRXt	tj
jjd�}t
jd|d��|jtj|j�WdQRXt
jd|d��|jtj|j�WdQRX|j|j�t|��|j|j�t|��|j|j�t|��|j|j�t|��dS)Nz???rFz/psutil._psplatform.cext.winservice_query_status)r�z/psutil._psplatform.cext.winservice_query_config)�nextrrr�r�rrr-Z	exceptionZWindowsError�_psplatformrWZERROR_SERVICE_DOES_NOT_EXISTrrdrr�ZERROR_ACCESS_DENIEDrrr�rrN)rr��cmZservice�excrrr�test_win_service_get!s2




z!TestServices.test_win_service_getN)rfrgrhrr#rrrrr�s0r�__main__l)2r�r^rr�r+r�r�r�r�r�r��warningsrrZpsutil._compatrZpsutil.testsrrrrrr	r
rr�catch_warnings�simplefilterr1r�r�r5�ImportErrorr�r rW�maxsizer�rriZTestCaser rjrr�r�r�rrf�__file__rrrr�<module>sl





<
m
A
N
^
U
tests/__pycache__/test_linux.cpython-36.opt-1.pyc000064400000175722150466730550015732 0ustar003

��JZ�3�@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ej,j-ej,j.e/��Z0dZ1dZ2dZ3e�r�dZ4dd �Z5d!d"�Z6d#d$�Z7d%d&�Z8d'd(�Z9d)d*�Z:e*j;ed+�Gd,d-�d-e*j<��Z=e*j;ed+�Gd.d/�d/e*j<��Z>e*j;ed+�Gd0d1�d1e*j<��Z?e*j;ed+�Gd2d3�d3e*j<��Z@e*j;ed+�Gd4d5�d5e*j<��ZAe*j;ed+�Gd6d7�d7e*j<��ZBe*j;ed+�Gd8d9�d9e*j<��ZCe*j;ed+�e*j;ed:�Gd;d<�d<e*j<���ZDe*j;ed+�Gd=d>�d>e*j<��ZEe*j;ed+�Gd?d@�d@e*j<��ZFe*j;ed+�GdAdB�dBe*j<��ZGe*j;ed+�GdCdD�dDe*j<��ZHe*j;ed+�GdEdF�dFe*j<��ZIeJdGk�r�e#e/�dS)HzLinux specific tests.�)�divisionN)�LINUX)�PY3)�u)�
call_until)�HAS_BATTERY)�HAS_CPU_FREQ)�
HAS_RLIMIT)�MEMORY_TOLERANCE)�mock)�PYPY)�pyrun)�
reap_children)�
reload_module)�retry_before_failing)�run_test_module_by_name)�safe_rmpath)�sh)�skip_on_not_implemented)�TESTFN)�
ThreadTask)�TRAVIS)�unittest)�whichi�i�i'�icCspddl}|dd�}tr"t|d�}tjtjtj�}tj|��*tj|j	|j
�ttj
d|��dd��SQRXdS)Nr��ascii�256s��)�fcntlr�bytes�socket�AF_INET�
SOCK_DGRAM�
contextlib�closingZ	inet_ntoa�ioctl�fileno�SIOCGIFADDR�struct�pack)�ifnamer�s�r-�"/usr/lib64/python3.6/test_linux.py�get_ipv4_address@s

r/c
s�ddl}|dd�}tr"t|d�}tjtjtj�}tj|��`|j|j	�t
tjd|��}trfdd��nddl
}|j�dj�fdd	�|d
d�D��dd
�SQRXdS)NrrrrcSs|S)Nr-)�xr-r-r.�ordWszget_mac_address.<locals>.ord�csg|]}d�|��qS)z%02x:r-)�.0�char)r1r-r.�
<listcomp>\sz#get_mac_address.<locals>.<listcomp>�r����)rrr r!r"r#r$r%r&r'�
SIOCGIFHWADDRr)r*�__builtin__r1�join)r+rr,�infor:r-)r1r.�get_mac_addressMs

r=cCsttd�}|jd�}xJ|D]B}|jd�r|j�\}}}}tjdd�}|t|�t|�t|��SqWtddj|���dS)zQParse 'free' cmd and return swap memory's s total, used and free
    values.
    zfree -b�
ZSwap�freeztotal used freez&can't find 'Swap' in 'free' output:
%sN)r�split�
startswith�collections�
namedtuple�int�
ValueErrorr;)�out�lines�line�_�total�usedr?�ntr-r-r.�	free_swap_s


rMcCs~td�}|jd�}xT|D]L}|jd�rdd�|j�dd�D�\}}}}tjdd	�}||||||�SqWtd
dj|���dS)zSParse 'free' cmd and return physical memory's total, used
    and free values.
    zfree -br>ZMemcSsg|]}t|��qSr-)rD)r3r0r-r-r.r5{sz free_physmem.<locals>.<listcomp>r7�r?ztotal used free shared outputz%can't find 'Mem' in 'free' output:
%sN)rr@rArBrCrEr;)rFrGrHrJrKr?�sharedrLr-r-r.�free_physmemns


"rPcCsNtd�}x4|jd�D]&}|j�}||krt|jd�d�SqWtd|��dS)Nz	vmstat -sr>� rz can't find %r in 'vmstat' output)rr@�striprDrE)�statrFrHr-r-r.�vmstat�srTcCs(td�j�}ttt|j�djd���S)Nzfree -Vr7�.r8)rrR�tuple�maprDr@)rFr-r-r.�get_free_version_info�srXz
LINUX onlyc@s�eZdZdd�Zejeo e�d kd�e�dd���Z	eje
d�e�d	d
���Ze�dd��Zeje
d�e�d
d���Z
eje
d�e�dd���Ze�dd��Ze�dd��Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)!�TestSystemVirtualMemorycCs&td�d}tj�j}|j||�dS)Nztotal memoryi)rT�psutil�virtual_memoryrJ�assertAlmostEqual)�self�vmstat_value�psutil_valuer-r-r.�
test_total�s
z"TestSystemVirtualMemory.test_total��zold free versioncCs8t�}|j}tj�j}|j||td|||jfd�dS)Nz	%s %s 
%s)�delta�msg)rPrKrZr[r\r
�output)r]r?�
free_valuer_r-r-r.�	test_used�s
z!TestSystemVirtualMemory.test_usedzunreliable on TRAVIScCs*td�d}tj�j}|j||td�dS)Nzfree memoryi)rc)rTrZr[r?r\r
)r]r^r_r-r-r.�	test_free�s
z!TestSystemVirtualMemory.test_freecCs*td�d}tj�j}|j||td�dS)Nz
buffer memoryi)rc)rTrZr[�buffersr\r
)r]r^r_r-r-r.�test_buffers�s
z$TestSystemVirtualMemory.test_bufferscCs*td�d}tj�j}|j||td�dS)Nz
active memoryi)rc)rTrZr[�activer\r
)r]r^r_r-r-r.�test_active�s
z#TestSystemVirtualMemory.test_activecCs*td�d}tj�j}|j||td�dS)Nzinactive memoryi)rc)rTrZr[�inactiver\r
)r]r^r_r-r-r.�
test_inactive�s
z%TestSystemVirtualMemory.test_inactivecCsJt�}|j}|dkrtjd��tj�j}|j||td|||jfd�dS)Nrz%free does not support 'shared' columnz	%s %s 
%s)rcrd)	rPrOr�SkipTestrZr[r\r
re)r]r?rfr_r-r-r.�test_shared�s

z#TestSystemVirtualMemory.test_sharedcCshtd�}|jd�}d|dkr*tjd��n:t|dj�d	�}tj�j}|j||t	d|||fd�dS)
Nzfree -br>�	availablerz(free does not support 'available' columnr7z	%s %s 
%s)rcrdr8)
rr@rrorDrZr[rqr\r
)r]rFrGrfr_r-r-r.�test_available�s

z&TestSystemVirtualMemory.test_availablecsT�fdd�}t�trdnd}tj|d|d���}tjdd���}tjd�tj�}|j	t
|�d	�|d
}|jdt|j
��|jdt|j
��|jd
t|j
��|jdt|j
��|jdt|j
��|jdt|j
��|jdt|j
��|j	|jd
�|j	|jd
�|j	|jd
�|j	|jd
�|j	|jd
�|j	|jd
�WdQRXWdQRXdS)Ncs0|dkrtjtjd�j��S�|f|�|�SdS)Nz
/proc/meminfoa�                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemAvailable:         -1 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    SReclaimable:     346648 kB
                    )�io�BytesIO�textwrap�dedent�encode)�name�args�kwargs)�	orig_openr-r.�	open_mock�s	zBTestSystemVirtualMemory.test_warnings_on_misses.<locals>.open_mockz
builtins.openz__builtin__.openT)�create�side_effect)�record�alwaysr7rz#memory stats couldn't be determined�cachedrOrkrmrirq)�openrr�patch�warnings�catch_warnings�simplefilterrZr[�assertEqual�len�assertIn�str�messager�rkrmrOrirq)r]r|�patch_point�m�ws�ret�wr-)r{r.�test_warnings_on_misses�s.
z/TestSystemVirtualMemory.test_warnings_on_missesc
Cs�ddlm}ddlm}i}|d��4}x,|D]$}|j�}t|d�d||d<q,WWdQRX||�}d|kr�|d}t||�|d}	|j|	d	�dS)
Nr)�calculate_avail_vmem)�open_binaryz
/proc/meminfor7is
MemAvailable:�d�
)�psutil._pslinuxr�r�r@rD�absZ
assertLess)
r]r�r�Zmems�frH�fields�a�bZdiff_percentr-r-r.�test_avail_old_percents

&z.TestSystemVirtualMemory.test_avail_old_percentcs��fdd�}t�trdnd}tj|d|d��N}tjdd��}tj�}WdQRX|j|j	d�|d
}|j
dt|j��WdQRXdS)
Ncs0|dkrtjtjd�j��S�|f|�|�SdS)Nz
/proc/meminfoa�                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemAvailable:    6574984 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    SReclaimable:     346648 kB
                    )rsrtrurvrw)rxryrz)r{r-r.r|0szKTestSystemVirtualMemory.test_avail_old_comes_from_kernel.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)ri�Sdirz,inactive memory stats couldn't be determinedl �")
r�rrr�r�r�rZr[r�rqr�r�r�)r]r|r�r�r�r�r�r-)r{r.� test_avail_old_comes_from_kernel-sz8TestSystemVirtualMemory.test_avail_old_comes_from_kernelcs��fdd�}t�trdnd}tj|d|d��N}tjdd��}tj�}WdQRX|j|j	d�|d}|j
dt|j��WdQRXdS)Ncs0|dkrtjtjd�j��S�|f|�|�SdS)Nz
/proc/meminfoa�                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    )rsrtrurvrw)rxryrz)r{r-r.r|Ss
zHTestSystemVirtualMemory.test_avail_old_missing_fields.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)ri�dii�Irz,inactive memory stats couldn't be determinedi�}l'Ll`LG)
r�rrr�r�r�rZr[r�rqr�r�r�)r]r|r�r�r�r�r�r-)r{r.�test_avail_old_missing_fieldsOsz5TestSystemVirtualMemory.test_avail_old_missing_fieldscs��fdd�}t�trdnd}tj|d|d��N}tjdd��}tj�}WdQRX|j|j	d�|d}|j
dt|j��WdQRXdS)NcsF|dkrtjtjd�j��S|dkr2ttjd��n�|f|�|�SdS)Nz
/proc/meminfoaT                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    SReclaimable:     346648 kB
                    z/proc/zoneinfozno such file or directory)rsrtrurvrw�IOError�errno�ENOENT)rxryrz)r{r-r.r|qs
zJTestSystemVirtualMemory.test_avail_old_missing_zoneinfo.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)ri�dii�Irz,inactive memory stats couldn't be determinedi�}l'Ll`LG)
r�rrr�r�r�rZr[r�rqr�r�r�)r]r|r�r�r�r�r�r-)r{r.�test_avail_old_missing_zoneinfonsz7TestSystemVirtualMemory.test_avail_old_missing_zoneinfoN)rararb)�__name__�
__module__�__qualname__r`r�skipIfrrXrrgrrhrjrlrnrprrr�r�r�r�r�r-r-r-r.rY�s$	


,"rYc@s\eZdZedd��Zdd�Ze�dd��Ze�dd��Zd	d
�Z	dd�Z
d
d�Zdd�ZdS)�TestSystemSwapMemoryc	Cs,td��}|j�}WdQRXd|ko*d|kS)z3Return True if /proc/meminfo provides swap metrics.z
/proc/meminfoNz
SwapTotal:z	SwapFree:)r��read)r��datar-r-r.�meminfo_has_swap_info�s
z*TestSystemSwapMemory.meminfo_has_swap_infocCs"t�j}tj�j}|j||td�S)N)rc)rMrJrZ�swap_memoryr\r
)r]rfr_r-r-r.r`�s
zTestSystemSwapMemory.test_totalcCs"t�j}tj�j}|j||td�S)N)rc)rMrKrZr�r\r
)r]rfr_r-r-r.rg�s
zTestSystemSwapMemory.test_usedcCs"t�j}tj�j}|j||td�S)N)rc)rMr?rZr�r\r
)r]rfr_r-r-r.rh�s
zTestSystemSwapMemory.test_freecCs�tjddd��v}tjdd��^}tjd�tj�}|jt|�d�|d}|j	dt
|j��|j|jd�|j|j
d�WdQRXWdQRXdS)	Nzpsutil._pslinux.openT)r})rr�r7rz9'sin' and 'sout' swap memory stats couldn't be determined)rr�r�r�r�rZr�r�r�r�r�r��sin�sout)r]r�r�r�r�r-r-r.�test_missing_sin_sout�s
z*TestSystemSwapMemory.test_missing_sin_soutcs��fdd�}t�trdnd}tj|d|d��v}tjdd��^}tjd�tj�}|j	t
|�d	�|d
}|jdt|j
��|j	|jd
�|j	|jd
�WdQRXWdQRXdS)Ncs*|dkrttjd��n�|f|�|�SdS)Nz/proc/vmstatzno such file or directory)r�r�r�)rxryrz)r{r-r.r|�sz=TestSystemSwapMemory.test_no_vmstat_mocked.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)rr�r7rzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)r�rrr�r�r�r�rZr�r�r�r�r�r�r�r�)r]r|r�r�r�r�r�r-)r{r.�test_no_vmstat_mocked�s
z*TestSystemSwapMemory.test_no_vmstat_mockedcCs�|j�stjd�Stjd��}tj�}WdQRXddlj}|j	�\}}}}}}}||9}||9}|j
|j|�|j
|j|�dS)Nz!/proc/meminfo has no swap metricsz"psutil._pslinux.cext.linux_sysinfor)
r�r�skiprr�rZr�Zpsutil._psutil_linuxZ
_psutil_linuxZ
linux_sysinfor�rJr?)r]r��swapZcextrIrJr?Zunit_multiplierr-r-r.�test_meminfo_against_sysinfo�s

z1TestSystemSwapMemory.test_meminfo_against_sysinfoc	sD�fdd�}t�trdnd}tj|d|d��}tj�WdQRXdS)Ncs&|dkrtjd�S�|f|�|�SdS)Nz
/proc/meminfo�)rsrt)rxryrz)r{r-r.r|�s
zKTestSystemSwapMemory.test_emulate_meminfo_has_no_metrics.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)r�rrr�rZr�)r]r|r�r�r-)r{r.�#test_emulate_meminfo_has_no_metrics�sz8TestSystemSwapMemory.test_emulate_meminfo_has_no_metricsN)
r�r�r��staticmethodr�r`rrgrhr�r�r�r�r-r-r-r.r��sr�c@s&eZdZejed�dd��Zejejj	d�d�dd��Z
ejejj	d�d	�d
d��Zejed�d
�dd��Z
ejed�d�dd��Zdd�Zdd�Zejed�dd��Zejed�ejed�dd���Zejed�dd��Zejed�d d!��Zejed�ejed�d"d#���Zd$S)%�
TestSystemCPUzunknown failure on traviscCs�tj�j}tjdtj�d�d}ttt	|j
d���}|dkrL|jd|�n|jd|�|d
krn|jd	|�n|jd	|�|dkr�|jd|�n|jd|�dS)Nz
\d+\.\d+\.\d+�rrU��ZstealrZguestraZ
guest_nice)r�r�r�)r�r�r)rar�r)
rZ�	cpu_times�_fields�re�findall�os�unamerVrWrDr@r��assertNotIn)r]r�Z
kernel_verZkernel_ver_infor-r-r.�test_cpu_timess
zTestSystemCPU.test_cpu_timesz/sys/devices/system/cpu/onlinez-/sys/devices/system/cpu/online does not existc
CsVtd��}|j�j�}WdQRXdt|�krRt|jd�d�d}|jtj�|�dS)Nz/sys/devices/system/cpu/online�-r7)	r�r�rRr�rDr@r�rZ�	cpu_count)r]r��valuer-r-r.�*test_cpu_count_logical_w_sysdev_cpu_onlines

z8TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_onlinez/sys/devices/system/cpuz&/sys/devices/system/cpu does not existcCs0tjd�}tdd�|D��}|jtj�|�dS)Nz/sys/devices/system/cpucSs g|]}tjd|�dk	r|�qS)zcpu\d+$N)r��search)r3r0r-r-r.r5%szITestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_num.<locals>.<listcomp>)r��listdirr�r�rZr�)r]Zls�countr-r-r.�'test_cpu_count_logical_w_sysdev_cpu_num!s
z5TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_numZnprocznproc utility not availablecCs$ttd��}|jtjdd�|�dS)Nznproc --allT)�logical)rDrr�rZr�)r]�numr-r-r.�test_cpu_count_logical_w_nproc(sz,TestSystemCPU.test_cpu_count_logical_w_nprocZlscpuzlscpu utility not availablecCs8td�}tdd�|jd�D��}|jtjdd�|�dS)Nzlscpu -pcSsg|]}|jd�s|�qS)�#)rA)r3r0r-r-r.r50sz@TestSystemCPU.test_cpu_count_logical_w_lscpu.<locals>.<listcomp>r>T)r�)rr�r@r�rZr�)r]rFr�r-r-r.�test_cpu_count_logical_w_lscpu-sz,TestSystemCPU.test_cpu_count_logical_w_lscpuc	&s2ddl}|jj�}tjdtd���}|j|jj�|�tjddd��:}|j|jj��|j|jd�|j|j	ddd�WdQRXt
d	d
��}|j�}WdQRXtj
|�}tjd|dd��}|j|jj�|�WdQRX�fdd
�}t
�tr�dnd}tj||dd��|j|jj�|�WdQRXWdQRXdS)Nrzpsutil._pslinux.os.sysconf)r~zpsutil._pslinux.openT)r}r�z
/proc/statz
/proc/cpuinfo�rb)�return_valuer}cs(|jd�rtjd�S�|f|�|�SdS)Nz
/proc/cpuinfor�)rArsrt)rxryrz)r{r-r.r|Ps

z>TestSystemCPU.test_cpu_count_logical_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~r})r��_pslinuxZcpu_count_logicalrr�rEr��assertIsNoneZ
call_count�	call_argsr�r�rsrtr)	r]rZ�originalr�r�Zcpuinfo_data�	fake_filer|r�r-)r{r.�test_cpu_count_logical_mocked3s(
 
z+TestSystemCPU.test_cpu_count_logical_mockedc	Cs.tjddd��}|jtjj��WdQRXdS)Nzpsutil._pslinux.openT)r})rr�r�rZr�Zcpu_count_physical)r]r�r-r-r.�test_cpu_count_physical_mocked[sz,TestSystemCPU.test_cpu_count_physical_mockedz
not supportedc	Cs,tjdgd��|jtj��WdQRXdS)Nzpsutil._pslinux.glob.glob)r�)rr�r�rZ�cpu_freq)r]r-r-r.�test_cpu_freq_no_resultbsz%TestSystemCPU.test_cpu_freq_no_resultzfails on Travisc
sH��fdd�}g�tj�tjd|dd��|jt��d�WdQRXdS)Ncs.|jd�r�jd�gS�jd��|�SdS)Nz&/sys/devices/system/cpu/cpufreq/policy)rA�append)�pattern)�flags�	orig_globr-r.�	glob_mockks



z>TestSystemCPU.test_cpu_freq_use_second_file.<locals>.glob_mockzpsutil._pslinux.glob.globT)r~r}r�)�globrr�r�r�)r]r�r-)r�r�r.�test_cpu_freq_use_second_filegs
z+TestSystemCPU.test_cpu_freq_use_second_filecs��fdd�}t�trdnd}tj||d��Ttjddgd��8tj�}|j|jd	�|j|jd
�|j|j	d�WdQRXWdQRXdS)NcsP|jd�rtjd�S|jd�r(tjd�S|jd�r<tjd�S�|f|�|�SdS)Nz/scaling_cur_freqs500000z/scaling_min_freqs600000z/scaling_max_freqs700000)�endswithrsrt)rxryrz)r{r-r.r||s





z;TestSystemCPU.test_cpu_freq_emulate_data.<locals>.open_mockz
builtins.openz__builtin__.open)r~z	glob.globz'/sys/devices/system/cpu/cpufreq/policy0)r�g@@g��@g�@)
r�rrr�rZr�r��current�min�max)r]r|r��freqr-)r{r.�test_cpu_freq_emulate_datazs
z(TestSystemCPU.test_cpu_freq_emulate_datacs��fdd�}t�trdnd}dddg}tj||d��Rtjd	|d
��8tj�}|j|jd�|j|jd�|j|j	d
�WdQRXWdQRXdS)NcsP|jd�rtjd�S|jd�r(tjd�S|jd�r<tjd�S�|f|�|�SdS)Nz/scaling_cur_freqs100000z/scaling_min_freqs200000z/scaling_max_freqs300000)r�rsrt)rxryrz)r{r-r.r|�s





z@TestSystemCPU.test_cpu_freq_emulate_multi_cpu.<locals>.open_mockz
builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z	glob.glob)r�gY@gi@g�r@)
r�rrr�rZr�r�r�r�r�)r]r|r��policiesr�r-)r{r.�test_cpu_freq_emulate_multi_cpu�s
z-TestSystemCPU.test_cpu_freq_emulate_multi_cpucs��fdd�}t�trdnd}dddg}tj||d��6tjd	|d
��tj�}|j|jd�WdQRXWdQRX�fdd�}t�tr�dnd}tj||d��.tjd	|d
��|jt	tj�WdQRXWdQRXdS)
Ncs@|jd�rttjd��n$|jd�r,tjd�S�|f|�|�SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freqs200000)r�r�r�r�rsrt)rxryrz)r{r-r.r|�s



zGTestSystemCPU.test_cpu_freq_no_scaling_cur_freq_file.<locals>.open_mockz
builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z	glob.glob)r���csD|jd�rttjd��n(|jd�r0ttjd��n�|f|�|�SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freq)r�r�r�r�)rxryrz)r{r-r.r|�s


)
r�rrr�rZr�r�r��assertRaises�NotImplementedError)r]r|r�r�r�r-)r{r.�&test_cpu_freq_no_scaling_cur_freq_file�s "z4TestSystemCPU.test_cpu_freq_no_scaling_cur_freq_fileN)r�r�r�rr�rr�r��path�existsr�r�rr�r�r�r�rr�r�r�r�r�r-r-r-r.r�s (

r�c@s4eZdZejed�dd��Zejed�dd��ZdS)�TestSystemCPUStatszfails on TraviscCs&td�}tj�j}|j||dd�dS)Nzcontext switchesi�)rc)rTrZ�	cpu_statsZctx_switchesr\)r]r^r_r-r-r.�test_ctx_switches�s
z$TestSystemCPUStats.test_ctx_switchescCs&td�}tj�j}|j||dd�dS)N�
interruptsi�)rc)rTrZr�r�r\)r]r^r_r-r-r.�test_interrupts�s
z"TestSystemCPUStats.test_interruptsN)r�r�r�rr�rr�r�r-r-r-r.r��sr�c@s|eZdZdd�Zdd�Ze�dd��Zeje	d�d�eje
d	�d
d���Zej
ded
�ej
ddd�dd���Zdd�ZdS)�TestSystemNetworkcCsjxdtj�j�D]T\}}xJ|D]B}|jtjkr@|j|jt|��q|jtj	kr|j|jt
|��qWqWdS)N)rZ�net_if_addrs�itemsZfamilyZAF_LINKr�Zaddressr=r!r"r/)r]rxZaddrsZaddrr-r-r.�test_net_if_addrs_ips�s
z'TestSystemNetwork.test_net_if_addrs_ipscCsbx\tj�j�D]L\}}ytd|�}Wntk
r:YqX|j|jttj	d|�d��qWdS)Nzifconfig %sz(?i)MTU[: ](\d+)r)
rZ�net_if_statsr�r�RuntimeErrorr�ZmturDr�r�)r]rx�statsrFr-r-r.�test_net_if_stats�sz#TestSystemNetwork.test_net_if_statscs�fdd�}tjddd�}x�|j�D]�\�}y|��}Wntk
rNw$YnX|j|j|ddd	�|j|j|d
dd	�|j|j|ddd	�|j|j|ddd	�|j|j	|d
dd	�|j|j
|ddd	�|j|j|ddd	�|j|j|ddd	�q$WdS)Ncs�i}td��}ttjd|�d�|d<ttjd|�d�|d<ttjd|�d�|d<ttjd|�d	�|d
<ttjd|�d�|d<ttjd|�d	�|d
<ttjd|�d�|d<ttjd|�d�|d<|S)Nzifconfig %szRX packets[: ](\d+)r�packets_recvzTX packets[: ](\d+)�packets_sentzerrors[: ](\d+)�errinr7�erroutzdropped[: ](\d+)�dropin�dropoutz#RX (?:packets \d+ +)?bytes[: ](\d+)�
bytes_recvz#TX (?:packets \d+ +)?bytes[: ](\d+)�
bytes_sent)rrDr�r�)Znicr�rF)rxr-r.�ifconfigsz8TestSystemNetwork.test_net_io_counters.<locals>.ifconfigTF)Zpernic�nowraprirN)rcrr�r�r�r�r�rrii)
rZ�net_io_countersr�r�r\rrr�r�r�r�rr)r]rZnior�Zifconfig_retr-)rxr.�test_net_io_counterss.z&TestSystemNetwork.test_net_io_countersZipz'ip' utility not availablezskipped on TraviscCs�td�j�}dd�tj�j�D�}d}xL|jd�D]>}|j�}tjd|�r2|d7}|jd�dj�}|j||�q2W|j	t
|�|d	tj|�|fd
�dS)Nzip addrcSsg|]}d|kr|�qS)�:r-)r3r0r-r-r.r52sz7TestSystemNetwork.test_net_if_names.<locals>.<listcomp>rr>z^\d+:r7rz	%s
---
%s)rd)
rrRrZr��keysr@r�r�r�r�r��pprintZpformat)r]rFZnics�foundrHrxr-r-r.�test_net_if_names.sz#TestSystemNetwork.test_net_if_namesz psutil._pslinux.socket.inet_ntop)r~zpsutil._pslinux.supports_ipv6F)r�cCsRy*tjtjtj�}|j|j�|jd�Wntjk
r@YnXtjdd�dS)N�::1rZinet6)�kind)r
r)	r!ZAF_INET6ZSOCK_STREAM�
addCleanup�closeZbind�errorrZ�net_connections)r]Z
supports_ipv6Z	inet_ntopr,r-r-r.�%test_net_connections_ipv6_unsupported=sz7TestSystemNetwork.test_net_connections_ipv6_unsupportedc
sF�fdd�}t�trdnd}tj||d��}tjdd�WdQRXdS)Ncs,|dkrtjtjd��S�|f|�|�SdS)Nz/proc/net/unixaB                    0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
                    0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
                    0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
                    000000000000000000000000000000000000000000000000000000
                    )rs�StringIOrurv)rxryrz)r{r-r.r|Jsz@TestSystemNetwork.test_net_connections_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~Zunix)r)r�rrr�rZr)r]r|r�r�r-)r{r.�test_net_connections_mockedIsz-TestSystemNetwork.test_net_connections_mockedN)r�r�r�r�r�rrrr�rrrrr�rErrr-r-r-r.r��s	*r�c@sNeZdZejeed�d�e�dd���Zdd�Z	dd�Z
d	d
�Zdd�Zd
S)�TestSystemDisks�statvfszos.statvfs() not availablecCs�dd�}x�tjdd�D]|}tj|j�}||j�\}}}}|j|j|�t|j|�d	krl|jd|j|f�t|j	|�dkr|jd|j	|f�qWdS)NcSsztd|�j�}|jd�}|jd�|jd�}|j�dd�\}}}}|dkrRd}t|�t|�t|�}}}||||fS)Nzdf -P -B 1 "%s"r>r�Znoner2)rrRr@�poprD)r�rFrGrH�devrJrKr?r-r-r.�dfis


z:TestSystemDisks.test_disk_partitions_and_usage.<locals>.dfF)�allr�izpsutil=%s, df=%si(i�i(i�)
rZ�disk_partitionsZ
disk_usageZ
mountpointr�rJr�r?�failrK)r]r�partZusagerrJrKr?r-r-r.�test_disk_partitions_and_usagedsz.TestSystemDisks.test_disk_partitions_and_usagecCs�tdd��}|j�}WdQRXd|krPx�tj�D]}|jdkr0Pq0W|jd�n`tjtd��}t	j
d|dd��<}t	j
d	dgd
�� }tj�}|j|djd�WdQRXWdQRXdS)Nz/proc/filesystems�r�zfszcouldn't find any ZFS partitionz
nodev	zfs
zpsutil._pslinux.openT)r�r}z$psutil._pslinux.cext.disk_partitions�	/dev/sdb3�/�rw)r�r)r#r$r"r%)r�r�rZrZfstyperrsrrrr�r�)r]r�r�rr��m1�m2r�r-r-r.�test_disk_partitions_mocked~s
z+TestSystemDisks.test_disk_partitions_mockedcs��fdd�}t�trdnd}tj||d���}tjdd�}|j|jd�|j|jd	�|j|j	d
t
�|j|jd�|j|jd�|j|j
d
�|j|jdt
�|j|jd�|j|jd�WdQRXdS)NcsB|dkrtjtjd��S|dkr.tjtd��S�|f|�|�SdS)Nz/proc/partitionszu                    major minor  #blocks  name

                       8        0  488386584 hda
                    z/proc/diskstatsz+   3     0   1 hda 2 3 4 5 6 7 8 9 10 11 12)rsrrurvr)rxryrz)r{r-r.r|�s
zJTestSystemDisks.test_disk_io_counters_kernel_2_4_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)rr7r�rarrNr���r�)r�rrr�rZ�disk_io_countersr��
read_count�read_merged_count�
read_bytes�SECTOR_SIZE�	read_time�write_count�write_merged_count�write_bytes�
write_time�	busy_time)r]r|r�r�r�r-)r{r.�'test_disk_io_counters_kernel_2_4_mocked�s
z7TestSystemDisks.test_disk_io_counters_kernel_2_4_mockedcs��fdd�}t�trdnd}tj||d���}tjdd�}|j|jd�|j|jd	�|j|j	d
t
�|j|jd�|j|jd�|j|j
d
�|j|jdt
�|j|jd�|j|jd�WdQRXdS)NcsB|dkrtjtjd��S|dkr.tjtd��S�|f|�|�SdS)Nz/proc/partitionszu                    major minor  #blocks  name

                       8        0  488386584 hda
                    z/proc/diskstatsz'   3    0   hda 1 2 3 4 5 6 7 8 9 10 11)rsrrurvr)rxryrz)r{r-r.r|�s
zOTestSystemDisks.test_disk_io_counters_kernel_2_6_full_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)rr7r�rarrNr�r)r*r�)r�rrr�rZr+r�r,r-r.r/r0r1r2r3r4r5)r]r|r�r�r�r-)r{r.�,test_disk_io_counters_kernel_2_6_full_mocked�s
z<TestSystemDisks.test_disk_io_counters_kernel_2_6_full_mockedcs��fdd�}t�trdnd}tj||d���}tjdd�}|j|jd�|j|jd	t	�|j|j
d
�|j|jdt	�|j|jd�|j|j
d�|j|jd�|j|jd�|j|jd�WdQRXdS)
NcsB|dkrtjtjd��S|dkr.tjtd��S�|f|�|�SdS)Nz/proc/partitionszu                    major minor  #blocks  name

                       8        0  488386584 hda
                    z/proc/diskstatsz   3    1   hda 1 2 3 4)rsrrurvr)rxryrz)r{r-r.r|�s
zRTestSystemDisks.test_disk_io_counters_kernel_2_6_limited_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)rr7r�rarr)r�rrr�rZr+r�r,r.r/r1r3r-r0r2r4r5)r]r|r�r�r�r-)r{r.�/test_disk_io_counters_kernel_2_6_limited_mocked�s
z?TestSystemDisks.test_disk_io_counters_kernel_2_6_limited_mockedN)
r�r�r�rr��hasattrr�rr r(r6r7r8r-r-r-r.ras rc@sVeZdZdd�Zejd�dd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�ZdS)�TestMisccCs(td�}tj�}|jt|�t|��dS)Nz	boot time)rTrZ�	boot_timer�rD)r]r^r_r-r-r.�test_boot_timeszTestMisc.test_boot_timezpsutil.traceback.print_excc"stj�}ttjj|d�d��$}|jd�|jd�|jd�WdQRX�z�t��fdd�}trbdnd	}tj	||d
���nt
t�|jt
tj�|jt
tjdd�|jt
tj�|jt
tjdd�|jt
tj�|jt
tjdd�|t_|jtj�d
�|jttj��d
�tjdd�}|jt|�d
�tjdd�}|jttt|��d
�ttjj|d�d��$}|jd�|jd�|jd�WdQRX|jtj�d
�|jttjdd��d
�|jttj��d
�|jttttjdd���d
�WdQRXWdtj|�t
t�X|jtjd�dS)NrSr�zcpu   0 0 0 0 0 0 0 0 0 0
zcpu0  0 0 0 0 0 0 0 0 0 0
zcpu1  0 0 0 0 0 0 0 0 0 0
cs&|jd�rttjd���|f|�|�S)Nz/proczrejecting access for test)rAr�r�r�)rxryrz)r{r-r.r|s
z4TestMisc.test_no_procfs_on_import.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)�percpurzcpu   1 0 0 0 0 0 0 0 0 0
zcpu0  1 0 0 0 0 0 0 0 0 0
zcpu1  1 0 0 0 0 0 0 0 0 0
z/proc)�tempfile�mkdtempr�r�r�r;�writerrr�rrZr�r�r�Zcpu_percentZcpu_times_percent�PROCFS_PATHr��sumrWZassertNotEqual�shutilZrmtree)r]�tbZ	my_procfsr�r|r�Zper_cpu_percentZper_cpu_times_percentr-)r{r.�test_no_procfs_on_importsL



(

z!TestMisc.test_no_procfs_on_importc
Cs.tjddd��}|jttjj�WdQRXdS)Nzpsutil._pslinux.openT)r})rr�r�r�rZr�r;)r]r�r-r-r.�test_boot_time_mockedDs

zTestMisc.test_boot_time_mockedcCs�tjdd
gd��}|jtj�d	jd
�WdQRXtjddgd��}|jtj�d	jd
�WdQRXtjddgd��}|jtj�d	jd�WdQRXdS)Nzpsutil._pslinux.cext.users�	giampaolo�pts/2�:0��h�ATr�)r�rZ	localhost�:0.0�foo)rGrHrIrJTr�)rGrHrKrJTr�)rGrHrLrJTr�)rr�r�rZZusers�host)r]r�r-r-r.�test_users_mockedKs

zTestMisc.test_users_mockedcCs�tj�}z�|t_|jttj�|jttj�|jttjdd�|jttj�|jttj	�|jttj
�|jttj�|jttj�|jttj
�|jtjtj�Wddt_tj|�XdS)NT)r=z/proc)r>r?rZrAr�r�r[r�r;rrr�r+rZ
NoSuchProcess�Processr��rmdir)r]Ztdirr-r-r.�test_procfs_path_szTestMisc.test_procfs_pathc	sH��fdd�}g�t�trdnd}tj||d��tj�WdQRXdS)NcsJtrt|t�r|j�}d|kr6�jd�ttjd��n�|f|�|�SdS)NZhw_sector_sizer2)r�
isinstancer �decoder�r�r�r�)rxryrz)�flagr{r-r.r|us
z1TestMisc.test_sector_size_mock.<locals>.open_mockz
builtins.openz__builtin__.open)r~)r�rrr�rZr+)r]r|r�r-)rTr{r.�test_sector_size_mockrs	zTestMisc.test_sector_size_mockc
CsZt�}|j�z<tj�}|j�dj}tj|�}|j�|j|tj��Wd|j	�XdS)Nr7)
r�startrZrO�threads�idZas_dictr�Zpids�stop)r]�t�p�tidZptr-r-r.�test_issue_687�s
zTestMisc.test_issue_687c	s:�fdd�}t�trdnd}tj||d��WdQRXdS)Ncs2|dtj�krtjtd��S�|f|�|�SdS)Nz/proc/%s/statusr2)r��getpidrsrr)rxryrz)r{r-r.r|�sz:TestMisc.test_pid_exists_no_proc_status.<locals>.open_mockz
builtins.openz__builtin__.open)r~)r�rrr�)r]r|r�r-)r{r.�test_pid_exists_no_proc_status�s
z'TestMisc.test_pid_exists_no_proc_statusN)
r�r�r�r<rr�rErFrNrQrUr]r_r-r-r-r.r:�s>r:z
no batteryc@s�eZdZejed�d�dd��Zejed�d�dd��Zdd�Zd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdS)�TestSensorsBatteryZacpizacpi utility not availablecCsDtd�}t|jd�dj�jdd��}tj�j}|j||dd�dS)Nzacpi -b�,r7�%r2)rc)	rrDr@rR�replacerZ�sensors_battery�percentr\)r]rFZ
acpi_valuer_r-r-r.�test_percent�s
zTestSensorsBattery.test_percentcCsTtd�}d|j�krtjd�Sd|kr,d}nd|jd�dk}|jtj�j|�dS)	Nzacpi -b�unknownzacpi output not reliablezdischarging at zero rateTZChargingr>r)	r�lowerrr�r@r�rZrd�
power_plugged)r]rFZpluggedr-r-r.�test_power_plugged�s
z%TestSensorsBattery.test_power_pluggedc
s`�fdd�}t�trdnd}tj||d��,}|jtj�jd�|jtj�jtj	�WdQRXdS)Ncs2|jd�s|jd�rtjd�S�|f|�|�SdS)Nz
AC0/onlinez	AC/online�1)r�rsrt)rxryrz)r{r-r.r|�s
z@TestSensorsBattery.test_emulate_power_plugged.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)
r�rrr�r�rZrdriZsecsleftZPOWER_TIME_UNLIMITED)r]r|r�r�r-)r{r.�test_emulate_power_plugged�sz-TestSensorsBattery.test_emulate_power_pluggedc
sL�fdd�}t�trdnd}tj||d��}|jtj�jd�WdQRXdS)NcsN|jd�s|jd�r"ttjd��n(|jd�r:tjtd��S�|f|�|�SdS)Nz
AC0/onlinez	AC/onliner2z/statusZcharging)r�r�r�r�rsrr)rxryrz)r{r-r.r|�s

zBTestSensorsBattery.test_emulate_power_plugged_2.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)r�rrr�r�rZrdri)r]r|r�r�r-)r{r.�test_emulate_power_plugged_2�sz/TestSensorsBattery.test_emulate_power_plugged_2c
sL�fdd�}t�trdnd}tj||d��}|jtj�jd�WdQRXdS)Ncs2|jd�s|jd�rtjd�S�|f|�|�SdS)Nz
AC0/onlinez	AC/online�0)r�rsrt)rxryrz)r{r-r.r|�s
zDTestSensorsBattery.test_emulate_power_not_plugged.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)r�rrr�r�rZrdri)r]r|r�r�r-)r{r.�test_emulate_power_not_plugged�sz1TestSensorsBattery.test_emulate_power_not_pluggedc
sL�fdd�}t�trdnd}tj||d��}|jtj�jd�WdQRXdS)NcsN|jd�s|jd�r"ttjd��n(|jd�r:tjtd��S�|f|�|�SdS)Nz
AC0/onlinez	AC/onliner2z/statusZdischarging)r�r�r�r�rsrr)rxryrz)r{r-r.r|�s

zFTestSensorsBattery.test_emulate_power_not_plugged_2.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)r�rrr�r�rZrdri)r]r|r�r�r-)r{r.� test_emulate_power_not_plugged_2�sz3TestSensorsBattery.test_emulate_power_not_plugged_2c	sJ�fdd�}t�trdnd}tj||d��}|jtj�j�WdQRXdS)NcsJ|jd�s|jd�r"ttjd��n$|jd�r6tjd�S�|f|�|�SdS)Nz"/sys/class/power_supply/AC0/onlinez!/sys/class/power_supply/AC/onliner2z#/sys/class/power_supply/BAT0/statuss???)rAr�r�r�rsrt)rxryrz)r{r-r.r|s



zETestSensorsBattery.test_emulate_power_undetermined.<locals>.open_mockz
builtins.openz__builtin__.open)r~)r�rrr�r�rZrdri)r]r|r�r�r-)r{r.�test_emulate_power_undetermineds	z2TestSensorsBattery.test_emulate_power_undeterminedc	sH�fdd�}t�trdnd}tj||d��}|jtj��WdQRXdS)Ncs6|jd�s|jd�r"ttjd��n�|f|�|�SdS)Nz'/sys/class/power_supply/BAT0/energy_nowz'/sys/class/power_supply/BAT0/charge_nowr2)rAr�r�r�)rxryrz)r{r-r.r|s

z@TestSensorsBattery.test_emulate_no_base_files.<locals>.open_mockz
builtins.openz__builtin__.open)r~)r�rrr�r�rZrd)r]r|r�r�r-)r{r.�test_emulate_no_base_filessz-TestSensorsBattery.test_emulate_no_base_filesc
sL�fdd�}t�trdnd}tj||d��}|jtj�jd�WdQRXdS)Ncs(|jd�rtjd�S�|f|�|�SdS)Nz(/sys/class/power_supply/BAT0/energy_fullrn)rArsrt)rxryrz)r{r-r.r|&s

z@TestSensorsBattery.test_emulate_energy_full_0.<locals>.open_mockz
builtins.openz__builtin__.open)r~r)r�rrr�r�rZrdre)r]r|r�r�r-)r{r.�test_emulate_energy_full_0$sz-TestSensorsBattery.test_emulate_energy_full_0c
sL�fdd�}t�trdnd}tj||d��}|jtj�jd�WdQRXdS)NcsRd}d}|j|�s|j|�r*ttjd��n$|jd�r>tjd�S�|f|�|�SdS)Nz(/sys/class/power_supply/BAT0/energy_fullz(/sys/class/power_supply/BAT0/charge_fullr2z%/sys/class/power_supply/BAT0/capacitys88)rAr�r�r�rsrt)rxryrzZenergy_fullZcharge_full)r{r-r.r|5s

zHTestSensorsBattery.test_emulate_energy_full_not_avail.<locals>.open_mockz
builtins.openz__builtin__.open)r~�X)r�rrr�r�rZrdre)r]r|r�r�r-)r{r.�"test_emulate_energy_full_not_avail2s
z5TestSensorsBattery.test_emulate_energy_full_not_availc	s:�fdd�}tjj�tjd|d��}tj�WdQRXdS)Ncs|jd�rdS�|�SdS)Nz"/sys/class/power_supply/AC0/onlineF)rA)rx)�orig_path_existsr-r.�path_exists_mockGs
zGTestSensorsBattery.test_emulate_no_ac0_online.<locals>.path_exists_mockzpsutil._pslinux.os.path.exists)r~)r�r�r�rr�rZrd)r]rwr�r-)rvr.�test_emulate_no_ac0_onlineEs
z-TestSensorsBattery.test_emulate_no_ac0_onlinec	sJ�fdd�}t�trdnd}tj||d��}|jtj�j�WdQRXdS)Ncs@|jd�s|jd�s|jd�r,ttjd��n�|f|�|�SdS)Nz!/sys/class/power_supply/AC/onlinez"/sys/class/power_supply/AC0/onlinez#/sys/class/power_supply/BAT0/statusr2)rAr�r�r�)rxryrz)r{r-r.r|Us



z;TestSensorsBattery.test_emulate_no_power.<locals>.open_mockz
builtins.openz__builtin__.open)r~)r�rrr�r�rZrdri)r]r|r�r�r-)r{r.�test_emulate_no_powerSsz(TestSensorsBattery.test_emulate_no_powerN)r�r�r�rr�rrfrjrlrmrorprqrrrsrurxryr-r-r-r.r`�sr`c@s(eZdZejed�dd��Zdd�ZdS)�TestSensorsTemperatureszunreliable on TRAVIScsx�fdd�}t�trdnd}tj||d��D}tjdd��,}|jtj�i�|j	dt
|d	j��WdQRXWdQRXdS)
Ncs,|jd�rttjd��n�|f|�|�SdS)NZ_inputr2)r��OSErrorr�ZEIO)rxryrz)r{r-r.r|is
zATestSensorsTemperatures.test_emulate_eio_error.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)rZignoringr)r�rrr�r�r�r�rZ�sensors_temperaturesr�r�r�)r]r|r�r�r�r-)r{r.�test_emulate_eio_errorgsz.TestSensorsTemperatures.test_emulate_eio_errorcs��fdd�}t�trdnd}tj||d��jtjddgd��Ntj�d	d
}|j|jd�|j|jd�|j|j	d
�|j|j
d�WdQRXWdQRXdS)Ncs�|jd�rtjtd��S|jd�r0tjtd��S|jd�rDtjd�S|jd�rXtjd�S|jd	�rltjd
�S�|f|�|�SdS)Nz/namerxz/temp1_label�labelz/temp1_inputs30000z
/temp1_maxs40000z/temp1_crits50000)r�rsrrrt)rxryrz)r{r-r.r|xs







z<TestSensorsTemperatures.test_emulate_data.<locals>.open_mockz
builtins.openz__builtin__.open)r~z	glob.globz/sys/class/hwmon/hwmon0/temp1)r�rxrr~g>@gD@gI@)r�rrr�rZr|r�r~r�ZhighZcritical)r]r|r�Ztempr-)r{r.�test_emulate_datawsz)TestSensorsTemperatures.test_emulate_dataN)r�r�r�rr�rr}rr-r-r-r.rzdsrzc@seZdZdd�ZdS)�TestSensorsFanscs��fdd�}t�trdnd}tj||d��Ntjddgd��2tj�d	d
}|j|jd�|j|jd�WdQRXWdQRXdS)
Ncs\|jd�rtjtd��S|jd�r0tjtd��S|jd�rHtjtd��S�|f|�|�SdS)Nz/namerxz/fan1_labelr~z/fan1_inputZ2000)r�rsrr)rxryrz)r{r-r.r|�s


z4TestSensorsFans.test_emulate_data.<locals>.open_mockz
builtins.openz__builtin__.open)r~z	glob.globz/sys/class/hwmon/hwmon2/fan1)r�rxrr~i�)	r�rrr�rZZsensors_fansr�r~r�)r]r|r�Zfanr-)r{r.r�s
z!TestSensorsFans.test_emulate_dataN)r�r�r�rr-r-r-r.r��sr�c@s�eZdZdd�ZeZdd�Zejed�dd��Z	dd	�Z
d
d�Zdd
�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zejed�dd��Zdd�Zdd �Zd!d"�Zd#S)$�TestProcesscCstt�dS)N)rr)r]r-r-r.�setUp�szTestProcess.setUpcCs�tjdt�}t|�}|jt�tdd�dt�tj|j	�}t
jd�|j�}|j
dd�}|j|jtdd	�|D��d
d�|j|jtdd	�|D��d
d�|j|jtd
d	�|D��d
d�dS)Nzk
            import time
            with open("%s", "w") as f:
                time.sleep(10)
            cSs
tjd�S)NrU)r�r�r-r-r-r.�<lambda>�sz3TestProcess.test_memory_full_info.<locals>.<lambda>z'%s' not in retg�������?F)ZgroupedcSsg|]}|j|j�qSr-)Z
private_dirtyZ
private_clean)r3r0r-r-r.r5�sz5TestProcess.test_memory_full_info.<locals>.<listcomp>i)rccSsg|]
}|j�qSr-)�pss)r3r0r-r-r.r5�scSsg|]
}|j�qSr-)r�)r3r0r-r-r.r5�s)rurvrr
rrrrZrO�pid�timeZsleepZmemory_full_info�memory_mapsr\ZussrBr�r�)r]�srcZsprocr[Zmem�mapsr-r-r.�test_memory_full_info�s 


z!TestProcess.test_memory_full_infozunreliable on PYPYc;CsRdd�}ttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXt�rNtt�ttd	��|j|�jd�WdQRXtt�ttd
��|j|�jd�WdQRXdS)NcSs\tj�}tj�d}x:x4|j�D](}|jtjjt�kr:|Stj�|kr Pq WqWtd��dS)Nr�ztimeout looking for test file)	rZrOr��
open_filesr�r��abspathrr�)r[Z	giveup_at�filer-r-r.�
get_test_file�s
z7TestProcess.test_open_files_mode.<locals>.get_test_filer�r!r�zr+zw+za+r0zx+)r�rr��moderr)r]r�r-r-r.�test_open_files_mode�s(z TestProcess.test_open_files_modecCs�tj�}|j�}tj��vt|jdt|��tjdt	t
jd�d��}|j�}WdQRXtjdt	t
jd�d��}|j
|j�g�WdQRXWdQRXdS)Nzlen(ret) != %izpsutil._pslinux.os.readlinkr2)r~)rZrOr�r>�NamedTemporaryFilerr�rr�r{r�r�ZEINVALr�)r]r[�filesr�r-r-r.�test_open_files_file_gone�s

z%TestProcess.test_open_files_file_gonecCsrtj�}|j�}tj��Pt|jdt|��tr6dnd}tj	|t
tjd�d��}|j�}WdQRXWdQRXdS)Nzlen(ret) != %iz
builtins.openz__builtin__.openr2)r~)
rZrOr�r>r�rr�rrr�r�r�r�)r]r[r�r�r�r-r-r.�test_open_files_fd_gones
z#TestProcess.test_open_files_fd_gonec
Cs8tjdid�� }|jtjjtj��j��WdQRXdS)Nz)psutil._pslinux._psposix.get_terminal_map)r�)	rr�r�rZr�rOr�r^Zterminal)r]r�r-r-r.�test_terminal_mockeds
z TestProcess.test_terminal_mockedcCs�tj�}tjtd��}tjd|dd��}|j|j�ddg�WdQRXtjtd��}tjd|dd��}|j|j�dddg�WdQRXdS)	Nzfoobarzpsutil._pslinux.openT)r�r}rL�barz	foobarr2)	rZrOrsrrrr�r��cmdline)r]r[r�r�r-r-r.�test_cmdline_mocked%s
zTestProcess.test_cmdline_mockedcCs�tj�}tjtd��}tjd|dd��}|j|j�ddg�WdQRXtjtd��}tjd|dd��}|j|j�dddg�WdQRXdS)	Nzfoo bar zpsutil._pslinux.openT)r�r}rLr�z	foo bar  r2)	rZrOrsrrrr�r�r�)r]r[r�r�r-r-r.�test_cmdline_spaces_mocked3s
z&TestProcess.test_cmdline_spaces_mockedc
CsFtjddd��.|jtj�j�d�|jtj�j�d�WdQRXdS)Nzpsutil._pslinux.os.readlinkz/home/foo (deleted))r�z	/home/foo)rr�r�rZrO�exe�cwd)r]r-r-r.�!test_readlink_path_deleted_mockedAs
z-TestProcess.test_readlink_path_deleted_mockedcs��fdd�}t�trdnd}tj||d��}tj�j�}|j|g�WdQRX�fdd�}tj||d��|jtj	tj�j�WdQRXdS)Ncs4|jdtj��r ttjd��n�|f|�|�SdS)Nz
/proc/%s/taskr2)rAr�r^r�r�r�)rxryrz)r{r-r.r|Lsz2TestProcess.test_threads_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~cs4|jdtj��r ttjd��n�|f|�|�SdS)Nz
/proc/%s/taskr2)rAr�r^r�r�ZEPERM)rxryrz)r{r-r.r|[s)
r�rrr�rZrOrWr�r��AccessDenied)r]r|r�r�r�r-)r{r.�test_threads_mockedGszTestProcess.test_threads_mockedcCs�tjdttjd�d��n}tjdtjdd�d��L}tj�j�}|j	|d�tjddd��|j
tjtj�j�WdQRXWdQRXWdQRXdS)	Nzpsutil._pslinux.readlinkr2)r~zpsutil.Process.cmdlinerzpsutil._pslinux.os.path.lexistsF)r�)rr�r{r�r�rZr�rOr�r�r��
ZombieProcess)r]r&r'r�r-r-r.�test_exe_mockedds
zTestProcess.test_exe_mockedcsr�fdd�}t�trdnd}tj||d��>}tj�}|jt��}|j�WdQRX|j	|j
jtj�WdQRXdS)Ncs4|jdtj��r ttjd��n�|f|�|�SdS)Nz/proc/%s/smapsr2)rAr�r^r�r�r�)rxryrz)r{r-r.r||sz.TestProcess.test_issue_1014.<locals>.open_mockz
builtins.openz__builtin__.open)r~)
r�rrr�rZrOr�r�r�r��	exceptionr�r�)r]r|r�r�r[�errr-)r{r.�test_issue_1014yszTestProcess.test_issue_1014z
not supportedcCs�tjdttjd�d��:}tj�}|j�|jtj	��}|j
tj�WdQRXWdQRX|j|j
j|j�|j|j
j|j��dS)Nz"psutil._pslinux.cext.linux_prlimitr2)r~)rr�r{r�ZENOSYSrZrOrxr�r�ZrlimitZ
RLIMIT_NOFILEr�r�r�)r]r�r[�excr-r-r.�test_rlimit_zombie�s
zTestProcess.test_rlimit_zombiecCs|tjdttjd�d��6}tj�}|j�|jtj	��}|j
�WdQRXWdQRX|j|jj
|j
�|j|jj|j��dS)Nzpsutil._pslinux.os.readlinkr2)r~)rr�r{r�r�rZrOrxr�r�r�r�r�r�)r]r�r[r�r-r-r.�test_cwd_zombie�s
zTestProcess.test_cwd_zombiecs�ddlm}�fdd�}t�tr$dnd}tj||d���tj�}|j|j	�d�|j|j
�tj�|j|j�d	�|j|j
�d
|tj��|j�}|j|jd|�|j|jd|�|j|jd
|�|j|jd|�|j|j�d
�WdQRXdS)Nr)�CLOCK_TICKSc's�|jdtj��rxddddddddddddddddd	ddddd
ddddddddddddddddd
g'}tjdj|�j��S�|f|�|�SdS)Nz
/proc/%s/stat�0z(cat)�Z�1�2�3�4�5�6rQ)rAr�r^rsrtr;rw)rxryrz)r{r-r.r|�sTz5TestProcess.test_stat_file_parsing.<locals>.open_mockz
builtins.openz__builtin__.open)r~�catr7r�r�rarrN)r�r�r�rrr�rZrOr�rx�statusZ
STATUS_ZOMBIE�ppidZcreate_timer;r��user�system�
children_user�children_systemZcpu_num)r]r�r|r�r[Zcpur-)r{r.�test_stat_file_parsing�s"/z"TestProcess.test_stat_file_parsingc
s��fdd�}t�trdnd}tj||d���tj�}|j|j�jd�|j|j�j	d�|j|j
�d�|j�}|j|jd	�|j|j
d
�|j|jd�|j�}|j|jd�|j|j
d
�|j|jd�|j|jj�ttdd���WdQRXdS)Ncs:|jdtj��r&tjtjd�j��S�|f|�|�SdS)Nz/proc/%s/statusa+                    Uid:	1000	1001	1002	1003
                    Gid:	1004	1005	1006	1007
                    Threads:	66
                    Cpus_allowed:	f
                    Cpus_allowed_list:	0-7
                    voluntary_ctxt_switches:	12
                    nonvoluntary_ctxt_switches:	13)rAr�r^rsrtrurvrw)rxryrz)r{r-r.r|�sz7TestProcess.test_status_file_parsing.<locals>.open_mockz
builtins.openz__builtin__.open)r~rb�
�Bi�i�i�i�i�i�rr*)r�rrr�rZrOr��num_ctx_switches�	voluntary�involuntary�num_threads�uids�realZ	effectiveZsaved�gids�_proc�_get_eligible_cpus�list�range)r]r|r�r[r�r�r-)r{r.�test_status_file_parsing�s"
z$TestProcess.test_status_file_parsingN)r�r�r�r�ZtearDownr�rr�rr�r�r�r�r�r�r�r�r�r�r	r�r�r�r�r-r-r-r.r��s"$Br�c@sreZdZdZedd��Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Ze
�dd��Zdd�Zdd�ZdS)�TestProcessAgainstStatusa/proc/pid/stat and /proc/pid/status have many values in common.
    Whenever possible, psutil uses /proc/pid/stat (it's faster).
    For all those cases we check that the value found in
    /proc/pid/stat (by psutil) matches the one found in
    /proc/pid/status.
    cCstj�|_dS)N)rZrO�proc)�clsr-r-r.�
setUpClasssz#TestProcessAgainstStatus.setUpClasscCs|tjjd|jj��^}xJ|D]B}|j�}|j|�r|jd�d}yt|�St	k
r\|SXqWt	d|��WdQRXdS)Nz/proc/%s/status�	r�z
can't find %r)
rZ�_psplatform�	open_textr�r�rRrA�	partitionrDrE)r]Z	linestartr�rHr�r-r-r.�read_status_files


z)TestProcessAgainstStatus.read_status_filecCs |jd�}|j|jj�|�dS)NzName:)r�r�r�rx)r]r�r-r-r.�	test_name!s
z"TestProcessAgainstStatus.test_namecCsH|jd�}||jd�d|jd��}|jdd�}|j|jj�|�dS)NzState:�(r7�)rQr�)r��find�rfindrcr�r�r�)r]r�r-r-r.�test_status%s
z$TestProcessAgainstStatus.test_statuscCs |jd�}|j|jj�|�dS)NzPPid:)r�r�r�r�)r]r�r-r-r.�	test_ppid+s
z"TestProcessAgainstStatus.test_ppidcCs |jd�}|j|jj�|�dS)NzThreads:)r�r�r�r�)r]r�r-r-r.�test_num_threads/s
z)TestProcessAgainstStatus.test_num_threadscCs:|jd�}ttt|j�dd���}|j|jj�|�dS)NzUid:r7r)r�rVrWrDr@r�r�r�)r]r�r-r-r.�	test_uids3s
z"TestProcessAgainstStatus.test_uidscCs:|jd�}ttt|j�dd���}|j|jj�|�dS)NzGid:r7r)r�rVrWrDr@r�r�r�)r]r�r-r-r.�	test_gids8s
z"TestProcessAgainstStatus.test_gidscCs@|jd�}|j|jj�j|�|jd�}|j|jj�j|�dS)Nzvoluntary_ctxt_switches:znonvoluntary_ctxt_switches:)r�r�r�r�r�r�)r]r�r-r-r.�test_num_ctx_switches=s

z.TestProcessAgainstStatus.test_num_ctx_switchescCsN|jd�}dt|�krJtt|jd��\}}|j|jj�tt	||d���dS)NzCpus_allowed_list:r�r7)
r�r�rWrDr@r�r�Zcpu_affinityr�r�)r]r�Zmin_Zmax_r-r-r.�test_cpu_affinityDs

z*TestProcessAgainstStatus.test_cpu_affinityc
Cs>|jd�}tjd��}|jjj�WdQRXdt|�kr:ndS)NzCpus_allowed_list:zpsutil._pslinux.per_cpu_timesr�)r�rr�r�r�r�r�)r]r�r�r-r-r.�test_cpu_affinity_eligible_cpusKs
z8TestProcessAgainstStatus.test_cpu_affinity_eligible_cpusN)r�r�r��__doc__�classmethodr�r�r�r�r�r�r�r�rr�r�r�r-r-r-r.r�s
r�c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�	TestUtilsc
Cs*tjjt��}|j|jd�WdQRXdS)NZrt)rZr�r��__file__r�r�)r]r�r-r-r.�test_open_text]szTestUtils.test_open_textc
Cs*tjjt��}|j|jd�WdQRXdS)Nr�)rZr�r�r�r�r�)r]r�r-r-r.�test_open_binaryaszTestUtils.test_open_binaryc
Cs2tjddd��}|jtjjd�d�WdQRXdS)Nzos.readlinkz
foo (deleted))r�r�rL)rr�r�rZr��readlink)r]r�r-r-r.�
test_readlinkeszTestUtils.test_readlinkcCs|tjjt�}t|d��}|jd�WdQRX|jtjj	tdd�d�|jtjj	tdd�d�|jtjj	tdd	d
�d	�dS)NZwtzfoo F)ZbinaryrLTsfooz??r�)Zfallback)
r�r�r�rr�r@r�rZr�r�)r]Zfnamer�r-r-r.�test_catjszTestUtils.test_catN)r�r�r�r�r�r�r�r-r-r-r.r�Zsr��__main__)Kr�Z
__future__rrBr$r�r�rsr�r
r�rCr!r)r>rur�r�rZrZpsutil._compatrrZpsutil.testsrrrr	r
rrr
rrrrrrrrrrrrr�r��dirnamer�ZHEREr(ZSIOCGIFCONFr9r/r/r=rMrPrTrXr�ZTestCaserYr�r�r�r�rr:r`rzr�r�r�r�r�r-r-r-r.�<module>s�
	


k
T

t

.7
-

Y
R

tests/__pycache__/test_aix.cpython-36.pyc000064400000006317150466730550014406 0ustar003

��JZm�@sxdZddlZddlmZddlmZddlmZddlmZddlZejed�Gdd	�d	ej	��Z
ed
krtee�dS)zAIX specific tests.�N)�AIX)�run_test_module_by_name)�sh)�unittestzAIX onlyc@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)�AIXSpecificTestCasecCs�td�}d}xdj�D]}|d|f7}qWtj||�}|j|d�d}t|jd��|}t|jd��|}t|jd	��|}t|jd
��|}	tj�}
d||}|j	|
j
|�|j|
j||d�|j|
j
||d�|j|
j|	|d�dS)
Nz/usr/bin/svmon -O unit=KBz	memory\s*z+size inuse free pin virtual available mmodez(?P<%s>\S+)\s+z(svmon command returned unexpected outputi�size�	availableZinuse�free�)�delta)r�split�re�search�assertIsNotNone�int�group�psutilZvirtual_memory�assertEqual�total�assertAlmostEqual�usedrr	)�self�out�
re_pattern�field�matchobjZKBrrrr	�
psutil_resultZMEMORY_TOLERANCE�r� /usr/lib64/python3.6/test_aix.py�test_virtual_memorys*z'AIXSpecificTestCase.test_virtual_memorycCsTtd�}tjd|�}|j|d�t|jd��}d}tj�}|jt|j	|�|�dS)Nz/usr/sbin/lsps -az=(?P<space>\S+)\s+(?P<vol>\S+)\s+(?P<vg>\S+)\s+(?P<size>\d+)MBz'lsps command returned unexpected outputrir
i)
rr
rrrrrZswap_memoryrr)rrrZtotal_mbZMBrrrr�test_swap_memory4sz$AIXSpecificTestCase.test_swap_memorycCs�td�}d}xdj�D]}|d|f7}qWtj||�}|j|d�d}tj�}|j|jt	|j
d��|d�|j|jt	|j
d	��|d�|j|jt	|j
d
��|d�|j|j
t	|j
d��|d�dS)Nz/usr/bin/mpstat -azALL\s*zfmin maj mpcs mpcr dev soft dec ph cs ics bound rq push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd syscz(?P<%s>\S+)\s+z)mpstat command returned unexpected outputi�Zcs)rZsyscZdevZsoft)rrr
rrrZ	cpu_statsrZctx_switchesrrZsyscallsZ
interruptsZsoft_interrupts)rrrrrZCPU_STATS_TOLERANCErrrr�test_cpu_statsIs2z"AIXSpecificTestCase.test_cpu_statscCs:td�}ttjd|�jd��}tjdd�}|j||�dS)Nz/usr/bin/mpstat -az
lcpu=(\d+)�T)Zlogical)rrr
rrr�	cpu_countr)rrZmpstat_lcpuZpsutil_lcpurrr�test_cpu_count_logicaljsz*AIXSpecificTestCase.test_cpu_count_logicalcCs4td�}t|j��}ttj�j��}|j||�dS)Nz/etc/ifconfig -l)r�setrrZnet_if_addrs�keysZassertSetEqual)rrZifconfig_namesZpsutil_namesrrr�test_net_if_addrs_namespsz+AIXSpecificTestCase.test_net_if_addrs_namesN)�__name__�
__module__�__qualname__rr r!r$r'rrrrrs
!r�__main__)
�__doc__r
rrZpsutil.testsrrrZskipIfZTestCaserr(�__file__rrrr�<module>s
ctests/__pycache__/test_system.cpython-36.pyc000064400000063474150466730550015160 0ustar003

��JZ/��@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlm
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+dd lm,Z,dd!lm-Z-Gd"d#�d#e-j.�Z/e0d$k�r�e(e1�dS)%zTests for system APIS.�N)�AIX)�BSD)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�long)�APPVEYOR)�ASCII_FS)�check_net_address)�DEVNULL)�enum)�get_test_subprocess)�HAS_BATTERY)�HAS_CPU_FREQ)�HAS_SENSORS_BATTERY)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�mock)�
reap_children)�retry_before_failing)�run_test_module_by_name)�safe_rmpath)�TESTFN)�TESTFN_UNICODE)�TRAVIS)�unittestc@sBeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
eje
d�dd��Zdd�Zdd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Zd-d.�Zd/d0�Zd1d2�Zd3d4�Zd5d6�Z d7d8�Z!d9d:�Z"d;d<�Z#d=d>�Z$d?d@�Z%dAdB�Z&dCdD�Z'dEdF�Z(dGdH�Z)eje*dI�dJdK��Z+eje,�o\e-j.j/dL�dM�eje0�ote1j2�dNkdO�dPdQ���Z3dRdS�Z4eje0�p�e*�o�e1j5�dT�dUdV��Z6dWdX�Z7eje8dY�dZd[��Z9d\d]�Z:eje;d^�d_d`��Z<eje;d^�dadb��Z=eje>d^�eje?dc�ddde���Z@ejeAd^�dfdg��ZBdNS)h�TestSystemAPIszTests for system-related APIs.cCstt�dS)N)rr)�self�r#�#/usr/lib64/python3.6/test_system.py�setUp>szTestSystemAPIs.setUpcCs
t�dS)N)r)r"r#r#r$�tearDownAszTestSystemAPIs.tearDowncCs�|jtj�dd�tj�D��t�}|j|jdd�tj�D��tj|j�}|j�|j	�|j
|jdd�tj�D��tjdtj
tj��d��|jttj��g�WdQRXtjdtjtj��d��*|jtj��ttj��WdQRXWdQRXdS)NcSsg|]
}|j�qSr#)�pid)�.0�xr#r#r$�
<listcomp>Esz4TestSystemAPIs.test_process_iter.<locals>.<listcomp>cSsg|]
}|j�qSr#)r')r(r)r#r#r$r*GscSsg|]
}|j�qSr#)r')r(r)r#r#r$r*Kszpsutil.Process)�side_effect)�assertIn�os�getpid�psutil�process_iterrr'�Process�kill�wait�assertNotInr�patchZ
NoSuchProcess�assertEqual�list�AccessDenied�assertRaises)r"�sproc�pr#r#r$�test_process_iterDsz TestSystemAPIs.test_process_itercCs8x.tjdgd�D]}|jt|jj��dg�qW|jt��ttjdgd��WdQRXtj	dtj
dd�d��L}x:tjddgd�D]&}|j|jd�|j|jdd�q�W|j
s�t�WdQRXtj	dtj
dd�d��X}t�}x>tjddg|d	�D](}|j|jd|�|j|jdd�q�W|j
�s*t�WdQRXdS)
Nr')�attrsZfooz$psutil._psplatform.Process.cpu_timesr�)r+�	cpu_times)r=Zad_value)r/r0r6r7�info�keysr9�
ValueErrorrr5r8�assertIsNone�assertGreaterEqual�called�AssertionError�object�assertIs)r"r;�m�flagr#r#r$�test_prcess_iter_w_paramsUs$z(TestSystemAPIs.test_prcess_iter_w_paramscs��fdd�}g�t�}t�}t�}dd�|||fD�}�jttj|dd��jttj|dd�tj�}tj|d|d	�\}}�jtj�|d
��j|g��jt	|�d��j�g�x|D]}	�j
t|	d��q�Wtd
��fdd��}
|j
�|
||�\}}�j|jdd�|D��t�r4�j|j�jtj�n�j|j�jd��j�|jg�x|D]}	�j
t|	d���q\Wtd
��fdd��}
|j
�|j
�|
||�\}}�jt��t|j|j|jg��x|D]}	�jt|	d���q�WdS)Ncs�j|j�dS)N)�appendr')r;)�pidsr#r$�callbackjsz0TestSystemAPIs.test_wait_procs.<locals>.callbackcSsg|]}tj|j��qSr#)r/r1r')r(r)r#r#r$r*qsz2TestSystemAPIs.test_wait_procs.<locals>.<listcomp>�)�timeout)rNg{�G�z�?)rPrNg�?��
returncode�cs<tj|d|d�\}}�jt|�d��jt|�d�||fS)Ng���Q��?)rPrNrO�)r/�
wait_procsr6�len)�procsrN�gone�alive)r"r#r$�test~s
z,TestSystemAPIs.test_wait_procs.<locals>.testcSsg|]
}|j�qSr#)r')r(r)r#r#r$r*�scs<tj|d|d�\}}�jt|�d��jt|�d�||fS)Ng���Q��?)rPrNrQr)r/rUr6rV)rWrNrXrY)r"r#r$rZ�s
���)rr9rBr/rU�	TypeError�time�
assertLessr6rV�assertFalse�hasattrr�	terminater,r'r	�poprR�signal�SIGTERM�set�
assertTrue)r"rN�sproc1�sproc2�sproc3rW�trXrYr;rZr#)rMr"r$�test_wait_procsisB

 
zTestSystemAPIs.test_wait_procscCsNt�}t�}t�}dd�|||fD�}x|D]}|j�q,Wtj|�\}}dS)NcSsg|]}tj|j��qSr#)r/r1r')r(r)r#r#r$r*�sz=TestSystemAPIs.test_wait_procs_no_timeout.<locals>.<listcomp>)rrar/rU)r"rgrhrirWr;rXrYr#r#r$�test_wait_procs_no_timeout�s
z)TestSystemAPIs.test_wait_procs_no_timeoutcCs4tj�}|j|t�|j|d�|j|tj��dS)Nr)r/Z	boot_time�assertIsInstance�float�
assertGreaterr^r])r"Zbtr#r#r$�test_boot_time�szTestSystemAPIs.test_boot_timez
POSIX onlycCs"ddl}|jtjd�|j��dS)Nr�SC_PAGE_SIZE)�resourcer6r-�sysconfZgetpagesize)r"rrr#r#r$�
test_PAGESIZE�szTestSystemAPIs.test_PAGESIZEcCs�tj�}|jdkst|��|jdks,t|��d|jko@dknsNt|��|jdks`t|��|jdksrt|��xt|jD]j}t	||�}|dkr�|j
|ttf�|dkrz|dks�|j
d||f�||jkrz|j
d||j||f�qzWdS)Nr�d�percent�totalz%r < 0 (%s)z%r > total (total=%s, %s=%s))r/Zvirtual_memoryrwrFZ	availablerv�used�free�_fields�getattrrm�intr�fail)r"�mem�name�valuer#r#r$�test_virtual_memory�s "

z"TestSystemAPIs.test_virtual_memorycCs�tj�}|j|jd	�|jdks(t|��|jdks:t|��|jdkrX|jdksjt|��n|jdksjt|��d|jko~dkns�t|��|j	dks�t|��|j
dks�t|��dS)
Nrwrxryrv�sin�soutrru)rwrxryrvr�r�)r/Zswap_memoryr6rzrwrFrxryrvr�r�)r"r~r#r#r$�test_swap_memory�s

"zTestSystemAPIs.test_swap_memorycCstt�}|jtj|j��tj|j�}|j�|j�|jtj|j��|jtjd��|j	tjd�dtj
�k�dS)NrOrr[)rrfr/�
pid_existsr'r1r2r3r_r6rM)r"r:r;r#r#r$�test_pid_exists�szTestSystemAPIs.test_pid_existscCs�t�tj�}xT|D]L}ytj|�s(t�Wqtk
r^tjd�|tj�krZ|j|�YqXqWtt	|�dt	|�d�}x |D]}|j
tj|�|d�q�WdS)Ng�������?i�ip)�msg)rr/rMr�rFr]�sleepr}�range�maxr_)r"rMr'r#r#r$�test_pid_exists_2�s


z TestSystemAPIs.test_pid_exists_2cCsJdd�tj�D�}tj�}|j|j�|j��|jt|�tt|���dS)NcSsg|]
}|j�qSr#)r')r(r)r#r#r$r*�sz,TestSystemAPIs.test_pids.<locals>.<listcomp>)r/r0rMr6�sortrVre)r"ZplistZpidlistr#r#r$�	test_pids�szTestSystemAPIs.test_pidscCs&tj}tt_ztj�Wd|t_XdS)N)�sys�stdoutrr/rZ)r"r�r#r#r$�	test_test�s
zTestSystemAPIs.test_testc
Cs�tj�}|j|ttjdd���|j|d�tjjd�rft	d��}|j
�}WdQRXd|krftjd��tjdd�}|j|d�|j||�dS)	NT)�percpurOz
/proc/cpuinfozphysical idz#cpuinfo doesn't include physical idF)�logical)
r/�	cpu_countr6rVr?rDr-�path�exists�open�readr ZSkipTest)r"r��fdZcpuinfo_dataZphysicalr#r#r$�test_cpu_counts

zTestSystemAPIs.test_cpu_countcCszxtd	D]l}tjd|d��}|jtj��|js2t�WdQRXtjd|d��"}|jtjdd��|jsht�WdQRXqWdS)
NrOrz$psutil._psplatform.cpu_count_logical)�return_valuez%psutil._psplatform.cpu_count_physicalF)r�r[)r[rN)rr5rCr/r�rErF)r"�valrIr#r#r$�test_cpu_count_nones


z"TestSystemAPIs.test_cpu_count_nonecCs^d}tj�}t|�x,|D]$}|j|t�|j|d�||7}qW|j|t|��t|�dS)Nrg)r/r?�sumrmrnrDr6�str)r"rw�times�cp_timer#r#r$�test_cpu_timess
zTestSystemAPIs.test_cpu_timescCsDttj��}tjd�ttj��}||}|dks@|jd|�dS)Ng�������?g�������?z
difference %s)r�r/r?r]r�r})r"�t1�t2�
differencer#r#r$�test_cpu_times_time_increases:s
z,TestSystemAPIs.test_cpu_times_time_increasescCs�xftjdd�D]V}d}t|�x,|D]$}|j|t�|j|d�||7}q$W|j|t|��t|�qW|jttjdd�d�ttjdd���dS)NT)r�rgF)	r/r?r�rmrnrDr6r�rV)r"r�rwr�r#r#r$�test_per_cpu_timesCs
z!TestSystemAPIs.test_per_cpu_timescCs�tjdd�}tj�d}xtj�|krPqWtjdd�}x<t||�D].\}}t|�t|�}}||}|dkrDdSqDW|j�dS)NT)r�g�������?g�������?)r/r?r]�zipr�r})r"Ztot1Zstop_atZtot2r�r�r�r#r#r$�test_per_cpu_times_2dsz#TestSystemAPIs.test_per_cpu_times_2cCs\tj�}tjdd�}|jdd�t|�D��}x*|jD] }|jt||�t||�dd�q4WdS)NT)r�cSsg|]}t|��qSr#)r�)r(Znumr#r#r$r*ysz<TestSystemAPIs.test_cpu_times_comparison.<locals>.<listcomp>rO)�delta)r/r?�_maker�rz�assertAlmostEqualr{)r"�baseZper_cpuZ
summed_valuesZfieldr#r#r$�test_cpu_times_comparisontsz(TestSystemAPIs.test_cpu_times_comparisoncCs�y<|j|t�|j|d�|j|d�|j|dtj��Wn@tk
r|}z$td|tj	|�tj	|�f��WYdd}~XnXdS)NggY@z
%s
last=%s
new=%sg�)
rmrnrDZassertIsNot�assertLessEqualr/r�rF�pprintZpformat)r"rvZlast_retZnew_ret�errr#r#r$�_test_cpu_percent~sz TestSystemAPIs._test_cpu_percentc
Csbtjdd�}x.td�D]"}tjdd�}|j|||�|}qW|jt��tjdd�WdQRXdS)Ng����MbP?)�intervalrurOr[)r/�cpu_percentr�r�r9rB)r"�lastr)�newr#r#r$�test_cpu_percent�szTestSystemAPIs.test_cpu_percentcCs�tjddd�}|jt|�tj��x>td�D]2}tjddd�}x|D]}|j|||�qDW|}q,W|jt��tjddd�WdQRXdS)Ng����MbP?T)r�r�rurOr[)	r/r�r6rVr�r�r�r9rB)r"r�r)r�rvr#r#r$�test_per_cpu_percent�s
z#TestSystemAPIs.test_per_cpu_percentcCs`tjdd�}xNtd�D]B}tjdd�}x|D]}|j|||�q,W|jt|�||�|}qWdS)Ng����MbP?)r�ru)r/�cpu_times_percentr�r�r�)r"r�r)r�rvr#r#r$�test_cpu_times_percent�s
z%TestSystemAPIs.test_cpu_times_percentcCs�tjddd�}|jt|�tj��x^td�D]R}tjddd�}x:|D]2}x|D]}|j|||�qNW|jt|�||�qDW|}q,WdS)Ng����MbP?T)r�r�ru)r/r�r6rVr�r�r�r�)r"r�r)r��cpurvr#r#r$�test_per_cpu_times_percent�s

z)TestSystemAPIs.test_per_cpu_times_percentc
Csrtjdd�dd�tjdd�D�}tjd|d��8x0tjdd�D] }x|D]}|j|dd�qJWq@WWdQRXdS)NT)r�cSs*g|]"}|jdd�tt|j��D���qS)cSsg|]}d�qS)rr#)r(r)r#r#r$r*�szQTestSystemAPIs.test_per_cpu_times_percent_negative.<locals>.<listcomp>.<listcomp>)r�r�rVrz)r(r)r#r#r$r*�szFTestSystemAPIs.test_per_cpu_times_percent_negative.<locals>.<listcomp>zpsutil.cpu_times)r�)r/r�r?rr5r�)r"Z
zero_timesr�rvr#r#r$�#test_per_cpu_times_percent_negative�s
z2TestSystemAPIs.test_per_cpu_times_percent_negativec
Cs2tjtj��}|j|jd�|jdks.t|��|jdks@t|��|j	dksRt|��|j|jksft|��|j|j	kszt|��d|j
ko�dkns�t|j
��ttd��r�tjtj��}d
}|j|j|j�|j
|j	|j	|d
�|j
|j|j|d
�tj�}|jt��}tj|�WdQRX|j|jjtj�dS)Nrwrxryrvrru�
disk_usage�i)r�)rwrxryrviiP)r/r�r-�getcwdr6rzrwrFrxryrvr`�shutilr��tempfileZmktempr9�OSErrorZ	exception�errno�ENOENT)r"ZusageZshutil_usageZ	toleranceZfname�excr#r#r$�test_disk_usage�s($zTestSystemAPIs.test_disk_usagec	Cs(tr$|jt��tjt�WdQRXdS)N)rr9�UnicodeEncodeErrorr/r�r)r"r#r#r$�test_disk_usage_unicode�sz&TestSystemAPIs.test_disk_usage_unicodecCstjd�dS)N�.)r/r�)r"r#r#r$�test_disk_usage_bytes�sz$TestSystemAPIs.test_disk_usage_bytescCstjdd�}|j||d�x�|D]�}|j|jt�|j|jt�|j|jt�|j|jt�t	rld|jkrlq t
s�tjj
|j�s�t|��n|jts�tr�tjj
|j�s�t|��ntjj|j�s�t|��|js t|��q Wtjdd�}|j||d�x�tjdd�D]�}t	�s�ytj|j�WnXtk
�rp}z:t�rJt�rJ|jtjk�rJ�w�|jtjtjfk�r`�WYdd}~Xn@Xt�s~t�r�tjj
|j��s�t|��ntjj|j��s�t|��|j|jt�|j|jt��q�Wdd�}|t�}dd	�tjdd�D�}|j||�tj|�dS)
NF)�all)r�ZcdromTcSs2tjj|�}xtjj|�s(tjj|�}qW|j�S)N)r-r��abspath�ismount�dirname�lower)r�r#r#r$�find_mount_pointsz=TestSystemAPIs.test_disk_partitions.<locals>.find_mount_pointcSsg|]}|jj��qSr#)�
mountpointr�)r(r)r#r#r$r*sz7TestSystemAPIs.test_disk_partitions.<locals>.<listcomp>)r/Zdisk_partitionsrfrmZdevicer�r�ZfstypeZoptsrr	r-r�r�rFr
r�isdir�statr�rr�ZEIOZEPERMZEACCES�__file__r,r�)r"�lsZdiskr�r�ZmountZmountsr#r#r$�test_disk_partitions�sL
z#TestSystemAPIs.test_disk_partitionscsl�fdd�}tjdd�}||�tjdd�}�j|g�x.|D]&}�j|��j|t�|||�q>WdS)Ncs(�j|d|j��j|d|j��j|d|j��j|d|j��j|d|j��j|d|j��j|d|j��j|d|j�|jdks�t	|��|jdks�t	|��|jdks�t	|��|jdks�t	|��|jdks�t	|��|jdks�t	|��|jdk�st	|��|jdk�s$t	|��dS)	NrrOrTrQ�r���)
r6Z
bytes_sentZ
bytes_recvZpackets_sentZpackets_recvZerrinZerroutZdropinZdropoutrF)�nt)r"r#r$�check_ntuples z9TestSystemAPIs.test_net_io_counters.<locals>.check_ntupleF)�pernicT)r/�net_io_counters�assertNotEqualrfrmr�)r"r��ret�keyr#)r"r$�test_net_io_counterss

z#TestSystemAPIs.test_net_io_counterscCsNtjdid��6}|jtjdd��|jtjdd�i�|js@t�WdQRXdS)Nz"psutil._psplatform.net_io_counters)r�F)r�T)rr5rCr/r�r6rErF)r"rIr#r#r$�test_net_io_counters_no_nics8s

z+TestSystemAPIs.test_net_io_counters_no_nicsc
Csttj�}|st|��tj�}ttjtjtjg�}�x�|j	�D�]�\}}|j
|t�|jt
t|��t
|���x�|D�]�}|j
|jt�|j
|jt�|j
|jttd�f�|j
|jttd�f�|j|j|�tjdkr�|j
|jtj�||j�r�|jtjk�r6tj|j�}tj|��|j|jdf�WdQRXnj|jtjk�r�tj|jdtjtjdtj�d}|\}	}
}}}
tj|	|
|�}tj|��|j|
�WdQRXxB|j|j|j|j fD]*}|dk	�r�|jtjk�r�t!||j��q�W|j�r�|j"|j �qr|j rr|j"|j�qrWq<Wt#�s&t$�s&t%�rDt&td��rp|jtjtj�n,t'�r\|jtjtj(�nt)�rp|jtjd�dS)NrQr�r�AF_LINKrO)rQr�r[)*r/�net_if_addrsrF�net_if_statsre�socketZAF_INETZAF_INET6r��itemsrmr�r6rVZfamilyr|�addressZnetmask�typeZ	broadcastr,r��version_infor�IntEnum�isup�
contextlib�closingZbindZgetaddrinfoZSOCK_STREAMZ
AI_PASSIVEZptprrCrrr
r`rZ	AF_PACKETr)r"�nicsZ	nic_statsZfamiliesZnicZaddrs�addr�sr@ZafZsocktype�protoZ	canonnameZsaZipr#r#r$�test_net_if_addrsAsX


z TestSystemAPIs.test_net_if_addrsc
Csztrdtjddddfg}ndg}tjd|d��B}tj�dd}|jsJt�tr^|j|j	d�n|j|j	d	�WdQRXdS)N�em1z06:3d:29rO�06-3d-29zpsutil._psplatform.net_if_addrs)r�rz06:3d:29:00:00:00z06-3d-29-00-00-00r[)r�r[r�NNN)
r	r/r�rr5r�rErFr6r�)r"r�rIr�r#r#r$� test_net_if_addrs_mac_null_bytes}s

z/TestSystemAPIs.test_net_if_addrs_mac_null_byteszunreliable on TRAVISc	Cs�tj�}|st|��tjtjtjf}xh|j�D]\\}}|j|t�|\}}}}|j|t	�|j
||�|j
||�|j|d�|j|d�q.WdS)Nr)r/r�rFZNIC_DUPLEX_FULLZNIC_DUPLEX_HALFZNIC_DUPLEX_UNKNOWNr�rmr��boolr,rD)	r"r�Zall_duplexesrZstatsr�ZduplexZspeedZmtur#r#r$�test_net_if_stats�sz TestSystemAPIs.test_net_if_statsz/proc/diskstatsz3/proc/diskstats not available on this linux versionNzunreliable on APPVEYORcs��fdd�}tjdd�}|dk	s(td��||�tjdd�}�jt|�tt|���xb|D]Z}|sjt|��|||�trZ|dj�rZx|d	j�r�|dd
�}q�W�j||j	��qZWdS)Ncs��j|d|j��j|d|j��j|d|j��j|d|j�tpNtsƈj|d|j��j|d|j�t	r��j|d|j
��j|d|j��j|d	|j�nt
rƈj|d|j�x$|jD]}t||�dks�t|��q�WdS)
NrrOrTrQr�r�r�r��)r6Z
read_countZwrite_countZ
read_bytesZwrite_bytesrrZ	read_timeZ
write_timerZread_merged_countZwrite_merged_countZ	busy_timerrzr{rF)r�r)r"r#r$r��sz:TestSystemAPIs.test_disk_io_counters.<locals>.check_ntupleF)�perdiskzno disks on this system?TrOr[r[r[)
r/�disk_io_countersrFr6rVrer�isdigitr4rA)r"r�r�r�r#)r"r$�test_disk_io_counters�s
z$TestSystemAPIs.test_disk_io_counterscCsNtjdid��6}|jtjdd��|jtjdd�i�|js@t�WdQRXdS)Nz#psutil._psplatform.disk_io_counters)r�F)r�T)rr5rCr/r�r6rErF)r"rIr#r#r$�test_disk_io_counters_no_disks�s

z-TestSystemAPIs.test_disk_io_counters_no_disksz unreliable on APPVEYOR or TRAVIScCs�tj�}|j|g�x�|D]�}|js,t|��|j|jt�|j|jttd�f�|j	dk	rp|j|j	ttd�f�|j|j	|j
dks�t|��tjj|j
�t
s�tr�|j|j�qtj|j�qWdS)Ng)r/�usersr�rrFrmr�Zterminalr��hostZstarted�datetimeZ
fromtimestamprrrCr'r1)r"r��userr#r#r$�
test_users�s

zTestSystemAPIs.test_userscCsZtj�}|j|jd�x>|jD]4}t||�}|j|d�tr|dkr|j|d�qWdS)N�ctx_switches�
interrupts�soft_interrupts�syscallsr)rrrr)rr)r/Z	cpu_statsr6rzr{rDrro)r"Zinfosrr�r#r#r$�test_cpu_stats�s
zTestSystemAPIs.test_cpu_statsznot suportedcs`�fdd�}tjdd�}tr&|r&dS|s2t|��|tjdd�g�tr\�jt|�tj��dS)Ncshxb|D]Z}�j|jd��j|j|j�x6|jD],}t||�}�j|ttt	f��j
|d�q0WqWdS)N�current�minr�r)r	r
r�)r6rzr�r	r�r{rmr|rrnrD)r�r�rr�)r"r#r$�check_ls�s

z.TestSystemAPIs.test_cpu_freq.<locals>.check_lsT)r�F)r/Zcpu_freqrrFrr6rVr�)r"rr�r#)r"r$�
test_cpu_freq�s	
zTestSystemAPIs.test_cpu_freqc	Cs�ddddddddd	g	}x"|D]}|jtt|�t|d
�qWtjdk�rJtjsPt�tjs\t�|j	d�dt
jj�kr�tj
s~t�|j	d�n�d
t
jj�kr�tjs�t�|jtjtjtjgjd�d�|j	d�|j	d�|j	d�|j	d�n^dt
jj�k�s
dt
jj�k�r"tj�st�|j	d	�n&dt
jj�k�rntj�s>t�|j	d�n$tj�sVt�tj�sdt�|j	d�x$|D]}|jtt|�d|d
��qtWdS)Nr	rrrrrrrr
)r��posix�linuxZbsdTrO�sunos�solaris�darwinF)rmr{r/r�r-rr	rFr�remover��platformr�rrr6rrr�countr
rrH)r"�namesrr#r#r$�test_os_constantss>










z TestSystemAPIs.test_os_constantsz
not supportedcCs�tj�}x�|j�D]x\}}|j|t�xb|D]Z}|j|jt�|jdk	rV|j|jd�|jdk	rn|j|jd�|j	dk	r,|j|j	d�q,WqWdS)Nr)
r/�sensors_temperaturesr�rmr��labelr	rD�high�critical)r"�tempsr�entries�entryr#r#r$�test_sensors_temperatures)s



z(TestSystemAPIs.test_sensors_temperaturesc
Cspddgi}tjd|d��N}tjdd	�dd
}|js8t�|j|jd�|j|jd�|j|j	d
�WdQRXdS)NZcoretempr�I@�N@��Q@z'psutil._psplatform.sensors_temperatures)r�T)Z
fahrenheitrg�^@g�a@g�c@)rrr r!)
rr5r/rrErFr6r	rr)r"�drIrr#r#r$�#test_sensors_temperatures_fahreneit7s


z2TestSystemAPIs.test_sensors_temperatures_fahreneitz
no batterycCsptj�}|j|jd�|j|jd�|jtjtjfkrF|j|jd�n|jtjkr^|j|j	�|j
|j	t�dS)Nrru)r/Zsensors_batteryrDrvr�ZsecsleftZPOWER_TIME_UNKNOWNZPOWER_TIME_UNLIMITEDrfZ
power_pluggedrmr�)r"r�r#r#r$�test_sensors_batteryCs
z#TestSystemAPIs.test_sensors_batterycCsjtj�}x\|j�D]P\}}|j|t�x:|D]2}|j|jt�|j|jttf�|j	|jd�q,WqWdS)Nr)
r/Zsensors_fansr�rmr�rr	r|rrD)r"Zfansrrrr#r#r$�test_sensors_fansQs
z TestSystemAPIs.test_sensors_fans)C�__name__�
__module__�__qualname__�__doc__r%r&r<rKrkrlrpr ZskipIfr	rtr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rr�rr-r�r�r
r/r�r�r�r�rrrrrrrr#rrr$rr%r#r#r#r$r!;sh7	
		!

		
>	<#

%
r!�__main__)2r)r�rr�r-r�r�rcr�r�r�r]r/rrrrrrrr	r
rZpsutil._compatrZpsutil.testsr
rrrrrrrrrrrrrrrrrrr ZTestCaser!r&r�r#r#r#r$�<module>sh'
tests/__pycache__/test_memory_leaks.cpython-36.opt-1.pyc000064400000052742150466730550017256 0ustar003

��JZ=G�@s<dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZ
ddl
mZddl
m
Z
ddl
mZddl
mZddl
mZdd	l
mZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(dZ)d Z*d!Z+e'�r�d"nd#Z,e
j-j.Z.e
j/�Z0e'�r�d"nd#Z,d$d%�Z1d&d'�Z2Gd(d)�d)e(j3�Z4Gd*d+�d+e4�Z5Gd,d-�d-e5�Z6Gd.d/�d/e4�Z7e8d0k�r8e#e9�dS)1a)
Tests for detecting function memory leaks (typically the ones
implemented in C). It does so by calling a function many times and
checking whether process memory usage keeps increasing between
calls or over time.
Note that this may produce false positives (especially on Windows
for some reason).
�)�print_functionN)�LINUX)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�xrange)�create_sockets)�get_test_subprocess)�HAS_CPU_AFFINITY)�HAS_CPU_FREQ)�HAS_ENVIRON)�
HAS_IONICE)�HAS_MEMORY_MAPS)�HAS_PROC_CPU_NUM)�HAS_PROC_IO_COUNTERS)�
HAS_RLIMIT)�HAS_SENSORS_BATTERY)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�
reap_children)�run_test_module_by_name)�safe_rmpath)�skip_on_access_denied)�TESTFN)�TRAVIS)�unittesti�i�TFcCstjto
td�S)Nz worthless on LINUX (pure python))r�skipIfr�SKIP_PYTHON_IMPL�r!r!�)/usr/lib64/python3.6/test_memory_leaks.py�
skip_if_linuxFs
r#cCstd
}i}x(t|�D]\}}d	|d	d
>||<qWx8t|�D],}|||kr<t|�||}d||fSq<Wd|S)z�
    http://code.activestate.com/recipes/578019
    >>> bytes2human(10000)
    '9.8K'
    >>> bytes2human(100001221)
    '95.4M'
    �K�M�G�T�P�E�Z�Y��
z%.2f%sz%sB)r$r%r&r'r(r)r*r+)�	enumerate�reversed�float)�nZsymbols�prefix�i�s�valuer!r!r"�bytes2humanKsr6c@sLeZdZdZeZeZeZ	dd�Z
dd�Zdd�Ze
dd	��Ze
d
d��ZdS)
�TestMemLeakz�Base framework class which calls a function many times and
    produces a failure if process memory usage keeps increasing
    between calls or over time.
    cCstj�dS)N)�gc�collect)�selfr!r!r"�setUpgszTestMemLeak.setUpcs~�����fdd�}�jdd�p$�j}�jdd�p6�j��jdd�pH�j}x"td�D]}�j�f����qTW�jtjg��jt	j
�d��jtj�g�|��j
�}|��j
�}	|	|}
|
|k�rzd	}tj�|}x,tj�|k�r�j�f����|d7}q�W~tj��j
�}
|
|	}|
|	k�rzt|
|�}td
|tjd�d}|d
7}|t|
��t|�||f}�j|�dS)zTest a callable.cs2x"t��D]}�j�f����q
W~tj�dS)N)r	�_callr8r9)�x)�args�fun�kwargs�loopsr:r!r"�call_many_timeslsz,TestMemLeak.execute.<locals>.call_many_times�
tolerance_NZloops_Z
retry_for_r-r,rzexta proc mem: %s)�filez0+%s after %s calls, +%s after another %s calls, z+%s extra proc mem)�pop�	tolerancerA�	retry_for�ranger<ZassertEqualr8Zgarbage�	threadingZactive_count�thisproc�children�_get_mem�timer9r6�print�sys�stderrZfail)r:r?r>r@rBrFrGr=Zmem1Zmem2Zdiff1ZncallsZstop_atZmem3Zdiff2Zextra_proc_mem�msgr!)r>r?r@rAr:r"�executejsB

zTestMemLeak.executecs"�����fdd�}�j|�dS)zRConvenience function which tests a callable raising
        an exception.
        cs�j��f����dS)N)ZassertRaisesr!)r>�excr?r@r:r!r"�call�sz'TestMemLeak.execute_w_exc.<locals>.callN)rR)r:rSr?r>r@rTr!)r>rSr?r@r:r"�
execute_w_exc�szTestMemLeak.execute_w_exccCs$tststrtj�jStj�jSdS)N)rrrrJ�memory_full_infoZuss�memory_infoZrssr!r!r!r"rL�s
zTestMemLeak._get_memcOs|||�dS)Nr!)r?r>r@r!r!r"r<�szTestMemLeak._callN)�__name__�
__module__�__qualname__�__doc__�MEMORY_TOLERANCErF�LOOPSrA�	RETRY_FORrGr;rRrU�staticmethodrLr<r!r!r!r"r7^s;		r7c@s�eZdZdZeZdd�Ze�dd��Ze�dd��Z	e�dd	��Z
e�d
d��Zej
ed�e�d
d���Zej
ed�e�dd���Ze�dd��Zdd�Zdd�Zej
ed�dd��Zej
ed�dd��Zej
ed�e�dd���Zej
ed�dd ��Ze�d!d"��Ze�eed#�d$d%���Zej
ed&�d'd(��Zej
ed�e�d)d*���Z e�d+d,��Z!e�eed#�d-d.���Z"e�d/d0��Z#e�ej
e$d�d1d2���Z%e�d3d4��Z&e�d5d6��Z'ej
ed�e�d7d8���Z(ej
e�o�e)d9�d:d;��Z*e�d<d=��Z+ej
e,d�d>d?��Z-ej
e,d�d@dA��Z.e�dBdC��Z/ej
e0dD�ej
e1d�e�dEdF����Z2ej
e3dG�ej
e4d�dHdI���Z5ej
e3dG�ej
e4d�dJdK���Z6e�ej
edL�dMdN���Z7ej
e8d�dOdP��Z9ej
ed&�dQdR��Z:dSS)T�TestProcessObjectLeaksz$Test leaks of Process class methods.cCsNtd�}x@ttj�D]2}|jd�r$q||kr.q|jt|d|�|d�qWdS)N�pid�as_dictrK�cpu_affinity�cpu_percent�ionice�
is_running�kill�memory_info_ex�memory_percent�nice�oneshot�parent�rlimit�send_signal�suspend�	terminate�wait�_�test_)rQ)rarbrKrcrdrerfrgrhrirjrkrlrmrnrorprq)�set�dir�psutil�Process�
startswith�
assertTrue�hasattr)r:�skip�namer!r!r"�
test_coverage�s
z$TestProcessObjectLeaks.test_coveragecCs|j|jj�dS)N)rR�procr|)r:r!r!r"�	test_name�sz TestProcessObjectLeaks.test_namecCs|j|jj�dS)N)rRr~Zcmdline)r:r!r!r"�test_cmdline�sz#TestProcessObjectLeaks.test_cmdlinecCs|j|jj�dS)N)rRr~Zexe)r:r!r!r"�test_exe�szTestProcessObjectLeaks.test_execCs|j|jj�dS)N)rRr~Zppid)r:r!r!r"�	test_ppid�sz TestProcessObjectLeaks.test_ppidz
POSIX onlycCs|j|jj�dS)N)rRr~Zuids)r:r!r!r"�	test_uids�sz TestProcessObjectLeaks.test_uidscCs|j|jj�dS)N)rRr~Zgids)r:r!r!r"�	test_gids�sz TestProcessObjectLeaks.test_gidscCs|j|jj�dS)N)rRr~Zstatus)r:r!r!r"�test_status�sz"TestProcessObjectLeaks.test_statuscCs|j|jj�dS)N)rRr~rj)r:r!r!r"�
test_nice_get�sz$TestProcessObjectLeaks.test_nice_getcCstj�}|j|jj|�dS)N)rJrjrRr~)r:Znicenessr!r!r"�
test_nice_set�sz$TestProcessObjectLeaks.test_nice_setz
not supportedcCs|j|jj�dS)N)rRr~re)r:r!r!r"�test_ionice_get�sz&TestProcessObjectLeaks.test_ionice_getcCsVtrtj�}|j|jj|�n4|j|jjtj�tjt	j
tj�dd�}|j
t|�dS)Nr,r���)rrJrerRr~rvZIOPRIO_CLASS_NONE�	functools�partial�cextZproc_ioprio_set�os�getpidrU�OSError)r:r5r?r!r!r"�test_ionice_set�sz&TestProcessObjectLeaks.test_ionice_setcCs|j|jj�dS)N)rRr~Zio_counters)r:r!r!r"�test_io_counterssz'TestProcessObjectLeaks.test_io_counterszworthless on POSIXcCs|j|jj�dS)N)rRr~Zusername)r:r!r!r"�
test_usernamesz$TestProcessObjectLeaks.test_usernamecCs|j|jj�dS)N)rRr~Zcreate_time)r:r!r!r"�test_create_timesz'TestProcessObjectLeaks.test_create_time)Zonly_ifcCs|j|jj�dS)N)rRr~Znum_threads)r:r!r!r"�test_num_threadssz'TestProcessObjectLeaks.test_num_threadszWINDOWS onlycCs|j|jj�dS)N)rRr~Znum_handles)r:r!r!r"�test_num_handlessz'TestProcessObjectLeaks.test_num_handlescCs|j|jj�dS)N)rRr~Znum_fds)r:r!r!r"�test_num_fdssz#TestProcessObjectLeaks.test_num_fdscCs|j|jj�dS)N)rRr~Znum_ctx_switches)r:r!r!r"�test_num_ctx_switches!sz,TestProcessObjectLeaks.test_num_ctx_switchescCs|j|jj�dS)N)rRr~Zthreads)r:r!r!r"�test_threads%sz#TestProcessObjectLeaks.test_threadscCs|j|jj�dS)N)rRr~�	cpu_times)r:r!r!r"�test_cpu_times*sz%TestProcessObjectLeaks.test_cpu_timescCs|j|jj�dS)N)rRr~Zcpu_num)r:r!r!r"�test_cpu_num.sz#TestProcessObjectLeaks.test_cpu_numcCs|j|jj�dS)N)rRr~rW)r:r!r!r"�test_memory_info3sz'TestProcessObjectLeaks.test_memory_infocCs|j|jj�dS)N)rRr~rV)r:r!r!r"�test_memory_full_info7sz,TestProcessObjectLeaks.test_memory_full_infocCs|j|jj�dS)N)rRr~Zterminal)r:r!r!r"�
test_terminal;sz$TestProcessObjectLeaks.test_terminalz worthless on POSIX (pure python)cCs|j|jj�dS)N)rRr~�resume)r:r!r!r"�test_resume@sz"TestProcessObjectLeaks.test_resumecCs|j|jj�dS)N)rRr~�cwd)r:r!r!r"�test_cwdEszTestProcessObjectLeaks.test_cwdcCs|j|jj�dS)N)rRr~rc)r:r!r!r"�test_cpu_affinity_getIsz,TestProcessObjectLeaks.test_cpu_affinity_getcCs4tj�}|j|jj|�ts0|jt|jjdg�dS)Nr,r�)rJrcrRr~rrU�
ValueError)r:Zaffinityr!r!r"�test_cpu_affinity_setMsz,TestProcessObjectLeaks.test_cpu_affinity_setc	Cs0tt�ttd��|j|jj�WdQRXdS)N�w)rr�openrRr~Z
open_files)r:r!r!r"�test_open_filesTsz&TestProcessObjectLeaks.test_open_filesztoo slow on OSXcCs|j|jj�dS)N)rRr~Zmemory_maps)r:r!r!r"�test_memory_maps[sz'TestProcessObjectLeaks.test_memory_mapsz
LINUX onlycCs|j|jjtj�dS)N)rRr~rmrv�
RLIMIT_NOFILE)r:r!r!r"�test_rlimit_getasz&TestProcessObjectLeaks.test_rlimit_getcCs6tjtj�}|j|jjtj|�|jt|jjd�dS)Nr,r�)rJrmrvr�rRr~rUr�)r:�limitr!r!r"�test_rlimit_setfsz&TestProcessObjectLeaks.test_rlimit_setzworthless on WINDOWSc
Cs2t��"trdnd}|j|jj|�WdQRXdS)NZinet�all)r
rrRr~Zconnections)r:Zkindr!r!r"�test_connectionsmsz'TestProcessObjectLeaks.test_connectionscCs|j|jj�dS)N)rRr~�environ)r:r!r!r"�test_environysz#TestProcessObjectLeaks.test_environcCs|jtjtj��dS)N)rRr��	proc_infor�r�)r:r!r!r"�test_proc_info}sz%TestProcessObjectLeaks.test_proc_infoN);rXrYrZr[rJr~r}r#rr�r�r�rrrr�r�r�r�r�rr�r�rr�r�r�rrr�rr�r�r�r�r�rr�r�r�r�r r�r�rr�r�r�rrr�rrr�r�r�rr�r�r!r!r!r"r`�sh


	r`cspeZdZdZe�fdd��Ze�fdd��Zdd�Zerhdd	�Z	d
d�Z
dd
�Zdd�Zdd�Z
dd�Z�ZS)�TestTerminatedProcessLeaksz�Repeat the tests above looking for leaks occurring when dealing
    with terminated processes raising NoSuchProcess exception.
    The C functions are still invoked but will follow different code
    paths. We'll check those code paths.
    cs:tt|�j�t�}tj|j�|_|jj�|jj	�dS)N)
�superr��
setUpClassrrvrwrar~rgrq)�cls�p)�	__class__r!r"r��s

z%TestTerminatedProcessLeaks.setUpClasscstt|�j�t�dS)N)r�r��
tearDownClassr)r�)r�r!r"r��sz(TestTerminatedProcessLeaks.tearDownClasscOs*y|||�Wntjk
r$YnXdS)N)rvZ
NoSuchProcess)r:r?r>r@r!r!r"r<�sz TestTerminatedProcessLeaks._callcCs|j|jj�dS)N)rRr~rg)r:r!r!r"�	test_kill�sz$TestTerminatedProcessLeaks.test_killcCs|j|jj�dS)N)rRr~rp)r:r!r!r"�test_terminate�sz)TestTerminatedProcessLeaks.test_terminatecCs|j|jj�dS)N)rRr~ro)r:r!r!r"�test_suspend�sz'TestTerminatedProcessLeaks.test_suspendcCs|j|jj�dS)N)rRr~r�)r:r!r!r"r��sz&TestTerminatedProcessLeaks.test_resumecCs|j|jj�dS)N)rRr~rq)r:r!r!r"�	test_wait�sz$TestTerminatedProcessLeaks.test_waitcs�fdd�}�j|�dS)NcsDytj�jj�Stk
r>}z|jtjkr.�WYdd}~XnXdS)N)r�r�r~rar��errnoZESRCH)�err)r:r!r"rT�s
z7TestTerminatedProcessLeaks.test_proc_info.<locals>.call)rR)r:rTr!)r:r"r��sz)TestTerminatedProcessLeaks.test_proc_info)rXrYrZr[�classmethodr�r�r<rr�r�r�r�r�r��
__classcell__r!r!)r�r"r��sr�c@s�eZdZdZdd�Ze�dd��Ze�dd��Ze�dd	��Ze�d
d��Z	dd
�Z
e�eje
d�dd���Zdd�Zejed�dd��Zejeo�ed�dd��Zejeo�ed�dd��Zdd�Zejeo�ejjd�d�e�dd ���Ze�d!d"��Ze�d#d$��Zejed%�eje�o&ej�d&kd'�d(d)���Z d*d+�Z!eje"d,�d-d.��Z#e�eje$d�d/d0���Z%e�eje&d�d1d2���Z'e�eje(d�d3d4���Z)e�d5d6��Z*eje+d7�d8d9��Z,e+�r�d:d;�Z-d<d=�Z.d>d?�Z/d@dA�Z0dBdC�Z1dDS)E�TestModuleFunctionsLeaksz&Test leaks of psutil module functions.cCsHtd
�}x:tjD]0}|j�sq||kr(q|jt|d|�|d	�qWdS)N�version_info�__version__�process_iter�
wait_procsrd�cpu_times_percent�	cpu_countrs)rQ)r�r�r�r�rdr�r�)rtrv�__all__�islowerryrz)r:r{r|r!r!r"r}�sz&TestModuleFunctionsLeaks.test_coveragecCs|jtjdd�dS)NT)�logical)rRrvr�)r:r!r!r"�test_cpu_count_logical�sz/TestModuleFunctionsLeaks.test_cpu_count_logicalcCs|jtjdd�dS)NF)r�)rRrvr�)r:r!r!r"�test_cpu_count_physical�sz0TestModuleFunctionsLeaks.test_cpu_count_physicalcCs|jtj�dS)N)rRrvr�)r:r!r!r"r��sz'TestModuleFunctionsLeaks.test_cpu_timescCs|jtjdd�dS)NT)Zpercpu)rRrvr�)r:r!r!r"�test_per_cpu_times�sz+TestModuleFunctionsLeaks.test_per_cpu_timescCs|jtj�dS)N)rRrvZ	cpu_stats)r:r!r!r"�test_cpu_stats�sz'TestModuleFunctionsLeaks.test_cpu_statsz
not supportedcCs|jtj�dS)N)rRrvZcpu_freq)r:r!r!r"�
test_cpu_freq�sz&TestModuleFunctionsLeaks.test_cpu_freqcCs|jtj�dS)N)rRrvZvirtual_memory)r:r!r!r"�test_virtual_memory�sz,TestModuleFunctionsLeaks.test_virtual_memoryz&worthless on SUNOS (uses a subprocess)cCs|jtj�dS)N)rRrvZswap_memory)r:r!r!r"�test_swap_memory�sz)TestModuleFunctionsLeaks.test_swap_memoryz worthless on POSIX (pure python)cCs|jtjtj��dS)N)rRrvZ
pid_existsr�r�)r:r!r!r"�test_pid_exists�sz(TestModuleFunctionsLeaks.test_pid_existscCs|jtjd�dS)N�.)rRrvZ
disk_usage)r:r!r!r"�test_disk_usage�sz(TestModuleFunctionsLeaks.test_disk_usagecCs|jtj�dS)N)rRrvZdisk_partitions)r:r!r!r"�test_disk_partitions�sz-TestModuleFunctionsLeaks.test_disk_partitionsz/proc/diskstatsz3/proc/diskstats not available on this Linux versioncCs|jtjdd�dS)NF)�nowrap)rRrvZdisk_io_counters)r:r!r!r"�test_disk_io_counterssz.TestModuleFunctionsLeaks.test_disk_io_counterscCs|jtj�dS)N)rRrvZpids)r:r!r!r"�	test_pidssz"TestModuleFunctionsLeaks.test_pidscCs|jtjdd�dS)NF)r�)rRrvZnet_io_counters)r:r!r!r"�test_net_io_counterssz-TestModuleFunctionsLeaks.test_net_io_countersz worthless on Linux (pure python)rzneed root accessc	Cs"t��|jtj�WdQRXdS)N)r
rRrvZnet_connections)r:r!r!r"�test_net_connectionssz-TestModuleFunctionsLeaks.test_net_connectionscCs|jtjtrdndd�dS)N�Pi)rCi@)rRrvZnet_if_addrsr)r:r!r!r"�test_net_if_addrssz*TestModuleFunctionsLeaks.test_net_if_addrszEPERM on traviscCs|jtj�dS)N)rRrvZnet_if_stats)r:r!r!r"�test_net_if_statssz*TestModuleFunctionsLeaks.test_net_if_statscCs|jtj�dS)N)rRrvZsensors_battery)r:r!r!r"�test_sensors_battery$sz-TestModuleFunctionsLeaks.test_sensors_batterycCs|jtj�dS)N)rRrvZsensors_temperatures)r:r!r!r"�test_sensors_temperatures)sz2TestModuleFunctionsLeaks.test_sensors_temperaturescCs|jtj�dS)N)rRrvZsensors_fans)r:r!r!r"�test_sensors_fans.sz*TestModuleFunctionsLeaks.test_sensors_fanscCs|jtj�dS)N)rRrvZ	boot_time)r:r!r!r"�test_boot_time5sz'TestModuleFunctionsLeaks.test_boot_timez(XXX produces a false positive on WindowscCs|jtj�dS)N)rRrvZusers)r:r!r!r"�
test_users:sz#TestModuleFunctionsLeaks.test_userscCs|jtj�dS)N)rRr�Zwinservice_enumerate)r:r!r!r"�test_win_service_iterBsz.TestModuleFunctionsLeaks.test_win_service_itercCsdS)Nr!)r:r!r!r"�test_win_service_getEsz-TestModuleFunctionsLeaks.test_win_service_getcCs"ttj��j�}|jtj|�dS)N)�nextrv�win_service_iterr|rRr�Zwinservice_query_config)r:r|r!r!r"�test_win_service_get_configHsz4TestModuleFunctionsLeaks.test_win_service_get_configcCs"ttj��j�}|jtj|�dS)N)r�rvr�r|rRr�Zwinservice_query_status)r:r|r!r!r"�test_win_service_get_statusLsz4TestModuleFunctionsLeaks.test_win_service_get_statuscCs"ttj��j�}|jtj|�dS)N)r�rvr�r|rRr�Zwinservice_query_descr)r:r|r!r!r"� test_win_service_get_descriptionPsz9TestModuleFunctionsLeaks.test_win_service_get_descriptionN)2rXrYrZr[r}r#r�r�r�r�r�rrr
r�r�rr�rr r�r�r�rr��path�existsr�r�r�r�getuidr�r�rr�rr�rr�rr�r�rr�r�r�r�r�r�r!r!r!r"r��sR


$r��__main__):r[Z
__future__rr�r�r8r�rOrIrMrvZpsutil._commonrrrrrrZpsutil._compatr	Zpsutil.testsr
rrr
rrrrrrrrrrrrrrrrr]r\r^r Z_psplatformr�rwrJr#r6ZTestCaser7r`r�r�rX�__file__r!r!r!r"�<module>
slcB<
tests/__pycache__/test_posix.cpython-36.pyc000064400000031747150466730550014774 0ustar003

��JZ�?�@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZddlmZddlm
Z
ddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!dd�Z"dd�Z#dd�Z$ej%ed �Gd!d"�d"ej&��Z'ej%ed �Gd#d$�d$ej&��Z(e)d%k�r�ee*�dS)&zPOSIX specific tests.�N)�AIX)�BSD)�LINUX)�OPENBSD)�OSX)�POSIX)�SUNOS)�callable)�PY3)�APPVEYOR)�get_kernel_version)�get_test_subprocess)�mock)�
PYTHON_EXE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�skip_on_access_denied)�TRAVIS)�unittest)�wait_for_pid)�whichcCspts|jdd�}tr |jdd�}tr0|jdd�}t|�}tsN|jd�dj�}yt|�Stk
rj|SXd	S)
zkExpects a ps command with a -o argument and parse the result
    returning only the value of interest.
    z --no-headers � z-o startz-o stimez-o rssz	-o rssize�
�N)	r�replacerrr�split�strip�int�
ValueError)�cmd�output�r#�"/usr/lib64/python3.6/test_posix.py�ps+sr%cCs&d}trd}td||f�jd�dS)N�commandZcommzps --no-headers -o %s -p %srr)rr%r)�pid�fieldr#r#r$�ps_nameIsr)cCs d}tstrd}td||f�S)Nr&�argszps --no-headers -o %s -p %s)rrr%)r'r(r#r#r$�ps_argsPsr+z
POSIX onlyc@s�eZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Ze�e
�dd���Ze�e
�dd���Zdd�Zdd�Zdd�Zdd�Zejep�ed�dd��Zdd �Zd!d"�Zejed#�ejed$�d%d&���Zd'd(�Zd)S)*�TestProcesszBCompare psutil results against 'ps' command line utility (mainly).cCs&ttddgtjd�j|_t|j�dS)Nz-Ez-O)�stdin)r
r�
subprocess�PIPEr'r)�clsr#r#r$�
setUpClass[s
zTestProcess.setUpClasscCs
t�dS)N)r)r0r#r#r$�
tearDownClassaszTestProcess.tearDownClasscCs.td|j�}tj|j�j�}|j||�dS)Nzps --no-headers -o ppid -p %s)r%r'�psutil�ProcessZppid�assertEqual)�selfZppid_psZppid_psutilr#r#r$�	test_ppideszTestProcess.test_ppidcCs0td|j�}tj|j�j�j}|j||�dS)Nzps --no-headers -o uid -p %s)r%r'r3r4�uids�realr5)r6Zuid_psZ
uid_psutilr#r#r$�test_uidjszTestProcess.test_uidcCs0td|j�}tj|j�j�j}|j||�dS)Nzps --no-headers -o rgid -p %s)r%r'r3r4Zgidsr9r5)r6Zgid_psZ
gid_psutilr#r#r$�test_gidoszTestProcess.test_gidcCs.td|j�}tj|j�j�}|j||�dS)Nzps --no-headers -o user -p %s)r%r'r3r4�usernamer5)r6Zusername_psZusername_psutilr#r#r$�
test_usernametszTestProcess.test_usernamecCsJtj�}tjdtd��*}|j|j�t|j�j	��|j
s<t�WdQRXdS)Nzpsutil.pwd.getpwuid)�side_effect)r3r4r�patch�KeyErrorr5r<�strr8r9�called�AssertionError)r6�pZfunr#r#r$�test_username_no_resolutionysz'TestProcess.test_username_no_resolutioncCs@tjd�td|j�}tj|j�j�dd}|j||�dS)Ng�������?zps --no-headers -o rss -p %sri)�time�sleepr%r'r3r4�memory_infor5)r6Zrss_psZ
rss_psutilr#r#r$�test_rss_memory�s
zTestProcess.test_rss_memorycCs@tjd�td|j�}tj|j�j�dd}|j||�dS)Ng�������?zps --no-headers -o vsz -p %sri)rFrGr%r'r3r4rHr5)r6Zvsz_psZ
vsz_psutilr#r#r$�test_vsz_memory�s
zTestProcess.test_vsz_memorycCsZt|j�}tjj|�j�}tj|j�j�j�}t	j
dd|�}t	j
dd|�}|j||�dS)Nz\d.\d�)r)r'�os�path�basename�lowerr3r4�name�re�subr5)r6Zname_psZname_psutilr#r#r$�	test_name�s
zTestProcess.test_namecCs^d}dddg}tjd|d��8tjd|d��tj�}|j|j�d�WdQRXWdQRXdS)Nzlong-program-namezlong-program-name-extendedZfooZbarzpsutil._psplatform.Process.name)�return_valuez"psutil._psplatform.Process.cmdline)rr?r3r4r5rP)r6rP�cmdlinerDr#r#r$�test_name_long�s


zTestProcess.test_name_longcCs\d}tjd|d��@tjdtjdd�d��tj�}|j|j�d�WdQRXWdQRXdS)Nzlong-program-namezpsutil._psplatform.Process.name)rTz"psutil._psplatform.Process.cmdlinerrK)r>)rr?r3�AccessDeniedr4r5rP)r6rPrDr#r#r$�test_name_long_cmdline_ad_exc�s
z)TestProcess.test_name_long_cmdline_ad_exccCs\d}tjd|d��@tjdtjdd�d��tj�}|jtj|j�WdQRXWdQRXdS)Nzlong-program-namezpsutil._psplatform.Process.name)rTz"psutil._psplatform.Process.cmdlinerrK)r>)rr?r3Z
NoSuchProcessr4�assertRaisesrP)r6rPrDr#r#r$�test_name_long_cmdline_nsp_exc�s
z*TestProcess.test_name_long_cmdline_nsp_exczps -o start not availablecCshtd|j�jd�d}tj|j�j�}tjj|�jd�}t	|�}tjj|�jd�}|j
|||g�dS)Nzps --no-headers -o start -p %srrz%H:%M:%S)r%r'rr3r4Zcreate_time�datetimeZ
fromtimestampZstrftime�round�assertIn)r6Ztime_psZtime_psutilZtime_psutil_tstampZround_time_psutilZround_time_psutil_tstampr#r#r$�test_create_time�szTestProcess.test_create_timecCs`t|j�}tj|j�j�}y|j||�Wn0tk
rZ|dt|��}|j||�YnXdS)N)r)r'r3r4Zexer5rC�len)r6Zps_pathnameZpsutil_pathnameZadjusted_ps_pathnamer#r#r$�test_exe�s
zTestProcess.test_execCs0t|j�}djtj|j�j��}|j||�dS)Nr)r+r'�joinr3r4rUr5)r6Z
ps_cmdlineZpsutil_cmdliner#r#r$�test_cmdline�s
zTestProcess.test_cmdlineznot reliable on SUNOSznot reliable on AIXcCs*td|j�}tj�j�}|j||�dS)Nzps --no-headers -o nice -p %s)r%r'r3r4�nicer5)r6Zps_niceZpsutil_nicer#r#r$�	test_nice�szTestProcess.test_nicec	
s�fdd�}tjtj��}g}ddddddd	d
ddg
}trNt�dkrN|jd�trft�dkrf|jd�x�ttj�D]���jd�sr�|kr�qrqry0|j	�}xt
d
�D]}||��q�W|j	�}Wntjk
r�YqrXt||�dkrrd�||f}|j|�qrW|�r|j
ddj|��dS)NcsBf}t|�d�}|dk	r:t|�r:�dkr0tjf}||�n|dS)N�rlimit)�getattrr	r3Z
RLIMIT_NOFILE)rD�attrr*)rPr#r$�call�s
z&TestProcess.test_num_fds.<locals>.callZ	terminate�killZsuspendZresumercZsend_signal�waitZchildrenZas_dictZmemory_info_ex���$re�Znum_ctx_switches�_rz@failure while processing Process.%s method (before=%s, after=%s)r)rkrlrm)rkrlrn)r3r4rL�getpidrr�append�dir�
startswithZnum_fds�rangerW�abs�failra)	r6rhrDZfailuresZ
ignored_namesZnum1�xZnum2rvr#)rPr$�test_num_fds�s4



zTestProcess.test_num_fdsN)�__name__�
__module__�__qualname__�__doc__�classmethodr1r2r7r:r;r=rErrrIrJrSrVrXrZr�skipIfrrr^r`rbrrrdrxr#r#r#r$r,Ws,			



r,c@s�eZdZdZe�dd��Zejed�eje	d�eje
d�d�dd	����Zejep`e	o`e
j�d
�e�dd���Zd
d�Zdd�Zdd�Zdd�Zejed�dd��ZdS)�TestSystemAPIszTest some system APIs.cCs�tstrddddg}nddddg}t|tjd�}|j�dj�}|j�dksPt�t	rbt
|tjj
�}g}x<|jd�d	d�D]&}|rzt|j�dj��}|j|�qzW|j|j�tj�}|j�|j�ts�tr�d|kr�|jdd�|j||�dS)
Nr%z-Az-or'Zax)�stdoutrrr)rrr
r.r/ZcommunicaterZpollrCr
rA�sysr��encodingrrrq�remover'r3Zpids�sortrr�insertr5)r6r!rDr"Zpids_ps�liner'Zpids_psutilr#r#r$�	test_pids s(zTestSystemAPIs.test_pidszunreliable on SUNOSzunreliable on TRAVISZifconfigzno ifconfig cmdcCsVtd�}xHtjdd�j�D]4}x.|j�D]}|j|�r(Pq(W|jd||f�qWdS)Nzifconfig -aT)Zpernicz/couldn't find %s nic in 'ifconfig -a' output
%s)rr3Znet_io_counters�keysrrsrv)r6r"Znicr�r#r#r$�test_nic_names?s
zTestSystemAPIs.test_nic_namesz unreliable on APPVEYOR or TRAVIScCsxtd�}|jd�}dd�|D�}dd�|D�}|jt|�ttj���x,tj�D] }|j|j|�|j|j|�qPWdS)NZwhorcSsg|]}|j�d�qS)r)r)�.0rwr#r#r$�
<listcomp>Tsz-TestSystemAPIs.test_users.<locals>.<listcomp>cSsg|]}|j�d�qS)r)r)r�rwr#r#r$r�Us)	rrr5r_r3�usersr]rPZterminal)r6�out�linesr�Z	terminals�ur#r#r$�
test_usersNs
zTestSystemAPIs.test_userscCsFtjdttjd�d��&}|jttjjt	j
��|js8t�WdQRXdS)Nzpsutil._psposix.os.killrK)r>)
rr?�OSError�errno�EBADFrYr3�_psposixZ
pid_existsrLrprBrC)r6�mr#r#r$�test_pid_exists_let_raise[sz(TestSystemAPIs.test_pid_exists_let_raisecCsFtjdttjd�d��&}|jttjjt	j
��|js8t�WdQRXdS)Nzpsutil._psposix.os.waitpidrK)r>)
rr?r�r�r�rYr3r��wait_pidrLrprBrC)r6r�r#r#r$�test_os_waitpid_let_raisedsz(TestSystemAPIs.test_os_waitpid_let_raisec
CsNtjdttjd�d��.}|jtjjtjj	t
j�dd�|js@t
�WdQRXdS)Nzpsutil._psposix.os.waitpidrK)r>g{�G�z�?)Ztimeout)rr?r�r�ZEINTRrYr3r�ZTimeoutExpiredr�rLrprBrC)r6r�r#r#r$�test_os_waitpid_eintrlsz$TestSystemAPIs.test_os_waitpid_eintrcCs>tjddd��&}|jttjjtj��|j	s0t
�WdQRXdS)Nzpsutil._psposix.os.waitpidr)rT���)rr�)rr?rYr r3r�r�rLrprBrC)r6r�r#r#r$�test_os_waitpid_bad_ret_statusus

z-TestSystemAPIs.test_os_waitpid_bad_ret_statuszunreliable on AIXc
Cs�dd�}d
}x�tjdd�D]�}tj|j�}y||j�\}}}}WnLtk
r�}	z0t|	�j�}	d|	ksvd|	ksvd	|	krzwn�WYdd}	~	XqX|j|j	||d
�|j|j
||d
�|j|j||d
�|j|j|dd
�qWdS)NcSsvtd|�j�}|jd�d}|j�}t|d�d}t|d�d}t|d�d}t|djdd	��}||||fS)
Nzdf -k %srrirk���%rK)rrrr�floatr)�devicer�r�Zfields�total�used�free�percentr#r#r$�df�sz*TestSystemAPIs.test_disk_usage.<locals>.dfr�iF)�allzno such file or directoryzraw devices not supportedzpermission denied)Zdeltarii@)
r3Zdisk_partitionsZ
disk_usageZ
mountpointr��RuntimeErrorrArOZassertAlmostEqualr�r�r�r�)
r6r�Z	tolerance�partZusager�r�r�r��errr#r#r$�test_disk_usage~s"
zTestSystemAPIs.test_disk_usageN)ryrzr{r|rr�rr~rrrr�rr3r�r�r�r�r�r�rr�r#r#r#r$rs


			r�__main__)+r|r[r�rLrQr.r�rFr3rrrrrrrZpsutil._compatr	r
Zpsutil.testsrrr
rrrrrrrrrrrr%r)r+r~ZTestCaser,rry�__file__r#r#r#r$�<module>sT
E

tests/__pycache__/test_contracts.cpython-36.pyc000064400000055706150466730550015633 0ustar003

��JZ2^�@s�dZddlZddlZddlZddlZddlZddlZddlmZddl	m
Z
ddl	mZddl	mZddl	m
Z
ddl	mZdd	l	mZdd
l	mZddl	mZddl	mZdd
l	mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddl	Z	Gd d!�d!e$j(�Z)Gd"d#�d#e$j(�Z*Gd$d%�d%e$j(�Z+Gd&d'�d'e$j(�Z,e-d(k�r�e e.�dS))z�Contracts tests. These tests mainly check API sanity in terms of
returned types and APIs availability.
Some of these are duplicates of tests test_system.py and test_process.py
�N)�closing)�AIX)�BSD)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�callable)�long)�bind_unix_socket)�check_connection_ntuple)�get_kernel_version)�HAS_CONNECTIONS_UNIX)�
HAS_RLIMIT)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�
is_namedtuple)�run_test_module_by_name)�safe_rmpath)�skip_on_access_denied)�TESTFN)�unittest)�unix_socket_path)�VALID_PROC_STATUSES)�warnc@s�eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.S)/�TestAvailabilityzQMake sure code reflects what doc promises in terms of APIs
    availability.
    cCs$tp
tp
t}|jttjd�|�dS)N�cpu_affinity)rrr�assertEqual�hasattr�psutil�Process)�self�hasit�r'�&/usr/lib64/python3.6/test_contracts.py�test_cpu_affinity<sz"TestAvailability.test_cpu_affinitycCs(|jttd�t�|jttd�t�dS)NZwin_service_iterZwin_service_get)r!r"r#r)r%r'r'r(�test_win_service@sz!TestAvailability.test_win_servicecCs|jttd�tptpt�dS)NZPROCFS_PATH)r!r"r#rrr)r%r'r'r(�test_PROCFS_PATHDsz!TestAvailability.test_PROCFS_PATHcCsj|j}|ttd�t�|ttd�t�|ttd�t�|ttd�t�|ttd�t�|ttd�t�dS)NZABOVE_NORMAL_PRIORITY_CLASSZBELOW_NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSZIDLE_PRIORITY_CLASSZNORMAL_PRIORITY_CLASSZREALTIME_PRIORITY_CLASS)r!r"r#r)r%�aer'r'r(�test_win_priorityHsz"TestAvailability.test_win_prioritycCsJ|j}|ttd�t�|ttd�t�|ttd�t�|ttd�t�dS)NZIOPRIO_CLASS_NONEZIOPRIO_CLASS_RTZIOPRIO_CLASS_BEZIOPRIO_CLASS_IDLE)r!r"r#r)r%r,r'r'r(�test_linux_ioprioQs
z"TestAvailability.test_linux_iopriocCsH|j}tot�dk}|ttjd�|�|ttd�|�|ttd�|�|ttd�|�|ttd�|�|ttd	�|�|ttd
�|�|ttd�|�|ttd�|�|ttd
�|�|ttd�|�|ttd�|�|ttd�|�to�t�dk}|ttd�|�|ttd�|�|ttd�|�|ttd�|�|ttd�|�dS)N���$�rlimitZ
RLIM_INFINITYZ	RLIMIT_ASZRLIMIT_COREZ
RLIMIT_CPUZRLIMIT_DATAZRLIMIT_FSIZEZRLIMIT_LOCKSZRLIMIT_MEMLOCK�
RLIMIT_NOFILEZRLIMIT_NPROCZ
RLIMIT_RSSZRLIMIT_STACK�rZRLIMIT_MSGQUEUEZRLIMIT_NICEZ
RLIMIT_RTPRIOZ
RLIMIT_RTTIMEZRLIMIT_SIGPENDING)r/r0r1)r4r)r!rrr"r#r$)r%r,r&r'r'r(�test_linux_rlimitXs*z"TestAvailability.test_linux_rlimitcCs:totjjd�ptjjd�}|jttd�|p2tp2t�dS)Nz/sys/devices/system/cpu/cpufreqz$/sys/devices/system/cpu/cpu0/cpufreqZcpu_freq)	r�os�path�existsr!r"r#r	r)r%�linuxr'r'r(�
test_cpu_freqpszTestAvailability.test_cpu_freqcCs|jttd�t�dS)N�sensors_temperatures)r!r"r#r)r%r'r'r(�test_sensors_temperaturesvsz*TestAvailability.test_sensors_temperaturescCs|jttd�t�dS)N�sensors_fans)r!r"r#r)r%r'r'r(�test_sensors_fansysz"TestAvailability.test_sensors_fanscCs"|jttd�tptptpt�dS)NZsensors_battery)r!r"r#rrrr	)r%r'r'r(�test_battery|szTestAvailability.test_batterycCs |jttjd�tptpt�dS)N�environ)r!r"r#r$rr	r)r%r'r'r(�test_proc_environ�sz"TestAvailability.test_proc_environcCs|jttjd�t�dS)N�uids)r!r"r#r$r
)r%r'r'r(�test_proc_uids�szTestAvailability.test_proc_uidscCs|jttjd�t�dS)NrB)r!r"r#r$r
)r%r'r'r(�test_proc_gids�szTestAvailability.test_proc_gidscCs|jttjd�t�dS)N�terminal)r!r"r#r$r
)r%r'r'r(�test_proc_terminal�sz#TestAvailability.test_proc_terminalcCs|jttjd�tpt�dS)N�ionice)r!r"r#r$rr)r%r'r'r(�test_proc_ionice�sz!TestAvailability.test_proc_ionicecCs|jttjd�t�dS)Nr2)r!r"r#r$r)r%r'r'r(�test_proc_rlimit�sz!TestAvailability.test_proc_rlimitcCs(ttjd�}|j|tstrdnd�dS)N�io_countersFT)r"r#r$r!r	r)r%r&r'r'r(�test_proc_io_counters�sz&TestAvailability.test_proc_io_counterscCs|jttjd�t�dS)N�num_fds)r!r"r#r$r
)r%r'r'r(�test_proc_num_fds�sz"TestAvailability.test_proc_num_fdscCs|jttjd�t�dS)N�num_handles)r!r"r#r$r)r%r'r'r(�test_proc_num_handles�sz&TestAvailability.test_proc_num_handlescCs |jttjd�tptpt�dS)Nr )r!r"r#r$rrr)r%r'r'r(�test_proc_cpu_affinity�sz'TestAvailability.test_proc_cpu_affinitycCs |jttjd�tptpt�dS)N�cpu_num)r!r"r#r$rrr)r%r'r'r(�test_proc_cpu_num�sz"TestAvailability.test_proc_cpu_numcCs,ttjd�}|j|tststr"dnd�dS)N�memory_mapsFT)r"r#r$r!rrr)r%r&r'r'r(�test_proc_memory_maps�sz&TestAvailability.test_proc_memory_mapsN)�__name__�
__module__�__qualname__�__doc__r)r*r+r-r.r5r:r<r>r?rArCrDrFrHrIrKrMrOrPrRrTr'r'r'r(r7s.	rc@seZdZdd�ZdS)�TestDeprecationscCsdtjdd��}tj�j�WdQRX|d}|j|j�t�|jdt	|j
��|jdt	|j
��dS)NT)�recordrzmemory_info_ex() is deprecatedzuse memory_info() instead)�warnings�catch_warningsr#r$�memory_info_ex�assertIsInstance�category�
FutureWarning�assertIn�str�message)r%Zws�wr'r'r(�test_memory_info_ex�sz$TestDeprecations.test_memory_info_exN)rUrVrWrer'r'r'r(rY�srYc@s�eZdZdZedd��Zdd�Zdd�Zdd	�Zd
d�Z	e
jed�e
je
d
�eed�dd����Zdd�Zdd�Zdd�Ze
jed�dd��Ze
jed�dd��Zdd�ZdS)�
TestSystemz�Check the return types of system related APIs.
    Mainly we want to test we never return unicode on Python 2, see:
    https://github.com/giampaolo/psutil/issues/1039
    cCstj�|_dS)N)r#r$�proc)�clsr'r'r(�
setUpClass�szTestSystem.setUpClasscCstt�dS)N)rr)r%r'r'r(�tearDown�szTestSystem.tearDowncCs>tj�}t|�st�x$|D]}|j|t�|j|d�qWdS)Nr)r#�	cpu_timesr�AssertionErrorr^�float�assertGreaterEqual)r%�ret�nr'r'r(�test_cpu_times�s

zTestSystem.test_cpu_timescCs&x tjdd�D]}|j|t�qWdS)NT)Zperdisk)r#Zdisk_io_countersr^rb)r%�kr'r'r(�test_io_counters�szTestSystem.test_io_counterscCsNxHtj�D]<}|j|jt�|j|jt�|j|jt�|j|jt�q
WdS)N)r#Zdisk_partitionsr^ZdevicerbZ
mountpointZfstypeZopts)r%Zdiskr'r'r(�test_disk_partitions�s
zTestSystem.test_disk_partitionsz
POSIX onlyzcan't list UNIX sockets)Zonly_ifcCs^t��N}tt|���6tjdd�}|s*t�x|D]}|j|jt�q0WWdQRXWdQRXdS)NZunix)Zkind)	rrrr#Znet_connectionsrlr^Zladdrrb)r%�nameZcons�connr'r'r(�test_net_connections�s
zTestSystem.test_net_connectionscCsrxltj�j�D]\\}}|j|t�xF|D]>}|j|jt�|j|jttd�f�|j|jttd�f�q(WqWdS)N)	r#Znet_if_addrs�itemsr^rbZaddressZnetmask�typeZ	broadcast)r%�ifnameZaddrs�addrr'r'r(�test_net_if_addrs�s
zTestSystem.test_net_if_addrscCs*x$tj�j�D]\}}|j|t�qWdS)N)r#Znet_if_statsrxr^rb)r%rz�_r'r'r(�test_net_if_stats�szTestSystem.test_net_if_statscCs.x(tjdd�j�D]\}}|j|t�qWdS)NT)Zpernic)r#Znet_io_countersrxr^rb)r%rzr}r'r'r(�test_net_io_counters�szTestSystem.test_net_io_countersz
not supportedcCsFx@tj�j�D]0\}}|j|t�x|D]}|j|jt�q(WqWdS)N)r#r=rxr^rb�label)r%ru�units�unitr'r'r(r>�s
zTestSystem.test_sensors_fanscCsFx@tj�j�D]0\}}|j|t�x|D]}|j|jt�q(WqWdS)N)r#r;rxr^rbr�)r%rur�r�r'r'r(r<s
z$TestSystem.test_sensors_temperaturescCsfx`tj�D]T}|j|jt�|j|jttd�f�|j|jttd�f�|j|jt	td�f�q
WdS)N)
r#�usersr^rurbrEry�host�pid�int)r%�userr'r'r(�
test_userss
zTestSystem.test_usersN)rUrVrWrX�classmethodrirjrqrsrtrZskipIfr
rrr	rwr|r~rrr>rr<r�r'r'r'r(rf�s		rfc@s(eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*d+�Zd,d-�Zd.d/�Zd0d1�Zd2d3�Zd4d5�Zd6d7�Zd8d9�Zd:d;�Z d<d=�Z!d>d?�Z"d@dA�Z#dBdC�Z$dDdE�Z%dFdG�Z&dHS)I�TestFetchAllProcessesz~Test which iterates over all running processes and performs
    some sanity checks against Process API's returned values.
    cCsdtr`ddl}ddl}|j�}|j�}tdd�|D��|_tdd�|D��|_tdd�|D��|_dS)NrcSsg|]
}|j�qSr')Zpw_uid)�.0�xr'r'r(�
<listcomp>(sz/TestFetchAllProcesses.setUp.<locals>.<listcomp>cSsg|]
}|j�qSr')Zpw_name)r�r�r'r'r(r�)scSsg|]
}|j�qSr')Zgr_gid)r�r�r'r'r(r�*s)	r
�pwd�grpZgetpwallZgetgrall�set�all_uids�
all_usernames�all_gids)r%r�r�r��groupsr'r'r(�setUp"szTestFetchAllProcesses.setUpcCs�d}tdddddddd	d
ddg�}tr6tr6|jd
�g}x2ttj�D]$}|jd�rVqF||kr`qF|j|�qFWt	�}g}�x(tj
�D�]}|j����x�|D�]�}|}ydf}	i}
t||d�}|dk	r�t
|�r�|d
kr�tjf}	n|dkr�ddi}
||	|
�}n|}|d7}W�nLtk
�r>d|jjd|}t|�Yq�tjtjfk
�r�}
zJ|j|
j|j�|
j�r�|j|
j|j��t|
��s�t�|
j�s�t�WYdd}
~
Xq�tk
�rX}
z�dddd}|d||f7}||k�r�|dt|�7}|d7}|dd7}|dtj�7}djdd�|j �D��}|d7}|j|�PWYdd}
~
Xq�X|ddgdd ifk�r~|�s~t|��t||�}|||�q�WWdQRXq�W|�r�|j!d j|��|�s�t�dS)!NrZsend_signalZsuspendZresumeZ	terminate�kill�waitZas_dict�parentZchildrenr]�oneshotr2r}rSZgroupedF�z&%r was skipped because not implementedz.test_�
�=�FzFAIL: test_%s (proc=%sz	, ret=%s)z)
�-z
%scss|]}d|VqdS)� �Nz    r')r��ir'r'r(�	<genexpr>csz7TestFetchAllProcesses.test_fetch_all.<locals>.<genexpr>g�)"r�rr�add�dirr#r$�
startswith�append�objectZprocess_iterr��getattrr
r3�NotImplementedError�	__class__rUrZ
NoSuchProcessZAccessDeniedr!r�rurbrl�msg�	Exception�repr�	traceback�
format_exc�join�
splitlinesZfail)r%Zvalid_procsZexcluded_namesZattrsru�defaultZfailures�pro�args�kwargs�attrr��err�s�methr'r'r(�test_fetch_all,sx






z$TestFetchAllProcesses.test_fetch_allcCs*|j|t�x|D]}|j|t�qWdS)N)r^�listrb)r%rorg�partr'r'r(�cmdlinets
zTestFetchAllProcesses.cmdlinecCst|j|ttd�f�|s&|j|d�nJtjj|�s:t|��trptjj	|�rpt
td�rpt
td�rptj|tj�spt�dS)Nr��access�X_OK)
r^rbryr!r6r7�isabsrlr
�isfiler"r�r�)r%rorgr'r'r(�exeyszTestFetchAllProcesses.execCs|j|t�|j|d�dS)Nr)r^r�rn)r%rorgr'r'r(r��szTestFetchAllProcesses.pidcCs |j|ttf�|j|d�dS)Nr)r^r�rrn)r%rorgr'r'r(�ppid�szTestFetchAllProcesses.ppidcCs|j|t�ts|st�dS)N)r^rbrrl)r%rorgr'r'r(ru�szTestFetchAllProcesses.namecCs^|j|t�y|j|d�Wn*tk
rFtr@|j�tjkr@n�YnXtj	dtj
|��dS)Nrz%Y %m %d %H:%M:%S)r^rmrnrlr�statusr#Z
STATUS_ZOMBIE�timeZstrftimeZ	localtime)r%rorgr'r'r(�create_time�sz!TestFetchAllProcesses.create_timecCsDt|�st�x2|D]*}|j|t�|j|d�|j||j�qWdS)Nr)rrlr^r�rnrar�)r%rorgZuidr'r'r(rB�s

zTestFetchAllProcesses.uidscCsPt|�st�x>|D]6}|j|t�trtr|j|d�|j||j�qWdS)Nr)	rrlr^r�r	rrnrar�)r%rorg�gidr'r'r(�gids�s
zTestFetchAllProcesses.gidscCs*|j|t�|st�tr&|j||j�dS)N)r^rbrlr
rar�)r%rorgr'r'r(�username�szTestFetchAllProcesses.usernamecCs0|j|t�|st�|j|d�|j|t�dS)N�?)r^rbrlZassertNotEqualrar)r%rorgr'r'r(r��szTestFetchAllProcesses.statuscCsBt|�st�x0|D](}|j|ttf�|dkr|j|d�qWdS)Nr�r���)rrlr^r�rrn)r%rorg�fieldr'r'r(rJ�s

z!TestFetchAllProcesses.io_counterscCshtr*t|�st�x|D]}|j|t�qWtrL|j|jd�|j|jd�n|j|d�|j	|d�dS)Nrr�r/)rr�r/)
r
rrlr^r�rrnZioclass�valuera)r%rorgr�r'r'r(rG�s
zTestFetchAllProcesses.ionicecCs|j|t�|j|d�dS)Nr�)r^r�rn)r%rorgr'r'r(�num_threads�sz!TestFetchAllProcesses.num_threadscCsr|j|t�x`|D]X}t|�s"t�|j|jd�|j|jd�|j|jd�x|D]}|j|tt	f�qRWqWdS)Nr)
r^r�rrlrn�idZ	user_timeZsystem_timer�rm)r%rorg�tr�r'r'r(�threads�s

zTestFetchAllProcesses.threadscCs6t|�st�x$|D]}|j|t�|j|d�qWdS)Nr)rrlr^rmrn)r%rorgrpr'r'r(rk�s
zTestFetchAllProcesses.cpu_timescCs0|j|t�d|kodkns,t|��dS)NggY@)r^rmrl)r%rorgr'r'r(�cpu_percent�sz!TestFetchAllProcesses.cpu_percentcCs\|j|t�tr|dkrdS|j|d�tj�dkr@|j|d�|j|tt	tj����dS)Nr�rr�)
r^r�rrnr#�	cpu_countr!rar��range)r%rorgr'r'r(rQ�szTestFetchAllProcesses.cpu_numcCs�t|�st�x(|D] }|j|ttf�|j|d�qWtr�tr�|jdkr�xx|j	D](}|dkrRt
||�}|j|j||d�qRWnDtr�|j|j
|j�|j|j|j�|j|j|j�|j|j|j�dS)Nr�vms)r�)rrlr^r�rrnr
rr��_fieldsr��
assertGreaterrZ	peak_wsetZwsetZpeak_paged_poolZ
paged_poolZpeak_nonpaged_poolZ
nonpaged_poolZ
peak_pagefileZpagefile)r%rorgr�rur'r'r(�memory_info�s

z!TestFetchAllProcesses.memory_infocCs�t|�st�tj�j}xR|jD]H}t||�}|j|tt	f�|j
|d||fd�|j|||||fd�qWtr~|j
|j
|j�dS)Nr)r�)rrlr#Zvirtual_memory�totalr�r�r^r�rrnZassertLessEqualrZpssZuss)r%rorgr�rur�r'r'r(�memory_full_infos

z&TestFetchAllProcesses.memory_full_infocCs�|j|t�x�|D]�}|j|jt�|j|jt�trF|j|jd�nhtr�|j|j	t�|j|j
t�|j|jt�|j|j	d�|j
|j
d	�|j|jd�ntr�|jr�qtjj|j�s�t|��tjj|j�st|��qWdS)
Nr�r�rrd�a�r+�a+r�)r�rdr�r�r�)r^r��fdr�r7rbrr!rZposition�mode�flagsrnrar�rr6r�rlr�)r%rorg�fr'r'r(�
open_filess"
z TestFetchAllProcesses.open_filescCs|j|t�|j|d�dS)Nr)r^r�rn)r%rorgr'r'r(rL(szTestFetchAllProcesses.num_fdscCs2|jt|�tt|���x|D]}t|�qWdS)N)r!�lenr�r)r%rorgrvr'r'r(�connections,s
z!TestFetchAllProcesses.connectionscCs�|r�|j|t�tjj|�s$t|��ytj|�}WnDtk
rv}z(trX|j	t
jjkrXn|j	t	j
krf�WYdd}~XnXtj|j�s�t�dS)N)r^rbr6r7r�rl�stat�OSErrorr�errnor#Z_psplatformZACCESS_DENIED_SET�ENOENT�S_ISDIR�st_mode)r%rorg�str�r'r'r(�cwd1s
zTestFetchAllProcesses.cwdcCs0|j|t�d|kodkns,t|��dS)Nr�d)r^rmrl)r%rorgr'r'r(�memory_percentAsz$TestFetchAllProcesses.memory_percentcCs|j|t�dS)N)r^�bool)r%rorgr'r'r(�
is_runningEsz TestFetchAllProcesses.is_runningcCsR|j|t�|gkst|��ttj��}x$|D]}|j|t�|j||�q.WdS)N)r^r�rlr�r#r�r�ra)r%rorgZcpusrpr'r'r(r Hs
z"TestFetchAllProcesses.cpu_affinitycCsH|j|ttd�f�|dk	rDtjj|�s0t|��tjj|�sDt|��dS)N)r^rbryr6r7r�rlr8)r%rorgr'r'r(rEPszTestFetchAllProcesses.terminalcCs�x�|D]�}|j|jt�|j|jt�|j|jt�xr|jD]h}t||�}|dkrv|jd�s�tjj	|j�s�t
|j��q<|dkr�|s�t
�q<|j|ttf�|j
|d�q<WqWdS)Nr7�[r{�permsr)r{r�)r^r{rbr�r7r�r�r�r6r�rlr�rrn)r%rorg�ntZfnamer�r'r'r(rSVs



z!TestFetchAllProcesses.memory_mapscCs|j|t�|j|d�dS)Nr)r^r�rn)r%rorgr'r'r(rNisz!TestFetchAllProcesses.num_handlescCsT|j|t�tr2d|ko"dknsPt|��ndd�tt�D�}|j||�dS)N�cSs g|]}|jd�rtt|��qS)Z_PRIORITY_CLASS)�endswithr�r#)r�r�r'r'r(r�rsz.TestFetchAllProcesses.nice.<locals>.<listcomp>i��)r^r�r
rlr�r#ra)r%rorgZ
prioritiesr'r'r(�nicems
"zTestFetchAllProcesses.nicecCs:t|�st�x(|D] }|j|ttf�|j|d�qWdS)Nr)rrlr^r�rrn)r%rorgr�r'r'r(�num_ctx_switchesvs
z&TestFetchAllProcesses.num_ctx_switchescCs@|j|t�|jt|�d�|j|dd�|j|dd�dS)Nr/rr�r�r�)r^�tupler!r�rn)r%rorgr'r'r(r2|szTestFetchAllProcesses.rlimitcCs>|j|t�x,|j�D] \}}|j|t�|j|t�qWdS)N)r^�dictrxrb)r%rorgrr�vr'r'r(r@�szTestFetchAllProcesses.environN)'rUrVrWrXr�r�r�r�r�r�rur�rBr�r�r�rJrGr�r�rkr�rQr�r�r�rLr�r�r�r�r rErSrNr�r�r2r@r'r'r'r(r�sH
H

		r��__main__)/rXr�r6r�r�r�r[�
contextlibrr#rrrrrrr	r
rrZpsutil._compatr
rZpsutil.testsrrrrrrrrrrrrrrrrZTestCaserrYrfr�rU�__file__r'r'r'r(�<module>	sXx^n
tests/__pycache__/test_connections.cpython-36.opt-1.pyc000064400000034302150466730550017101 0ustar003

��JZ�P�@s8dZddlZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ddl
Z
ddl
mZdd	l
mZdd
l
m
Z
ddl
mZddl
mZdd
l
mZddl
mZddl
mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&dd!lm'Z'dd"lm(Z(dd#lm)Z)dd$lm*Z*e
j+�Z,Gd%d&�d&e-�Z.Gd'd(�d(e.e'j/�Z0Gd)d*�d*e.e'j/�Z1Gd+d,�d,e.e'j/�Z2Gd-d.�d.e'j/�Z3e4d/k�r4e!e5�dS)0z;Tests for net_connections() and Process.connections() APIs.�N)�closing)�AF_INET)�AF_INET6)�
SOCK_DGRAM)�SOCK_STREAM)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�
supports_ipv6)�PY3)�AF_UNIX)�bind_socket)�bind_unix_socket)�check_connection_ntuple)�create_sockets)�
get_free_port)�HAS_CONNECTIONS_UNIX)�pyrun)�
reap_children)�run_test_module_by_name)�safe_rmpath)�skip_on_access_denied)�tcp_socketpair)�TESTFN)�TRAVIS)�unittest)�unix_socket_path)�unix_socketpair)�
wait_for_filec@s8eZdZdd�Zdd�Zdd�Zd
dd	�Zddd�ZdS)�BasecCststjdd�}dS)N�all)�kind)r	�thisproc�connections)�self�cons�r+�(/usr/lib64/python3.6/test_connections.py�setUp6sz
Base.setUpcCs"tt�t�tstjdd�}dS)Nr%)r&)rrrr	r'r()r)r*r+r+r,�tearDown<s
z
Base.tearDowncCsrtjdd�}tdd�|D��}tr.||j�S|jt|�d�|djdkrf|j||j�j|j��|dSdS)Nr%)r&cSsg|]}|j|f�qSr+)�fd)�.0�cr+r+r,�
<listcomp>Gsz+Base.get_conn_from_sock.<locals>.<listcomp>�r���)r'r(�dictr	�fileno�assertEqual�lenr/)r)�sockr*Zsmapr+r+r,�get_conn_from_sockEszBase.get_conn_from_sockNcCs�|dkr|j|�}t|�|jdkr6|j|j|j��|j|j|j�|j|j|jtj	tj
��|j�}|r�tr�t
|t�r�|j�}|jtkr�|dd�}|jtkr�tr�n|j|j|�|jtkr�tr�tjdd�}|jtj�|�|S)z�Given a socket, makes sure it matches the one obtained
        via psutil. It assumes this process created one connection
        only (the one supposed to be checked).
        Nr3�r%)r&r4)r:rr/r7r6�family�typeZ
getsockopt�socketZ
SOL_SOCKETZSO_TYPEZgetsocknamer�
isinstance�bytes�decoderrr
�laddrrr'r(�compare_procsys_connections�os�getpid)r)r9�connrBr*r+r+r,�check_socketRs(


zBase.check_socketr%csdytj|d�}Wn tjk
r0tr*dS�YnX�fdd�|D�}|j�|j�|j||�dS)z�Given a process PID and its list of connections compare
        those against system-wide connections retrieved via
        psutil.net_connections.
        )r&Ncs"g|]}|j�kr|dd��qS)Nr3r4)�pid)r0r1)rHr+r,r2�sz4Base.compare_procsys_connections.<locals>.<listcomp>)�psutil�net_connectionsZAccessDeniedr�sortr7)r)rHZ	proc_consr&Zsys_consr+)rHr,rCvsz Base.compare_procsys_connections)N)r%)�__name__�
__module__�__qualname__r-r.r:rGrCr+r+r+r,r$4s
	
$r$c@s|eZdZdZdd�Zeje�d�dd��Zdd�Z	eje�d�d	d
��Z
ejed�dd
��Zejed�dd��Z
dS)�TestUnconnectedSocketsz;Tests sockets which are open but not connected to anything.c
CsFdt�f}tttt|d��� }|j|�}|j|jtj	�WdQRXdS)Nz	127.0.0.1)�addr)
rrrrrrGr7�statusrI�CONN_LISTEN)r)rPr9rFr+r+r,�test_tcp_v4�s

z"TestUnconnectedSockets.test_tcp_v4zIPv6 not supportedc
CsFdt�f}tttt|d��� }|j|�}|j|jtj	�WdQRXdS)Nz::1)rP)
rrrrrrGr7rQrIrR)r)rPr9rFr+r+r,�test_tcp_v6�s

z"TestUnconnectedSockets.test_tcp_v6c
CsFdt�f}tttt|d��� }|j|�}|j|jtj	�WdQRXdS)Nz	127.0.0.1)rP)
rrrrrrGr7rQrI�	CONN_NONE)r)rPr9rFr+r+r,�test_udp_v4�s

z"TestUnconnectedSockets.test_udp_v4c
CsFdt�f}tttt|d��� }|j|�}|j|jtj	�WdQRXdS)Nz::1)rP)
rrrrrrGr7rQrIrU)r)rPr9rFr+r+r,�test_udp_v6�s

z"TestUnconnectedSockets.test_udp_v6z
POSIX onlycCsLt��<}tt|td��� }|j|�}|j|jtj�WdQRXWdQRXdS)N)r=)	r!rrrrGr7rQrIrU)r)�namer9rFr+r+r,�
test_unix_tcp�s
z$TestUnconnectedSockets.test_unix_tcpcCsLt��<}tt|td��� }|j|�}|j|jtj�WdQRXWdQRXdS)N)r=)	r!rrrrGr7rQrIrU)r)rXr9rFr+r+r,�
test_unix_udp�s
z$TestUnconnectedSockets.test_unix_udpN)rLrMrN�__doc__rSr �skipIfrrTrVrWrrYrZr+r+r+r,rO�srOc@sTeZdZdZejed�dd��Zejed�dd��Z	e
ed�d	d
��Zdd�Z
d
S)�TestConnectedSocketPairszJTest socket pairs which are are actually connected to
    each other.
    zunreliable on SUONSc
Cszdt�f}tt|d�\}}zHtjdd�}|jt|�d�|j|djtj	�|j|djtj	�Wd|j
�|j
�XdS)Nz	127.0.0.1)rP�tcp4)r&r;rr3)rrrr'r(r7r8rQrIZCONN_ESTABLISHED�close)r)rP�server�clientr*r+r+r,�test_tcp�s
z!TestConnectedSocketPairs.test_tcpz
POSIX onlycCs2t��� }t|�\}}z�tjdd�}tr6dd�|D�}|jt|�d�tsRtsRt	r�|j|dj
d�|j|dj
d�|j||djp�|dj�nztr�xt|dj|dj
|dj|dj
fD]}|j|d�q�Wn:|j|djp�|dj|�|j|dj
�p|dj
|�Wd|j
�|j
�XWdQRXdS)	N�unix)r&cSsg|]}|jdkr|�qS)z/var/run/log)�raddr)r0r1r+r+r,r2�sz6TestConnectedSocketPairs.test_unix.<locals>.<listcomp>r;r�r3)r!r"r'r(r	r7r8rrr
rdrBr
r_)r)rXr`rar*rPr+r+r,�	test_unix�s&
"z"TestConnectedSocketPairs.test_unix)Zonly_ifcs�fdd�}tjd�}tjd�}ddlm}tjjt�}||�jt	t
�d|d�}||�jt	t
�d|d�}||�jt	t�d	|d�}||�jt	t�d	|d�}	t|�}
t
t|��}t|�}t
t|��}
t�r�t|�}t
t|��}t|	�}t
t|��}nd}d}d}d}�x�tj�D�]�}|j�}�jt|�d
�x�|D]�}|j|
jk�r\|||t
t|ftjd�n�|j|jk�r�|||t
t|
ftjd�nZ|jt|dd�k�r�|||tt|ftjd�n,|jt|dd�k�r0|||tt|ftjd��q0W�qW�jt|jdd�dS)Nc
s�d}t|��j|j|��j|j|��j|j|��j|j|��j|j|�x"|D]}	|j|	d�}
|	|krXqXqXWtr��j	|j
|g�dS)
Nr%�inet�inet4�inet6�tcpr^�tcp6�udp�udp4�udp6)r&)
r%rgrhrirjr^rkrlrmrn)rr7r<r=rBrdrQr(rrCrH)�procrFr<r=rBrdrQZkindsZ	all_kindsr&r*)r)r+r,�
check_conns
z8TestConnectedSocketPairs.test_combos.<locals>.check_conna
            import socket, time
            s = socket.socket($family, socket.SOCK_STREAM)
            s.bind(('$addr', 0))
            s.listen(1)
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        z�
            import socket, time
            s = socket.socket($family, socket.SOCK_DGRAM)
            s.bind(('$addr', 0))
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        r)�Templatez	127.0.0.1)r<rPZtestfnz::1r3r%rgrhrjr^rlrmrHrirkrnz???)r&)r%rgrhrjr^)r%rgrhrlrm)r%rgrirjrk)r%rgrirlrn)�textwrap�dedent�stringrqrD�path�basenamerZ
substitute�intrrr�evalr#rr'Zchildrenr(r7r8rHrrIrRrrU�getattr�assertRaises�
ValueError)r)rpZtcp_templateZudp_templaterqZtestfileZ
tcp4_templateZ
udp4_templateZ
tcp6_templateZ
udp6_templateZ	tcp4_procZ	tcp4_addrZ	udp4_procZ	udp4_addrZ	tcp6_procZ	tcp6_addrZ	udp6_procZ	udp6_addr�pr*rFr+)r)r,�test_combossb
z$TestConnectedSocketPairs.test_comboscCs�t����}tjdd�}|jt|�t|��tjdd�}|jt|�t�rJdnd�x,|D]$}|j|jtt	f�|j|j
t�qVWtjdd�}|jt|�d�|j|djt�|j|dj
t�t��rtjdd�}|jt|�d�|j|djt	�|j|dj
t�tjd	d�}|jt|�t��r(dnd�x.|D]&}|j|jtt	f�|j|j
t��q4Wtjd
d�}|jt|�d�|j|djt�|j|dj
t�t��r�tjdd�}|jt|�d�|j|djt	�|j|dj
t�tjdd�}|jt|�t��rd
nd�x2|D]*}|j|jtt	f�|j|j
ttf��qWt��r�tjdd�}|jt|�d�x.|D]&}|j|jt	�|j|j
ttf��qlWt
�r�tjdd�}|jt|�d�x.|D]&}|j|jt�|j|j
ttf��q�WWdQRXdS)Nr%)r&rjr;r3r^rrkrlrmrnrg�rirc�)rr'r(r7r8r�assertInr<rrr=rrrr)r)�socksr*rFr+r+r,�test_multi_sockets_filteringes`





z5TestConnectedSocketPairs.test_multi_sockets_filteringN)rLrMrNr[r r\r
rbrrfrrr}r�r+r+r+r,r]�s
!br]c@sJeZdZdZe�dd��Ze�dd��Ze�eje	o6e
d�dd���Zd	S)
�TestSystemWideConnectionszTests for net_connections().c
s��fdd�}t���ddlm}xZ|j�D]N\}}|dkrBtrBq*|\}}tj|�}�jt|�tt	|���||||�q*W�j
ttjdd�WdQRXdS)NcsVttdt��}xB|D]:}�j|j||d�|j|krF�j|j||d�t|�qWdS)Nr)�msg)ryr>�objectr�r<r=r)r*�families�types_rrF)r)r+r,�check�s

z0TestSystemWideConnections.test_it.<locals>.checkr)�	conn_tmaprcz???)r&)r�psutil._commonr��itemsrrIrJr7r8�setrzr{)r)r�r�r&�groupsr�r�r*r+)r)r,�test_it�s
z!TestSystemWideConnections.test_itcCs@t��0}dd�tjdd�D�}|jt|�t|��WdQRXdS)NcSsg|]}|jtj�kr|�qSr+)rHrDrE)r0�xr+r+r,r2�sz>TestSystemWideConnections.test_multi_socks.<locals>.<listcomp>r%)r&)rrIrJr7r8)r)r�r*r+r+r,�test_multi_socks�sz*TestSystemWideConnections.test_multi_sockszunreliable on OSX + TRAVISc

st��}t|�}WdQRXg�d}xRt|�D]F}tjjt�t|�}tj	d|�}t
|�}�j|j�|j
t|�q,Wx$t|�D]}tt|�}t|�q�W�fdd�tjdd�D�}xJ�D]B�|jt�fdd�|D��|�tj��}	|jt|	jd��|�q�WdS)N�
a                import time, os
                from psutil.tests import create_sockets
                with create_sockets():
                    with open('%s', 'w') as f:
                        f.write(str(os.getpid()))
                    time.sleep(60)
                csg|]}|j�kr|�qSr+)rH)r0r�)�pidsr+r,r2�szFTestSystemWideConnections.test_multi_sockets_procs.<locals>.<listcomp>r%)r&csg|]}|j�kr|�qSr+)rH)r0r�)rHr+r,r2�s)rr8�rangerDru�realpathr�strrrrsr�appendrHZ
addCleanuprr#rIrJr7�Processr()
r)r�Zexpected�times�iZfname�srcZsprocZsysconsr|r+)rHr�r,�test_multi_sockets_procs�s(



z2TestSystemWideConnections.test_multi_sockets_procsN)rLrMrNr[rr�r�r r\rrr�r+r+r+r,r��s
r�c@seZdZdd�ZdS)�TestMisccCs�g}g}xXtt�D]L}|jd�rtt|�}t|�}|jt|�|j||�|j|�|j|�qWtrrtjtj	t
r|tjdS)NZCONN_)�dirrI�
startswithryr�ZassertNotInr�r
Z	CONN_IDLEZ
CONN_BOUNDrZCONN_DELETE_TCB)r)ZintsZstrsrXZnumZstr_r+r+r,�test_connection_constants�s


z"TestMisc.test_connection_constantsN)rLrMrNr�r+r+r+r,r��sr��__main__)6r[rDr>rr�
contextlibrrrrrrIrrr	r
rrr
rr�rZpsutil._compatrZpsutil.testsrrrrrrrrrrrrrrrr r!r"r#r�r'r�r$ZTestCaserOr]r�r�rL�__file__r+r+r+r,�<module>s^\7`P
tests/__pycache__/test_process.cpython-36.pyc000064400000120120150466730550015270 0ustar003

��JZ9��@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlmZddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ddlm,Z,ddlm-Z-dd lm.Z.dd!lm/Z/dd"lm0Z0dd#lm1Z1dd$lm2Z2dd%lm3Z3dd&lm4Z4dd'lm5Z5dd(lm6Z6dd)lm7Z7dd*lm8Z8dd+lm9Z9dd,lm:Z:dd-lm;Z;dd.lm<Z<dd/lm=Z=Gd0d1�d1e;j>�Z?e�r�ej@�dk�r�Gd2d3�d3e?�ZAGd4d5�d5e;j>�ZBeCd6k�r�e2eD�dS)7zTests for psutil.Process class.�N)�AIX)�BSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�long)�PY3)�APPVEYOR)�
call_until)�copyload_shared_lib)�
create_exe)�create_proc_children_pair)�create_zombie_proc)�enum)�get_test_subprocess)�
get_winver)�HAS_CPU_AFFINITY)�HAS_ENVIRON)�
HAS_IONICE)�HAS_MEMORY_MAPS)�HAS_PROC_CPU_NUM)�HAS_PROC_IO_COUNTERS)�
HAS_RLIMIT)�HAS_THREADS)�mock)�PYPY)�
PYTHON_EXE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�safe_rmpath)�sh)�skip_on_access_denied)�skip_on_not_implemented)�TESTFILE_PREFIX)�TESTFN)�
ThreadTask)�TRAVIS)�unittest)�wait_for_pid)�	WIN_VISTAc@sreZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zejed�dd��Zdd �Zejed!�ejed"�d#d$���Zejed�eed%�d&d'���Zejed�ejeo�e�e kd�d(d)���Z!ejed�eje�oe�e kd�d*d+���Z"eje#d�d,d-��Z$eje#d�d.d/��Z%eje#d�d0d1��Z&eje#d�d2d3��Z'eje#d�d4d5��Z(d6d7�Z)ejed8�d9d:��Z*eje+d�d;d<��Z,e-�e.e/d%�eje+d�d=d>����Z0d?d@�Z1dAdB�Z2eje3d�dCdD��Z4eje3d�dEdF��Z5dGdH�Z6dIdJ�Z7dKdL�Z8dMdN�Z9dOdP�Z:eje;dQ�eje<dR�dSdT���Z=ejed!�dUdV��Z>ejed!�dWdX��Z?dYdZ�Z@d[d\�ZAd]d^�ZBd_d`�ZCdadb�ZDejeEd�dcdd��ZFejeEd�dedf��ZGejeEd�dgdh��ZHejeIdi�ejeJdj�dkdl���ZKejeIdi�ejeJdj�dmdn���ZLejed!�dodp��ZMeed%�ejeN�pzeOdq�drds���ZPdtdu�ZQdvdw�ZRdxdy�ZSdzd{�ZTd|d}�ZUd~d�ZVd�d��ZWd�d��ZXd�d��ZYd�d��ZZd�d��Z[d�d��Z\ejed!�d�d���Z]ejed!�d�d���Z^ejed!�d�d���Z_d�d��Z`ejead�d�d���Zbejead�ejed!�d�d����Zcd�S)��TestProcesszTests for psutil.Process class.cCstt�dS)N)r$r))�self�r1�$/usr/lib64/python3.6/test_process.py�setUpNszTestProcess.setUpcCs
t�dS)N)r!)r0r1r1r2�tearDownQszTestProcess.tearDownc	CsXtj�}|j|jtj��t�}|jtj|j�j|j�|jt��d|_WdQRXdS)N�!)	�psutil�Process�assertEqual�pid�os�getpidr�assertRaises�AttributeError)r0�p�sprocr1r1r2�test_pidTszTestProcess.test_pidcCsNt�}|j}tj|�}|j�|j�}|jtj|��trJ|j	|t
j�dS)N)rr9r6r7�kill�wait�assertFalse�
pid_existsrr8�signal�SIGKILL)r0r?r@r>�sigr1r1r2�	test_kill\s
zTestProcess.test_killcCsNt�}|j}tj|�}|j�|j�}|jtj|��trJ|j	|t
j�dS)N)rr9r6r7�	terminaterBrCrDrr8rE�SIGTERM)r0r?r@r>rGr1r1r2�test_terminatefs
zTestProcess.test_terminatec CsLtr
tjntj}t�}tj|j�}|j|�|j	�}|j
tj|j��t�rH|j||�t�}tj|j�}|j|�t
jdttjd�d��(|jtj��|j|�WdQRXWdQRXt�}tj|j�}|j|�t
jdttjd�d��,|jtj��tj�j|�WdQRXWdQRXdtj�k�rHtjd�}|jt|jtj�dS)Nzpsutil.os.kill�)�side_effectr)rrErFrJrr6r7r9�send_signalrBrCrDr8r�patch�OSError�errnoZESRCHr<�
NoSuchProcessZEPERM�AccessDenied�pids�
ValueError)r0rGr?r>Zexit_sigr1r1r2�test_send_signalps2


"
zTestProcess.test_send_signalcCs^t�}tj|j�}|j�|j�}tr8|j|tj	�n|j|tj
�|j|j��t�}tj|j�}|j
�|j�}tr�|j|tj
�n|j|tj
�|j|j��d}ttd|g�}tj|j�}|j|j�d�|j|j��ttd|g�}tj|j�}|j|j�d�|j|j�d�t�}tj|j�}|j�|jtj|jd�|jt|jd�dS)Nz0import time, sys; time.sleep(0.01); sys.exit(5);z-c�g{�G�z�?�)rWN���)rr6r7r9rArBrr8rErFrJrC�
is_runningrIr �assertIn�namer<�TimeoutExpiredrU)r0r?r>�coder1r1r2�	test_wait�s<zTestProcess.test_waitcCs�t�\}}|jtj|jd�|jtj|jd�|j�|j�|j�}|j�}trp|j|tj	�|j|d�n|j|tj	�|j|tj	�dS)Ng{�G�z�?)
rr<r6r]rBrIrr8rErJ)r0�p1�p2Zret1Zret2r1r1r2�test_wait_non_children�s
z"TestProcess.test_wait_non_childrencCs�t�}tj|j�}|jtj|jd�|j�tj�d}x:y|jd�}Wn$tjk
rltj�|krh�Yq:XPq:Wt	r�|j
|tj�n|j
|tj
�|j|j��dS)Nr�)rr6r7r9r<r]rBrA�timerr8rErFrJrCrZ)r0r?r>Zstop_atr^r1r1r2�test_wait_timeout_0�s zTestProcess.test_wait_timeout_0c
Cs�tj�}|jdd�|jdd�xRtd�D]F}|jdd�}|j|t�|j|d�tsd|j|d�q*|j|d�q*W|j	t
��|jdd�WdQRXdS)Ng����MbP?)Zinterval�dggY@rXrY)r6r7�cpu_percent�range�assertIsInstance�float�assertGreaterEqualr�assertLessEqualr<rU)r0r>�xZpercentr1r1r2�test_cpu_percent�szTestProcess.test_cpu_percentc	Cs4tjddd��}tj�j�|js&t�WdQRXdS)Nzpsutil.cpu_count)Zreturn_value)rrOr6r7rg�called�AssertionError)r0�mr1r1r2�test_cpu_percent_numcpus_none�sz)TestProcess.test_cpu_percent_numcpus_nonecCsxtj�j�}|jdks(|jdks(t|��|jdks:t|��|jdksLt|��x&|jD]}t	j
dt	jt||���qTWdS)Ngz%H:%M:%S)
r6r7�	cpu_times�user�systemrp�
children_user�children_system�_fieldsrd�strftime�	localtime�getattr)r0�timesr\r1r1r2�test_cpu_times�szTestProcess.test_cpu_timescCs�tj�j�dd�\}}tj�dd�\}}t||g�t||g�dkrZ|jd||f�t||g�t||g�dkr�|jd||f�dS)Nrcg�������?zexpected: %s, found: %s)r6r7rsr:r|�max�min�fail)r0�	user_timeZkernel_time�utimeZktimer1r1r2�test_cpu_times_2szTestProcess.test_cpu_times_2z
not supportedcCsPtj�}|j�}|j|d�tj�dkr4|j|d�|j|j�ttj���dS)NrrX)r6r7Zcpu_numrk�	cpu_countr8r[rh)r0r>Znumr1r1r2�test_cpu_numszTestProcess.test_cpu_numcCsdt�}tj�}tj|j�}|j�}t||�}|dkrJ|jd|||f�tjdtj	|j���dS)Nrcz'expected: %s, found: %s, difference: %sz%Y %m %d %H:%M:%S)
rrdr6r7r9�create_time�absr�ryrz)r0r?Znowr>r��
differencer1r1r2�test_create_timeszTestProcess.test_create_timez
POSIX onlyznot reliable on TRAVIScCsLtj�j�}tjj�s tjj�r>tjj	t
d��}|j||�n
|j|�dS)N�tty)
r6r7�terminal�sys�stdin�isatty�stdoutr:�path�realpathr%r8�assertIsNone)r0r�r�r1r1r2�
test_terminal-s
zTestProcess.test_terminal)Zonly_ifcCs�tj�}|j�}ttd��}|j�WdQRX|j�}tr�tr�|j|j	|j	�|j
|j|j�tr�|j|j
|j
�|j
|j|j�n |j|j|j�|j|j|j�|j�}tjtd��.}tr�|jtddd��n|jdd�WdQRX|j�}|j|j|j�|j|j|j�|j|j	|j	�|j|j|j�t�r^|j|j|j�|j|j
|j
�xJtt|��D]:}t�r�|dk�r��ql|j||d�|j||d��qlWdS)N�rb)�prefixrmi@B�asciircr)r6r7Zio_counters�openr �readrr�
assertGreaterZ
read_countr8Zwrite_countrZ
read_charsZwrite_charsrkZ
read_bytesZwrite_bytes�tempfileZ
TemporaryFiler(r�write�bytesrh�len)r0r>Zio1�fZio2�ir1r1r2�test_io_counters7s>zTestProcess.test_io_countersc	Cs�t�r<ddlm}m}m}m}|j|d�|j|d�|j|d�|j|d�tj�}z�|jd�|j�\}}t	dk	r�|j
|t	j�|j|d�|j|d�|jd�|j�\}}|j|d�|j|d�|jdd�|j�\}}|j|d�|j|d�|jdd�|j�\}}|j|d�|j|d�Wd|j|�XnZtj�}|j�}|j
|t�z0d}||k�rld}|j|�|j|j�|�Wd|j|�XdS)Nr)�IOPRIO_CLASS_NONE�IOPRIO_CLASS_RT�IOPRIO_CLASS_BE�IOPRIO_CLASS_IDLErXrc���)
rr6r�r�r�r�r8r7�ionicerri�IntEnum�int)	r0r�r�r�r�r>Zioclass�value�originalr1r1r2�test_ionicecsJ



zTestProcess.test_ionicecCs�t�}tj|j�}tr�|jt|jdd�|jt|jdd�|jt|jd�|jt|jdd�|j	td|jtj
d�|j	td|jtjd�|j	td|jdd	�n"|jt|jd
�|jt|jdd�dS)Nrc�
rXr��fooz*can't specify value with IOPRIO_CLASS_NONEz*can't specify value with IOPRIO_CLASS_IDLEz$'ioclass' argument must be specified)r�r�rY)rr6r7r9rr<rUr��	TypeErrorZassertRaisesRegexr�r�)r0r?r>r1r1r2�test_ionice_errs�s$zTestProcess.test_ionice_errscCs�ddl}tjtj��}dd�tt�D�}|s4t|��x�|D]�}tt|�}|j|d�|t|�kr�|j	|t||��t
rxq:|j	|j|�|j|��q:|j|�}|j	t
|�d�|j|dd�|j|dd�q:WdS)NrcSsg|]}|jd�r|�qS)ZRLIMIT)�
startswith)�.0rmr1r1r2�
<listcomp>�sz/TestProcess.test_rlimit_get.<locals>.<listcomp>rcrXrYrY)�resourcer6r7r:r;�dirrpr{rkr8r�rlimitZ	getrlimitr�)r0r�r>�namesr\r��retr1r1r2�test_rlimit_get�s 


zTestProcess.test_rlimit_getcCs�t�}tj|j�}|jtjd�|j|jtj�d�|jt��tj	jd�jd�WdQRX|jt��|jtjd�WdQRXdS)NrWr)rWrW)rWrW)rWrWrW)
rr6r7r9r��
RLIMIT_NOFILEr8r<rUZ_psplatform)r0r?r>r1r1r2�test_rlimit_set�szTestProcess.test_rlimit_setc Cs�tj�}|jtj�\}}z�|jtjd|f�ttd��}|jdd�WdQRX|jt��*}ttd��}|jdd�WdQRXWdQRX|j	t
r�|jjn|jdtj
�Wd|jtj||f�|j	|jtj�||f�XdS)Ni�wb�Xir)r6r7r��RLIMIT_FSIZEr�r)r�r<�IOErrorr8rZ	exceptionrQZEFBIG)r0r>�soft�hardr��excr1r1r2�test_rlimit�s"zTestProcess.test_rlimitcCs�tj�}|jtj�\}}zN|jtjd|f�|jtjtj|f�ttd��}|jdd�WdQRXWd|jtj||f�|j|jtj�||f�XdS)Nir�r�i)	r6r7r�r��
RLIM_INFINITYr�r)r�r8)r0r>r�r�r�r1r1r2�test_rlimit_infinity�sz TestProcess.test_rlimit_infinitycCs<tj�}|jtj�\}}|jtj|�|jtj||f�dS)N)r6r7r�r�r8r�)r0r>r�r�r1r1r2�test_rlimit_infinity_value�sz&TestProcess.test_rlimit_infinity_valuecCsrtj�}tr<y|j�}WqDtjk
r8tjd��YqDXn|j�}t��|j�}|j||d�WdQRXdS)Nz$on OpenBSD this requires root accessrX)	r6r7r�num_threadsrSr,�SkipTestr*r8)r0r>�step1�step2r1r1r2�test_num_threads�szTestProcess.test_num_threadszWINDOWS onlycCstj�}|j|j�d�dS)Nr)r6r7r�Znum_handles)r0r>r1r1r2�test_num_handlesszTestProcess.test_num_handlescCs�tj�}tr<y|j�}WqDtjk
r8tjd��YqDXn|j�}t��~|j�}|jt	|�t	|�d�t
r�|j|djtj
��|d}|j|j|d�|j|j|d�|j|j|d�WdQRXdS)Nz$on OpenBSD this requires root accessrXrrc)r6r7r�threadsrSr,r�r*r8r�r�idr:r;r��system_time)r0r>r�r�Zathreadr1r1r2�test_threadss zTestProcess.test_threadsc
Cs�t�}tj|j�}trDy|j�Wn tjk
rBtjd��YnX|j	|j
�jtdd�|j�D��dd�|j	|j
�j
tdd�|j�D��dd�dS)Nz$on OpenBSD this requires root accesscSsg|]
}|j�qSr1)r�)r�rmr1r1r2r�7sz.TestProcess.test_threads_2.<locals>.<listcomp>g�������?)ZdeltacSsg|]
}|j�qSr1)r�)r�rmr1r1r2r�:s)rr6r7r9rr�rSr,r�ZassertAlmostEqualrsrt�sumru)r0r?r>r1r1r2�test_threads_2)szTestProcess.test_threads_2cCs�tj�}|j�dd�\}}|j�}|j|d�|j|d�dgd}|j�dd�\}}|j�}|j||�|j||�|j||�~tr�|j�}	|j|	j|	j	�|j|	j
|	j�|j�}	x |	jD]}
|jt
|	|
�d�q�WdS)Nrcri`�)r6r7Zmemory_info�memory_percentr�rkr
r8ZrssZwset�vmsZpagefilerxr{)r0r>Zrss1Zvms1Zpercent1ZmemarrZrss2Zvms2Zpercent2�memr\r1r1r2�test_memory_info<s&
zTestProcess.test_memory_infocCs�tj�j}tj�j�}xB|jD]8}t||�}|j|d||fd�|j|||||fd�qWt	sft
sftrt|j|jd�t	r�|j|j
d�|j|jd�dS)Nr)�msg)r6Zvirtual_memory�totalr7Zmemory_full_inforxr{rkrlrr
r�ussZpssZswap)r0r�r�r\r�r1r1r2�test_memory_full_infoZs

z!TestProcess.test_memory_full_infoc
Cs�tj�}|j�}dd�|D�}|jt|�tt|���|jdd�}x�|D]�}|jjd�sHtjj	|j�spt
|j��tr�y*tjj|j�s�tjj
|j�s�t
|j��WnHt
k
r�ts��n,td��}|j�}WdQRXd|j|kr�YnXqHdtjj|j�krHtjj|j�sHt
|j��qHWxv|D]n}xf|jD]\}t||�}	|d	k�rH�q*n<|d
k�rb|	�s�t
|	��n"|j|	ttf�|	dk�s*t
|	���q*W�qWdS)NcSsg|]}|�qSr1r1)r�rmr1r1r2r�ksz0TestProcess.test_memory_maps.<locals>.<listcomp>F)Zgrouped�[z/proc/self/smapsz%s (deleted)Z64r��addr�permsr)r�r�)r6r7�memory_mapsr8r��setr�r�r:�isabsrpr�exists�islinkrr�r��basenamerxr{rir�r)
r0r>�maps�pathsZext_maps�ntr��dataZfnamer�r1r1r2�test_memory_mapsgs<






zTestProcess.test_memory_mapsc
sHt��8}dd���fdd�tj�j�D�}|j�|�|�WdQRXdS)NcSstjjtjj|��S)N)r:r�r��normcase)r>r1r1r2�normpath�sz8TestProcess.test_memory_maps_lists_lib.<locals>.normpathcsg|]}�|j��qSr1)r�)r�rm)r�r1r2r��sz:TestProcess.test_memory_maps_lists_lib.<locals>.<listcomp>)rr6r7r�r[)r0r�Zlibpathsr1)r�r2�test_memory_maps_lists_lib�s

z&TestProcess.test_memory_maps_lists_libcCs�tj�}|j�}d|ko"dkns0t|��|jdd�}d|koNdkns\t|��d|kondkns|t|��|jt|jdd�ts�ts�tr�|jdd�}d|ko�dkns�t|��d|ko�dkns�t|��dS)Nrrfr�)Zmemtypez?!?r�)	r6r7r�rpr<rUrrr
)r0r>r�r1r1r2�test_memory_percent�s    zTestProcess.test_memory_percentcCsZt�}tj|j�}|j�st�|j�s*t�|j�|j�|j�sHt�|j�sVt�dS)N)rr6r7r9rZrprArB)r0r?r>r1r1r2�test_is_running�szTestProcess.test_is_runningcCs�t�}tj|j�j�}y|j|t�Wn�tk
r�trht	|�t	t�krht
jj}|j||�|t��nNdt
jdt
jdf}y |j|j|d�tj|d��Wntk
r�YnXYnXt|ddg�}|j|d�dS)Nz%s.%srrXrLz-czimport os; print('hey')Zhey)rr6r7r9�exer8r rpr
r�r:r�r�r��version_info�replacer%)r0r?r�r�Zver�outr1r1r2�test_exe�s zTestProcess.test_execCs�tddg}t|�}y(|jdjtj|j�j��dj|��Wn@tk
rzt	sVt
sVtrt|jtj|j�j�dt�n�YnXdS)Nz-czimport time; time.sleep(60)� r)r rr8�joinr6r7r9�cmdlinerprrr)r0r�r?r1r1r2�test_cmdline�s
zTestProcess.test_cmdlinecCsPtt�}tj|j�j�j�}tjj	tjj
tj��j�}|j
|�sLt||f��dS)N)rr r6r7r9r\�lowerr:r�r�r�r��
executabler�rp)r0r?r\Zpyexer1r1r2�	test_name�szTestProcess.test_namezbroken on SUNOSz
broken on AIXcs��fdd�}td�t��|j|��ddddddg}t|�}tj|j�}trZt|j�|j	|j
�|�|j	|j�tj
j���|j	tj
j|j��tj
j���dS)	Ncs&yt��Wntk
r YnXdS)N)r$rPr1)�
funky_pathr1r2�rm�sz.TestProcess.test_prog_w_funky_name.<locals>.rmz	foo bar )z-cz9import time; [time.sleep(0.01) for x in range(3000)];arg1Zarg2rLZarg3)r)r�
addCleanuprr6r7r9r+r-r8r�r\r:r�r�r�r�)r0r�r�r?r>r1)r�r2�test_prog_w_funky_name�s	

z"TestProcess.test_prog_w_funky_namecCsXtj�}|j�\}}}|j|tj��|j|tj��ttd�rT|jtj�|j��dS)N�	getresuid)	r6r7�uidsr8r:�getuid�geteuid�hasattrr�)r0r>�real�	effective�savedr1r1r2�	test_uidss
zTestProcess.test_uidscCsXtj�}|j�\}}}|j|tj��|j|tj��ttd�rT|jtj�|j��dS)Nr�)	r6r7�gidsr8r:�getgid�getegidr�	getresgid)r0r>rrrr1r1r2�	test_gidss
zTestProcess.test_gidscCs�tj�}|jt|jd�tr�z||j�}tjdkr@|j|t	j
�n|j|t�|j|tj
�|jtj�|j|j�tj�|jtj
�|j|j�tj
�Wd|jtj
�Xn�|j�}z�y�ttd�r�|jtjtjtj��|j��|jd�|j|j�d�ttd��r"|jtjtjtj��|j��t�sB|jd�|j|j�d�Wntjk
�r\YnXWdy|j|�Wntjk
�r�YnXXdS)N�strr�r��getpriorityrXr)r�r�)r6r7r<r��nicer
r�r�rirr�r�r8�NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSrr:r�PRIO_PROCESSr;rrS)r0r>ZinitZ
first_nicer1r1r2�	test_nice"sB




zTestProcess.test_nicecCstj�}|j|j�tj�dS)N)r6r7r8�statusZSTATUS_RUNNING)r0r>r1r1r2�test_statusKszTestProcess.test_statuscCsnt�}tj|j�}|j�}trZ|jd�\}}|j|tj	��dt
jkrj|j|t
jd�n|j|tj	��dS)N�\Z
USERDOMAIN)rr6r7r9�usernamer
�splitr8�getpassZgetuserr:�environ)r0r?r>rZdomainr1r1r2�
test_usernameOs
zTestProcess.test_usernamecCs*t�}tj|j�}|j|j�tj��dS)N)rr6r7r9r8�cwdr:�getcwd)r0r?r>r1r1r2�test_cwd[szTestProcess.test_cwdcCs.tddg}t|�}tj|j�}t|jd�dS)Nz-cz/import os, time; os.chdir('..'); time.sleep(60)z#ret == os.path.dirname(os.getcwd()))r rr6r7r9rr)r0�cmdr?r>r1r1r2�
test_cwd_2`s
zTestProcess.test_cwd_2cCs�tj�}|j�}|st|��|j|j|�ttd�rL|j|ttj	|j
���|jt|�tt|���tt
ttjdd����}xzts�|n|D]j}|j|g�|j|j�|g�ttd�r�|j|j�ttj	|j
���t|d�r�|j|j�d|j��q�W|jg�t�r |j|j�|jj��n|j|j�|�ttd��rX|j|j�ttj	|j
���|jt|jd�|j|�|jt|��|jt|��dS)N�sched_getaffinityT)�percpu�num_cpurrX)r6r7�cpu_affinityrpr�rr:r8�listr r9r�r�rhrgr+r"r�_procZ_get_eligible_cpusr<r��tuple)r0r>�initialZall_cpus�nr1r1r2�test_cpu_affinitygs6






zTestProcess.test_cpu_affinitycCszt�}tj|j�}ttjdd��dg}|jt|j|�|jt|jt	dd��|jt
|jddg�|jt|jdd	g�dS)
NT)r!r�i'i�*r�1rXrY)rr6r7r9r�rsr<rUr#rhr�)r0r?r>Zinvalid_cpur1r1r2�test_cpu_affinity_errs�sz"TestProcess.test_cpu_affinity_errscCs�tj�}|j�}|st|��|j|j|�g}xBtdt|�d�D],}x&tj||�D]}|rT|j	t
|��qTWqBWx&|D]}|j|�|j|j�|�qxWdS)NrrX)r6r7r#rpr�rhr��	itertools�combinations�appendr$r8)r0r>r'Zcombos�lZsubsetZcombor1r1r2�"test_cpu_affinity_all_combinations�s

z.TestProcess.test_cpu_affinity_all_combinationsz
broken on BSDzunreliable on APPVEYORc	CsRtj�}|j�}|jt|k�ttd��n}|jdd�|j�t|jdt	|��}x<|D]"}|j
tkrZtrz|j|j
d�PqZW|jdt|��WdQRXx"|D]}tj
j|j
�s�t|��q�Wdt}ttd|g�}tj|j�}xDtd�D],}d	d
�|j�D�}t|k�rPtjd�q�W|jt|�x$|D]}tj
j|��s.t|���q.WdS)Nr��xizlen(ret) != %izno file found; files=%sz2import time; f = open(r'%s', 'r'); time.sleep(60);z-crfcSsg|]
}|j�qSr1)r�)r�rmr1r1r2r��sz/TestProcess.test_open_files.<locals>.<listcomp>g{�G�z�?)r6r7�
open_filesrCr)r�r��flushrr�r�rr8Zpositionr��reprr:�isfilerprr r9rhrd�sleepr[)	r0r>�filesr��filer�r?rm�	filenamesr1r1r2�test_open_files�s4




zTestProcess.test_open_filescCs�ttd���}tj�}xB|j�D] }|j|jks<|j|j�krPqW|j	dt
|j���|j|j|j�tr||j|jd�n|j|j|j��|j�d}|j|d|j�|j|d|j�|j
|j|j��WdQRXdS)N�wzno file found; files=%srXrrY)r�r)r6r7r2r�r\�fd�filenor�r4r8r
�assertNotIn)r0Zfileobjr>r8Zntupler1r1r2�test_open_files_2�szTestProcess.test_open_files_2cCs�tj�}|j�}ttd�}|j|j�|j|j�|d�tj�}|j|j�|j|j�|d�|j�|j�|j|j�|�dS)Nr;rXrc)	r6r7Znum_fdsr�r)r��closer8�socket)r0r>�startr8Zsockr1r1r2�test_num_fds�s
zTestProcess.test_num_fdsz not reliable on OPENBSD & NETBSDcCsLtj�}t|j��}x(td�D]}t|j��}||krdSqW|jd�dS)Ni �z7num ctx switches still the same after 50.000 iterations)r6r7r�Znum_ctx_switchesrhr�)r0r>Zbeforerm�afterr1r1r2�test_num_ctx_switches�sz!TestProcess.test_num_ctx_switchescCs�ttd�r"|jtj�j�tj��tj�}t�}tj|j	�}|j|j�|�t
dd�tr^dSx2tj�D]&}|j	|j	krzqh|j
|j�||d�qhWdS)N�getppidT)�	recursive)r�)rr:r8r6r7�ppidrFr;rr9r!r
�process_iter�assertNotEqual)r0�this_parentr?r>r1r1r2�	test_ppids

zTestProcess.test_ppidcCs0tj�}t�}tj|j�}|j|j�j|�dS)N)r:r;rr6r7r9r8�parent)r0rKr?r>r1r1r2�test_parentszTestProcess.test_parentc	CsFt�}tj|j�}tjdtjdd�d��|j|j��WdQRXdS)Nzpsutil.Processrr�)rM)	rr6r7r9rrOrRr�rM)r0r?r>r1r1r2�test_parent_disappeared s
z#TestProcess.test_parent_disappearedcCs�tj�}|j|j�g�|j|jdd�g�tdd�}|j�}|jdd�}xL||fD]@}|jt|�d�|j|dj|j�|j|dj�tj	��qTWdS)NT)rGr)Z
creationflagsrX)
r6r7r8�childrenrr�r9rHr:r;)r0r>r?Z	children1Z	children2rPr1r1r2�
test_children(s
zTestProcess.test_childrencCsdt�\}}tj�}|j|j�|g�|j|jdd�||g�|j�|j�|j|jdd�g�dS)NT)rG)rr6r7r8rPrIrB)r0r`rar>r1r1r2�test_children_recursive7s
z#TestProcess.test_children_recursivec
Cs�tjt�}x@tj�D]4}y||j�d7<Wqtjk
rFYqXqWt|j�dd�d�dd}tj	|�}y|j
dd�}Wntjk
r�YnX|jt
|�t
t|���dS)	NrXcSs|dS)NrXr1)rmr1r1r2�<lambda>Msz6TestProcess.test_children_duplicates.<locals>.<lambda>)�keyrT)rGrY)�collections�defaultdictr�r6rIrH�Error�sorted�itemsr7rPrSr8r�r�)r0�tabler>r9�cr1r1r2�test_children_duplicatesDs


z$TestProcess.test_children_duplicatescCsdt�}tj|j�}|j�x*td�D]}|j�tjkr8Ptj	d�q$W|j
�|j|j�tj�dS)Nrfg{�G�z�?)rr6r7r9�suspendrhrZSTATUS_STOPPEDrdr6�resumerJ)r0r?r>rmr1r1r2�test_suspend_resumeVszTestProcess.test_suspend_resumecCs$|jttjd�|jttjd�dS)Nr*rXrY)r<r�r6r7rU)r0r1r1r2�test_invalid_pidaszTestProcess.test_invalid_pidc;Cs�tj�}|jddgd�}|jt|j��ddg�tjttj���}|jdgdd�}t|dt	�sp|j|dd�t
jddtjd	��"|j|jd
gdd�d
di�WdQRXt
jddtj
|jd�d	��|jtj
|jd
gd�WdQRXt
jddtj|jd�d	��"|j|jd
gdd�d
di�WdQRXt
jddtd	��F|j�}|jd
t	|j���|jt��|jd
gd�WdQRXWdQRX|jt��|jd�WdQRX|jt��|jdg�WdQRX|jt��|jddg�WdQRXdS)
Nr�r\)�attrsZconnectionsr�)raZad_valuezpsutil.Process.niceT)ZcreaterMrrXZbar)r6r7�as_dictr8rX�keysrrT�
isinstancer$rrOrSrRr9r<�
ZombieProcess�NotImplementedErrorr>r�rU)r0r>�dr1r1r2�test_as_dictes>""
"zTestProcess.test_as_dictcCs�tjd��@}tj�}|j��|j�|j�WdQRX|j|jd�WdQRXtjd��}|j�|j�WdQRX|j|jd�dS)Nz$psutil._psplatform.Process.cpu_timesrXrc)rrOr6r7�oneshotrsr8�
call_count)r0rqr>r1r1r2�test_oneshot�s
zTestProcess.test_oneshotc&Cs�tjd���}tjd��r}tj�}|j��:|j�|j�|j��|j�|j�WdQRXWdQRX|j|jd�|j|jd�WdQRXWdQRXtjd��}|j�|j�WdQRX|j|jd�dS)Nz$psutil._psplatform.Process.cpu_timesz(psutil._psplatform.Process.oneshot_enterrXrc)rrOr6r7rirsr8rj)r0�m1�m2r>rqr1r1r2�test_oneshot_twice�s

"zTestProcess.test_oneshot_twicec
Cs�t�}tj|j�}|j�|j�tr8ttjd|j�|j	|j
��ddddddg}trjtrj|j
d��xTt|�D�]F}|jd	�sv||kr�qvy�t||�}|d
kr�tr�|d�}n
|tj�}np|dkr�|�}|d
�}nX|dkr�|tj�}|tjd�}n8|dk�r|�}|dg�}n|dk�r(|tj�}n|�}Wnztjk
�rV|jd|�Yqvtjk
�rlYqvtjk
�r�t�r�|dk�r�n�Yqvtk
�r�YqvX|jd||f�qvWdS)Nz
%s not in retr9rZrBr�riZmemory_info_exr��_rrXr�rcrWr#rrNz/ZombieProcess for %r was not supposed to happenr�r�z4NoSuchProcess exception not raised for %r, retval=%s)rWrW)r�r�)rr6r7r9rIrBr
rrTrCrZrrr.r�r�r{rrr�rErJrer�rRrSrrf)r0r?r>Zexcluded_namesr\�methr�r1r1r2�test_halfway_terminated_process�s^









z+TestProcess.test_halfway_terminated_processcCs�dd�}t�}|jtdd�tj|�}|j|j�tj�|j|j	��|j
�||j�}|dk	rl|j|g�t|d�r�||j
tj�||j
tjd�||j�t|d�r�y||jdg�Wn:tk
r�}ztr�tr�d	t|�kr�n�WYdd}~XnX||jd�t|d
��r0t�r$||jdd�n||jd�t|d��rL||j
tjd�||j�||j�||j�||j�|jtj|��t�r�t�r�|j|tj��|j|dd
�tj�D��it_|j|dd
�tj�D��dS)Nc_s,y
|||�Stjtjfk
r&YnXdS)N)r6rerS)Zfun�args�kwargsr1r1r2�succeed_or_zombie_p_exc�s
z@TestProcess.test_zombie_process.<locals>.succeed_or_zombie_p_excT)rGr�rWr#rznot eligibler�rccSsg|]
}|j�qSr1)r9)r�rmr1r1r2r�9sz3TestProcess.test_zombie_process.<locals>.<listcomp>cSsg|]
}|j�qSr1)r9)r�rmr1r1r2r�;s)rWrW)rWrW) rr�r!r6r7r8r�
STATUS_ZOMBIE�
assertTruerZrbr]rr�r�rMr#rUr+rr
rr�r^rIrArDrr[rTrIZ_pmap)r0rtZzpidZzprocr��errr1r1r2�test_zombie_process�sP










zTestProcess.test_zombie_processc	CsBtj�}tjdtjd�d��}|j�s*t�|js4t�WdQRXdS)Nzpsutil.Processr)rM)r6r7rrOrerZrpro)r0r>rqr1r1r2�$test_zombie_process_is_running_w_exc=s
z0TestProcess.test_zombie_process_is_running_w_excc
CsHtj�}tjdtjd�d��"}|j|j�tj�|js:t	�WdQRXdS)Nz!psutil._psplatform.Process.statusr)rM)
r6r7rrOrer8rrurorp)r0r>rqr1r1r2� test_zombie_process_status_w_excGs
z,TestProcess.test_zombie_process_status_w_exccCs:dtj�kr"|jtjtjd�dStjd�}x�tjD]�}|dkrBq4t||�}y
|�}Wntjk
rlYq4X|d
kr�|j|j	d�q4|dkr�t
r�|j|j�d�q�tr�|j|j�d�q4|dkr4|s4t
|��q4Wt|d	��ry|jtj�Wntjk
�rYnX|j�t�s6|jdtj��|jtjd��dS)Nrr9rrr�rootzNT AUTHORITY\SYSTEMr\r�)rr)r6rTr<rRr7Z_as_dict_attrnamesr{rSr8rrrr
rprr�r�rbrr[rvrD)r0r>r\rpr�r1r1r2�
test_pid_0Qs<


zTestProcess.test_pid_0cCs@dd�}d|_tj�}||j��}|tjj��}|j||�dS)NcSsb|jdd�|jdd�|jdd�trL|jdd�|jdd�|jdd�tdd�|j�D��S)	NZPSUTIL_TESTINGZPLAT�HOMEZ__CF_USER_TEXT_ENCODINGZVERSIONER_PYTHON_PREFER_32_BITZVERSIONER_PYTHON_VERSIONcSs$g|]\}}|jd�|jd�f�qS)z
)�rstrip)r��k�vr1r1r2r��sz@TestProcess.test_environ.<locals>.clean_dict.<locals>.<listcomp>)�popr�dictrY)rgr1r1r2�
clean_dictzsz,TestProcess.test_environ.<locals>.clean_dict)ZmaxDiffr6r7rr:�copyr8)r0r�r>Zd1Zd2r1r1r2�test_environxszTestProcess.test_environcCs�tjd�}t}t||d�|jt|�t|gtjtjd�}t	j
|j�}t|j�|j
|j��|j|jj�d�|j|j�ddd��|j�|j|jd�dS)	Na�
            #include <unistd.h>
            #include <fcntl.h>
            char * const argv[] = {"cat", 0};
            char * const envp[] = {"A=1", "X", "C=3", 0};
            int main(void) {
                /* Close stderr on exec so parent can wait for the execve to
                 * finish. */
                if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0)
                    return 0;
                return execve("/bin/cat", argv, envp);
            }
            )Zc_code)r��stderr�r*�3)�A�Cr)�textwrap�dedentr)rr�r$r�
subprocess�PIPEr6r7r9r-rvrZr8r�r�r�communicate�
returncode)r0r^r�r?r>r1r1r2�test_weird_environ�s

zTestProcess.test_weird_environN)d�__name__�
__module__�__qualname__�__doc__r3r4r@rHrKrVr_rbrernrrr}r�r,ZskipIfrr�r�rr+r�rr'rr�rr
rr.r�r�rr�r�r�r�r�r�r�rr�r"r&rr�r�r�rr�r�r�r�r�r�r�r	rr�rrrrrrrrr)r+r0rr
r:r?rCrrrErLrNrOrQrRr\r_r`rhrkrnrqrxryrzr|rr�r�r1r1r1r2r/Ks�

 /	
		+ ."

)



)*

%


.
@I

'r/c@sReZdZdZeed�r&ej�Zej�Z	dd�Z
dd�Zdd�Zd	d
�Z
dd�Zd
S)�LimitedUserTestCasez�Repeat the previous tests by using a limited user.
        Executed only on UNIX and only if the user who run the test script
        is root.
        rcs\tj|f|�|�xDdd�t|�D�D].}t||���fdd�}t||tj||��q&WdS)NcSsg|]}|jd�r|�qS)Ztest)r�)r�rmr1r1r2r��sz0LimitedUserTestCase.__init__.<locals>.<listcomp>cs&y
��Wntjk
r YnXdS)N)r6rS)r0)rpr1r2�test_�s
z+LimitedUserTestCase.__init__.<locals>.test_)r/�__init__r�r{�setattr�types�
MethodType)r0rrrs�attrr�r1)rpr2r��s

zLimitedUserTestCase.__init__cCs*tt�tj|�tjd�tjd�dS)Ni�)r$r)r/r3r:�setegid�seteuid)r0r1r1r2r3�s

zLimitedUserTestCase.setUpcCs&tj|j�tj|j�tj|�dS)N)r:r��PROCESS_UIDr��PROCESS_GIDr/r4)r0r1r1r2r4�szLimitedUserTestCase.tearDowncCs8ytj�jd�Wntjk
r(YnX|jd�dS)NrXzexception not raisedrY)r6r7rrSr�)r0r1r1r2r�s
zLimitedUserTestCase.test_nicecCsdS)Nr1)r0r1r1r2rx�sz'LimitedUserTestCase.test_zombie_processN)r�r�r�r�rr:rr�r	r�r�r3r4rrxr1r1r1r2r��s
r�c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�	TestPopenzTests for psutil.Popen class.cCs
t�dS)N)r!)r0r1r1r2r4�szTestPopen.tearDowncCsjtddg}tj|tjtjd��B}|j�|j�|j|jt	|��|j
tt|d�|j
�WdQRXdS)Nz-czimport time; time.sleep(60);)r�r�r�)r r6�Popenr�r�r\rsr�rvr�r<r=r{rI)r0r�procr1r1r2�	test_misc�s

zTestPopen.test_miscc
Csftjtdgtjtjtjd��}|j�WdQRX|jjs<t�|j	jsHt�|j
jsTt�|j|jd�dS)Nz-V)r�r�r�r)
r6r�r r�r�r�r��closedrpr�r�r8r�)r0r�r1r1r2�test_ctx_manager�s
zTestPopen.test_ctx_managercCs�tddg}tj|tjtjd���}|j�|j�|jtj|j�|jtj|j	�|jtj|j
tj�t
r�tjdkr�|jtj|j
tj�|jtj|j
tj�WdQRXdS)Nz-czimport time; time.sleep(60);)r�r�rcr�)rcr�)r r6r�r�r�rIrBr<rRrArNrErJr
r�r�ZCTRL_C_EVENTZCTRL_BREAK_EVENT)r0rr�r1r1r2�test_kill_terminates

zTestPopen.test_kill_terminateN)r�r�r�r�r4r�r�r�r1r1r1r2r��s
r��__main__)Er�rUrQrr,r:rErAr�r�r�r�rdr�r6rrrrrrrr	r
Zpsutil._compatrrZpsutil.testsr
rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.ZTestCaser/rr�r�r��__file__r1r1r1r2�<module>s�q53
tests/__pycache__/test_bsd.cpython-36.opt-1.pyc000064400000042355150466730550015336 0ustar003

��JZcE�@s�dZddlZddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddl
mZddl
mZdd	l
m
Z
dd
l
mZddl
mZddl
mZdd
l
mZddl
mZddl
mZer�ejd�Zej�dkr�ed�Zq�dZndZdd�Zdd�Zejed�Gdd�dej��Zejed�Gdd�dej��Zeje	d�Gdd�dej��Zejed�Gd d!�d!ej��Ze d"k�r�ee!�dS)#z$Tests specific to all BSD platforms.�N)�BSD)�FREEBSD)�NETBSD)�OPENBSD)�get_test_subprocess)�HAS_BATTERY)�MEMORY_TOLERANCE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�unittest)�which�SC_PAGE_SIZE�museFcCshtd|�}tr(||jd�dd�}nts0trF||jd�dd�}yt|�Stk
rb|SXdS)zmExpects a sysctl command with an argument and parse the result
    returning only the value of interest.
    zsysctl z: �N�=�)rr�findrr�int�
ValueError)�cmdline�result�r� /usr/lib64/python3.6/test_bsd.py�sysctl+srcCs@td�}x&|jd�D]}|j|�rPqWtd��t|j�d�S)z+Thin wrapper around 'muse' cmdline utility.r�
zline not foundr)r�split�
startswithrr)Zfield�out�linerrrr:s
zBSD onlyc@s�eZdZdZedd��Zedd��Zeje	d�dd��Z
d	d
�Zejed�d�d
d��Z
ejed�d�dd��Zdd�ZdS)�BSDSpecificTestCasez)Generic tests common to all BSD variants.cCst�j|_dS)N)r�pid)�clsrrr�
setUpClassNszBSDSpecificTestCase.setUpClasscCs
t�dS)N)r	)r#rrr�
tearDownClassRsz!BSDSpecificTestCase.tearDownClassz -o lstart doesn't work on NETBSDcCsPtd|j�}|jdd�j�}tj|j�j�}tjdtj	|��}|j
||�dS)Nzps -o lstart -p %sZSTARTED�z%a %b %e %H:%M:%S %Y)rr"�replace�strip�psutil�ProcessZcreate_time�timeZstrftimeZ	localtime�assertEqual)�self�outputZstart_psZstart_psutilrrr�test_process_create_timeVsz,BSDSpecificTestCase.test_process_create_timecCs�dd�}x�tjdd�D]�}tj|j�}||j�\}}}}|j|j|�|j|j|�t|j|�d	krz|j	d|j|f�t|j
|�dkr|j	d|j
|f�qWdS)NcSs�td|�j�}|jd�}|jd�|jd�}|j�dd�\}}}}|dkrRd}t|�d}t|�d}t|�d}||||fS)Nz
df -k "%s"rr�Znoner&i)rr(r�popr)�pathr�linesr �dev�total�used�freerrr�dfbs


z*BSDSpecificTestCase.test_disks.<locals>.dfF)�all�
izpsutil=%s, df=%si(i�i(i�)r)Zdisk_partitionsZ
disk_usageZ
mountpointr,Zdevicer5�absr7Zfailr6)r-r8�partZusager4r5r6r7rrr�
test_disks_s
zBSDSpecificTestCase.test_disksrzsysctl cmd not availablecCs td�}|jtjdd�|�dS)Nzhw.ncpuT)Zlogical)rr,r)�	cpu_count)r-�systrrr�test_cpu_count_logicalzsz*BSDSpecificTestCase.test_cpu_count_logicalcCstd�}|j|tj�j�dS)Nz
hw.physmem)rr,r)�virtual_memoryr5)r-�numrrr�test_virtual_memory_totalsz-BSDSpecificTestCase.test_virtual_memory_totalcCs�xztj�j�D]j\}}ytd|�}Wntk
r:YqX|j|jd|k|d�d|kr|j|jtt	j
d|�d��qWdS)Nzifconfig %sZRUNNING)�msg�mtuz	mtu (\d+)r)r)Znet_if_stats�itemsr�RuntimeErrorr,ZisuprEr�re�findall)r-�nameZstatsrrrr�test_net_if_stats�sz%BSDSpecificTestCase.test_net_if_statsN)�__name__�
__module__�__qualname__�__doc__�classmethodr$r%r
�skipIfrr/r=rr@rCrKrrrrr!Js	r!zFREEBSD onlyc@s�eZdZedd��Zedd��Ze�dd��Zdd�Zd	d
�Z	dd�Z
e�d
d��Ze�dd��Ze�dd��Z
e�dd��Ze�dd��Ze�dd��Ze�dd��Ze�dd��Zejed�dd��Zejed�e�d d!���Zejed�e�d"d#���Zejed�e�d$d%���Zejed�e�d&d'���Zejed�e�d(d)���Zejed�e�d*d+���Zd,d-�Zd.d/�Zd0d1�Zd2d3�Z d4d5�Z!eje"d6�d7d8��Z#eje"d6�d9d:��Z$eje"d;�d<d=��Z%d>S)?�FreeBSDSpecificTestCasecCst�j|_dS)N)rr")r#rrrr$�sz"FreeBSDSpecificTestCase.setUpClasscCs
t�dS)N)r	)r#rrrr%�sz%FreeBSDSpecificTestCase.tearDownClasscCs�td|j�}tj|j�jdd�}|jd�dd�}x||r�|j�}|j�}|dd�\}}}}	}
|j�}|jd||f|j�|jt	|
�|j
�|jjd�s6|j|d	|j�q6WdS)
Nzprocstat -v %sF)Zgroupedrr�z%s-%s�[r:)
rr"r)r*Zmemory_mapsrr1r,ZaddrrZrssr2r)r-r�mapsr3r �fields�_�start�stopZperms�res�maprrr�test_proc_memory_maps�sz-FreeBSDSpecificTestCase.test_proc_memory_mapscCs<td|j�}|jtj|j�j�|jd�dj�d�dS)Nzprocstat -b %srr���)rr"r,r)r*Zexer)r-rrrr�
test_proc_exe�sz%FreeBSDSpecificTestCase.test_proc_execCsLtd|j�}|jdjtj|j�j��dj|jd�dj�dd���dS)Nzprocstat -c %s� rrr)rr"r,�joinr)r*rr)r-rrrr�test_proc_cmdline�sz)FreeBSDSpecificTestCase.test_proc_cmdlinecCs�td|j�}|jd�dj�dd�\}}}}}}tj|j�}|j�}	|j�}
|j|	jt	|��|j|	j
t	|��|j|	jt	|��|j|
jt	|��|j|
j
t	|��|j|
jt	|��dS)Nzprocstat -s %srrr�)rr"rr)r*�uids�gidsr,�realrZ	effectiveZsaved)r-rZeuidZruidZsuidZegidZrgidZsgid�prcrdrrr�test_proc_uids_gids�s&z+FreeBSDSpecificTestCase.test_proc_uids_gidscCs�g}td|j�}tj|j�}x�|jd�D]�}|j�j�}d|krtt|j�d�}|j�j	}|j
||�|jd�q*d|kr*t|j�d	�}|j�j}|j
||�|jd�q*Wt
|�dkr�td��dS)
Nzprocstat -r %srz voluntary contextrz involuntary contextrz)couldn't find lines match in procstat outr]r])rr"r)r*r�lowerr(rZnum_ctx_switchesZ	voluntaryr,�appendZinvoluntary�lenrG)r-�testedrrfr �pstat_value�psutil_valuerrr�test_proc_ctx_switches�s"

z.FreeBSDSpecificTestCase.test_proc_ctx_switchescCs�g}td|j�}tj|j�}x�|jd�D]�}|j�j�}d|kr�td|j�d
jd�d�}|j�j	}|j
||�|jd�q*d|kr*td|j�djd�d
�}|j�j}|j
||�|jd�q*Wt
|�dkr�td	��dS)Nzprocstat -r %srz	user timez0.r�.zsystem timerz)couldn't find lines match in procstat outr]r]r]r])rr"r)r*rrhr(�floatZ	cpu_times�userr,ri�systemrjrG)r-rkrrfr rlrmrrr�test_proc_cpu_times�s"

z+FreeBSDSpecificTestCase.test_proc_cpu_timescCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_active_count)�delta)r�PAGESIZE�assertAlmostEqualr)rA�activer)r-r?rrr�test_vmem_active�sz(FreeBSDSpecificTestCase.test_vmem_activecCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_inactive_count)rt)rrurvr)rA�inactiver)r-r?rrr�test_vmem_inactive�sz*FreeBSDSpecificTestCase.test_vmem_inactivecCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_wire_count)rt)rrurvr)rA�wiredr)r-r?rrr�test_vmem_wired�sz'FreeBSDSpecificTestCase.test_vmem_wiredcCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_cache_count)rt)rrurvr)rA�cachedr)r-r?rrr�test_vmem_cachedsz(FreeBSDSpecificTestCase.test_vmem_cachedcCs&td�t}|jtj�j|td�dS)Nzvm.stats.vm.v_free_count)rt)rrurvr)rAr7r)r-r?rrr�test_vmem_free	sz&FreeBSDSpecificTestCase.test_vmem_freecCs"td�}|jtj�j|td�dS)Nzvfs.bufspace)rt)rrvr)rA�buffersr)r-r?rrr�test_vmem_bufferssz)FreeBSDSpecificTestCase.test_vmem_bufferszmuse not installedcCstd�}|jtj�j|�dS)NZTotal)rr,r)rAr5)r-rBrrr�test_muse_vmem_totalsz,FreeBSDSpecificTestCase.test_muse_vmem_totalcCs"td�}|jtj�j|td�dS)NZActive)rt)rrvr)rArwr)r-rBrrr�test_muse_vmem_activesz-FreeBSDSpecificTestCase.test_muse_vmem_activecCs"td�}|jtj�j|td�dS)NZInactive)rt)rrvr)rAryr)r-rBrrr�test_muse_vmem_inactive#sz/FreeBSDSpecificTestCase.test_muse_vmem_inactivecCs"td�}|jtj�j|td�dS)NZWired)rt)rrvr)rAr{r)r-rBrrr�test_muse_vmem_wired*sz,FreeBSDSpecificTestCase.test_muse_vmem_wiredcCs"td�}|jtj�j|td�dS)NZCache)rt)rrvr)rAr}r)r-rBrrr�test_muse_vmem_cached1sz-FreeBSDSpecificTestCase.test_muse_vmem_cachedcCs"td�}|jtj�j|td�dS)NZFree)rt)rrvr)rAr7r)r-rBrrr�test_muse_vmem_free8sz+FreeBSDSpecificTestCase.test_muse_vmem_freecCs"td�}|jtj�j|td�dS)NZBuffer)rt)rrvr)rAr�r)r-rBrrr�test_muse_vmem_buffers?sz.FreeBSDSpecificTestCase.test_muse_vmem_bufferscCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_swtchi�)rt)rvr)�	cpu_stats�ctx_switchesr)r-rrr�test_cpu_stats_ctx_switchesFsz3FreeBSDSpecificTestCase.test_cpu_stats_ctx_switchescCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_intri�)rt)rvr)r��
interruptsr)r-rrr�test_cpu_stats_interruptsJsz1FreeBSDSpecificTestCase.test_cpu_stats_interruptscCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_softi�)rt)rvr)r�Zsoft_interruptsr)r-rrr�test_cpu_stats_soft_interruptsNsz6FreeBSDSpecificTestCase.test_cpu_stats_soft_interruptscCs|jtj�jtd�dd�dS)Nzvm.stats.sys.v_syscalli�)rt)rvr)r�Zsyscallsr)r-rrr�test_cpu_stats_syscallsRsz/FreeBSDSpecificTestCase.test_cpu_stats_syscallscCsLtd�}||jd�dd�}|d|jd��}t|�}|j|tj��dS)Nzsysctl kern.boottimez sec = ��,)rrrr,r)�	boot_time)r-�sZbtimerrr�test_boot_time\s
z&FreeBSDSpecificTestCase.test_boot_timez
no batterycCs�dd�}td�}tdd�|jd�D��}tj�}t|djdd	��}|d
}|j|j|�|dkrt|j|j	tj
�n|j||j	�|�dS)NcSs(t|d�\}}t|d�\}}d||fS)N�<z%d:%02d)�divmod)Zsecs�mr��hrrr�
secs2hoursgsz@FreeBSDSpecificTestCase.test_sensors_battery.<locals>.secs2hoursz
acpiconf -i 0cSs(g|] }|jd�d|jd�df�qS)�	rrr])r)�.0�xrrr�
<listcomp>msz@FreeBSDSpecificTestCase.test_sensors_battery.<locals>.<listcomp>rzRemaining capacity:�%r&zRemaining time:�unknown)r�dictrr)�sensors_batteryrr'r,�percent�secsleftZPOWER_TIME_UNLIMITED)r-r�rrVZmetricsr�Zremaining_timerrr�test_sensors_batteryesz,FreeBSDSpecificTestCase.test_sensors_batterycCsl|jtj�jtd��|jtj�jtd�dk�tj�j}|dkrT|jtd�d�n|j|td�d�dS)Nzhw.acpi.battery.lifezhw.acpi.aclinerrzhw.acpi.battery.timer�r])r,r)r�r�rZ
power_pluggedr�)r-r�rrr�#test_sensors_battery_against_sysctlxs

z;FreeBSDSpecificTestCase.test_sensors_battery_against_sysctlzhas batteryc	Cs@|jt��td�td�td�WdQRX|jtj��dS)Nzhw.acpi.battery.lifezhw.acpi.battery.timezhw.acpi.acline)ZassertRaisesrGrZassertIsNoner)r�)r-rrr�test_sensors_battery_no_battery�s
z7FreeBSDSpecificTestCase.test_sensors_battery_no_batteryN)&rLrMrNrPr$r%r
r\r^rargrnrsrxrzr|r~rr�r
rQ�MUSE_AVAILABLEr�r�r�r�r�r�r�r�r�r�r�r�rr�r�r�rrrrrR�sF

	rRzOPENBSD onlyc@seZdZdd�ZdS)�OpenBSDSpecificTestCasecCs6td�}tjj|d�}tjjtj��}|j||�dS)Nz
kern.boottimez%a %b %d %H:%M:%S %Y)r�datetimeZstrptimeZ
fromtimestampr)r�r,)r-r�Zsys_btZ	psutil_btrrrr��sz&OpenBSDSpecificTestCase.test_boot_timeN)rLrMrNr�rrrrr��sr�zNETBSD onlyc@s`eZdZedd��Zdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dS)�NetBSDSpecificTestCasecCsRtdd��2}x*|D]"}|j|�rt|j�d�dSqWWdQRXtd|��dS)Nz
/proc/meminfo�rbriz
can't find %s)�openrrrr)Zlook_for�fr rrr�
parse_meminfo�s


"z$NetBSDSpecificTestCase.parse_meminfocCs|jtj�j|jd��dS)Nz	MemTotal:)r,r)rAr5r�)r-rrr�test_vmem_total�sz&NetBSDSpecificTestCase.test_vmem_totalcCs |jtj�j|jd�td�dS)NzMemFree:)rt)rvr)rAr7r�r)r-rrrr�sz%NetBSDSpecificTestCase.test_vmem_freecCs |jtj�j|jd�td�dS)NzBuffers:)rt)rvr)rAr�r�r)r-rrrr��sz(NetBSDSpecificTestCase.test_vmem_bufferscCs |jtj�j|jd�td�dS)Nz
MemShared:)rt)rvr)rAZsharedr�r)r-rrr�test_vmem_shared�sz'NetBSDSpecificTestCase.test_vmem_sharedcCs |jtj�j|jd�td�dS)Nz
SwapTotal:)rt)rvr)�swap_memoryr5r�r)r-rrr�test_swapmem_total�sz)NetBSDSpecificTestCase.test_swapmem_totalcCs |jtj�j|jd�td�dS)Nz	SwapFree:)rt)rvr)r�r7r�r)r-rrr�test_swapmem_free�sz(NetBSDSpecificTestCase.test_swapmem_freecCs"tj�}|j|j|j|j�dS)N)r)r�r,r6r5r7)r-Zsmemrrr�test_swapmem_used�sz(NetBSDSpecificTestCase.test_swapmem_usedcCsbtdd��8}x0|D] }|jd�rt|j�d�}PqWtd��WdQRX|jtj�j|dd�dS)Nz
/proc/statr�sintrrzcouldn't find linei�)rt)	r�rrrrrvr)r�r�)r-r�r r�rrrr��s

z0NetBSDSpecificTestCase.test_cpu_stats_interruptscCsbtdd��8}x0|D] }|jd�rt|j�d�}PqWtd��WdQRX|jtj�j|dd�dS)Nz
/proc/statr�sctxtrzcouldn't find linei�)rt)	r�rrrrrvr)r�r�)r-r�r r�rrrr��s

z2NetBSDSpecificTestCase.test_cpu_stats_ctx_switchesN)rLrMrN�staticmethodr�r�rr�r�r�r�r�r�r�rrrrr��sr��__main__)"rOr��osrHr+r)rrrrZpsutil.testsrrrr	r
rrr
r�sysconfru�getuidr�rrrQZTestCaser!rRr�r�rL�__file__rrrr�<module>	sL


K


B
tests/__pycache__/test_posix.cpython-36.opt-1.pyc000064400000031543150466730550015725 0ustar003

��JZ�?�@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddlm	Z	ddlm
Z
ddlmZddlmZddlm
Z
ddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!dd�Z"dd�Z#dd�Z$ej%ed �Gd!d"�d"ej&��Z'ej%ed �Gd#d$�d$ej&��Z(e)d%k�r�ee*�dS)&zPOSIX specific tests.�N)�AIX)�BSD)�LINUX)�OPENBSD)�OSX)�POSIX)�SUNOS)�callable)�PY3)�APPVEYOR)�get_kernel_version)�get_test_subprocess)�mock)�
PYTHON_EXE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�skip_on_access_denied)�TRAVIS)�unittest)�wait_for_pid)�whichcCspts|jdd�}tr |jdd�}tr0|jdd�}t|�}tsN|jd�dj�}yt|�Stk
rj|SXd	S)
zkExpects a ps command with a -o argument and parse the result
    returning only the value of interest.
    z --no-headers � z-o startz-o stimez-o rssz	-o rssize�
�N)	r�replacerrr�split�strip�int�
ValueError)�cmd�output�r#�"/usr/lib64/python3.6/test_posix.py�ps+sr%cCs&d}trd}td||f�jd�dS)N�commandZcommzps --no-headers -o %s -p %srr)rr%r)�pid�fieldr#r#r$�ps_nameIsr)cCs d}tstrd}td||f�S)Nr&�argszps --no-headers -o %s -p %s)rrr%)r'r(r#r#r$�ps_argsPsr+z
POSIX onlyc@s�eZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Ze�e
�dd���Ze�e
�dd���Zdd�Zdd�Zdd�Zdd�Zejep�ed�dd��Zdd �Zd!d"�Zejed#�ejed$�d%d&���Zd'd(�Zd)S)*�TestProcesszBCompare psutil results against 'ps' command line utility (mainly).cCs&ttddgtjd�j|_t|j�dS)Nz-Ez-O)�stdin)r
r�
subprocess�PIPEr'r)�clsr#r#r$�
setUpClass[s
zTestProcess.setUpClasscCs
t�dS)N)r)r0r#r#r$�
tearDownClassaszTestProcess.tearDownClasscCs.td|j�}tj|j�j�}|j||�dS)Nzps --no-headers -o ppid -p %s)r%r'�psutil�ProcessZppid�assertEqual)�selfZppid_psZppid_psutilr#r#r$�	test_ppideszTestProcess.test_ppidcCs0td|j�}tj|j�j�j}|j||�dS)Nzps --no-headers -o uid -p %s)r%r'r3r4�uids�realr5)r6Zuid_psZ
uid_psutilr#r#r$�test_uidjszTestProcess.test_uidcCs0td|j�}tj|j�j�j}|j||�dS)Nzps --no-headers -o rgid -p %s)r%r'r3r4Zgidsr9r5)r6Zgid_psZ
gid_psutilr#r#r$�test_gidoszTestProcess.test_gidcCs.td|j�}tj|j�j�}|j||�dS)Nzps --no-headers -o user -p %s)r%r'r3r4�usernamer5)r6Zusername_psZusername_psutilr#r#r$�
test_usernametszTestProcess.test_usernamecCs@tj�}tjdtd�� }|j|j�t|j�j	��WdQRXdS)Nzpsutil.pwd.getpwuid)�side_effect)
r3r4r�patch�KeyErrorr5r<�strr8r9)r6�pZfunr#r#r$�test_username_no_resolutionysz'TestProcess.test_username_no_resolutioncCs@tjd�td|j�}tj|j�j�dd}|j||�dS)Ng�������?zps --no-headers -o rss -p %sri)�time�sleepr%r'r3r4�memory_infor5)r6Zrss_psZ
rss_psutilr#r#r$�test_rss_memory�s
zTestProcess.test_rss_memorycCs@tjd�td|j�}tj|j�j�dd}|j||�dS)Ng�������?zps --no-headers -o vsz -p %sri)rDrEr%r'r3r4rFr5)r6Zvsz_psZ
vsz_psutilr#r#r$�test_vsz_memory�s
zTestProcess.test_vsz_memorycCsZt|j�}tjj|�j�}tj|j�j�j�}t	j
dd|�}t	j
dd|�}|j||�dS)Nz\d.\d�)r)r'�os�path�basename�lowerr3r4�name�re�subr5)r6Zname_psZname_psutilr#r#r$�	test_name�s
zTestProcess.test_namecCs^d}dddg}tjd|d��8tjd|d��tj�}|j|j�d�WdQRXWdQRXdS)Nzlong-program-namezlong-program-name-extendedZfooZbarzpsutil._psplatform.Process.name)�return_valuez"psutil._psplatform.Process.cmdline)rr?r3r4r5rN)r6rN�cmdlinerBr#r#r$�test_name_long�s


zTestProcess.test_name_longcCs\d}tjd|d��@tjdtjdd�d��tj�}|j|j�d�WdQRXWdQRXdS)Nzlong-program-namezpsutil._psplatform.Process.name)rRz"psutil._psplatform.Process.cmdlinerrI)r>)rr?r3�AccessDeniedr4r5rN)r6rNrBr#r#r$�test_name_long_cmdline_ad_exc�s
z)TestProcess.test_name_long_cmdline_ad_exccCs\d}tjd|d��@tjdtjdd�d��tj�}|jtj|j�WdQRXWdQRXdS)Nzlong-program-namezpsutil._psplatform.Process.name)rRz"psutil._psplatform.Process.cmdlinerrI)r>)rr?r3Z
NoSuchProcessr4�assertRaisesrN)r6rNrBr#r#r$�test_name_long_cmdline_nsp_exc�s
z*TestProcess.test_name_long_cmdline_nsp_exczps -o start not availablecCshtd|j�jd�d}tj|j�j�}tjj|�jd�}t	|�}tjj|�jd�}|j
|||g�dS)Nzps --no-headers -o start -p %srrz%H:%M:%S)r%r'rr3r4Zcreate_time�datetimeZ
fromtimestampZstrftime�round�assertIn)r6Ztime_psZtime_psutilZtime_psutil_tstampZround_time_psutilZround_time_psutil_tstampr#r#r$�test_create_time�szTestProcess.test_create_timecCs`t|j�}tj|j�j�}y|j||�Wn0tk
rZ|dt|��}|j||�YnXdS)N)r)r'r3r4Zexer5�AssertionError�len)r6Zps_pathnameZpsutil_pathnameZadjusted_ps_pathnamer#r#r$�test_exe�s
zTestProcess.test_execCs0t|j�}djtj|j�j��}|j||�dS)Nr)r+r'�joinr3r4rSr5)r6Z
ps_cmdlineZpsutil_cmdliner#r#r$�test_cmdline�s
zTestProcess.test_cmdlineznot reliable on SUNOSznot reliable on AIXcCs*td|j�}tj�j�}|j||�dS)Nzps --no-headers -o nice -p %s)r%r'r3r4�nicer5)r6Zps_niceZpsutil_nicer#r#r$�	test_nice�szTestProcess.test_nicec	
s�fdd�}tjtj��}g}ddddddd	d
ddg
}trNt�dkrN|jd�trft�dkrf|jd�x�ttj�D]���jd�sr�|kr�qrqry0|j	�}xt
d
�D]}||��q�W|j	�}Wntjk
r�YqrXt||�dkrrd�||f}|j|�qrW|�r|j
ddj|��dS)NcsBf}t|�d�}|dk	r:t|�r:�dkr0tjf}||�n|dS)N�rlimit)�getattrr	r3Z
RLIMIT_NOFILE)rB�attrr*)rNr#r$�call�s
z&TestProcess.test_num_fds.<locals>.callZ	terminate�killZsuspendZresumerbZsend_signal�waitZchildrenZas_dictZmemory_info_ex���$rd�Znum_ctx_switches�_rz@failure while processing Process.%s method (before=%s, after=%s)r)rjrkrl)rjrkrm)r3r4rJ�getpidrr�append�dir�
startswithZnum_fds�rangerU�abs�failr`)	r6rgrBZfailuresZ
ignored_namesZnum1�xZnum2rur#)rNr$�test_num_fds�s4



zTestProcess.test_num_fdsN)�__name__�
__module__�__qualname__�__doc__�classmethodr1r2r7r:r;r=rCrrrGrHrQrTrVrXr�skipIfrrr\r_rarrrcrwr#r#r#r$r,Ws,			



r,c@s�eZdZdZe�dd��Zejed�eje	d�eje
d�d�dd	����Zejep`e	o`e
j�d
�e�dd���Zd
d�Zdd�Zdd�Zdd�Zejed�dd��ZdS)�TestSystemAPIszTest some system APIs.cCs�tstrddddg}nddddg}t|tjd�}|j�dj�}trRt|t	j
j�}g}x<|jd�d	d�D]&}|rjt
|j�dj��}|j|�qjW|j|j�tj�}|j�|j�ts�tr�d|kr�|jdd�|j||�dS)
Nr%z-Az-or'Zax)�stdoutrrr)rrr
r.r/Zcommunicaterr
rA�sysr�encodingrrrp�remover'r3Zpids�sortrr�insertr5)r6r!rBr"Zpids_ps�liner'Zpids_psutilr#r#r$�	test_pids s&zTestSystemAPIs.test_pidszunreliable on SUNOSzunreliable on TRAVISZifconfigzno ifconfig cmdcCsVtd�}xHtjdd�j�D]4}x.|j�D]}|j|�r(Pq(W|jd||f�qWdS)Nzifconfig -aT)Zpernicz/couldn't find %s nic in 'ifconfig -a' output
%s)rr3Znet_io_counters�keysrrrru)r6r"Znicr�r#r#r$�test_nic_names?s
zTestSystemAPIs.test_nic_namesz unreliable on APPVEYOR or TRAVIScCsxtd�}|jd�}dd�|D�}dd�|D�}|jt|�ttj���x,tj�D] }|j|j|�|j|j|�qPWdS)NZwhorcSsg|]}|j�d�qS)r)r)�.0rvr#r#r$�
<listcomp>Tsz-TestSystemAPIs.test_users.<locals>.<listcomp>cSsg|]}|j�d�qS)r)r)r�rvr#r#r$r�Us)	rrr5r^r3�usersr[rNZterminal)r6�out�linesr�Z	terminals�ur#r#r$�
test_usersNs
zTestSystemAPIs.test_userscCs<tjdttjd�d��}|jttjjt	j
��WdQRXdS)Nzpsutil._psposix.os.killrI)r>)rr?�OSError�errno�EBADFrWr3�_psposixZ
pid_existsrJro)r6�mr#r#r$�test_pid_exists_let_raise[sz(TestSystemAPIs.test_pid_exists_let_raisecCs<tjdttjd�d��}|jttjjt	j
��WdQRXdS)Nzpsutil._psposix.os.waitpidrI)r>)rr?r�r�r�rWr3r��wait_pidrJro)r6r�r#r#r$�test_os_waitpid_let_raisedsz(TestSystemAPIs.test_os_waitpid_let_raisec
CsDtjdttjd�d��$}|jtjjtjj	t
j�dd�WdQRXdS)Nzpsutil._psposix.os.waitpidrI)r>g{�G�z�?)Ztimeout)rr?r�r�ZEINTRrWr3r�ZTimeoutExpiredr�rJro)r6r�r#r#r$�test_os_waitpid_eintrlsz$TestSystemAPIs.test_os_waitpid_eintrcCs4tjddd��}|jttjjtj��WdQRXdS)Nzpsutil._psposix.os.waitpidr)rR���)rr�)	rr?rWr r3r�r�rJro)r6r�r#r#r$�test_os_waitpid_bad_ret_statusus

z-TestSystemAPIs.test_os_waitpid_bad_ret_statuszunreliable on AIXc
Cs�dd�}d
}x�tjdd�D]�}tj|j�}y||j�\}}}}WnLtk
r�}	z0t|	�j�}	d|	ksvd|	ksvd	|	krzwn�WYdd}	~	XqX|j|j	||d
�|j|j
||d
�|j|j||d
�|j|j|dd
�qWdS)NcSsvtd|�j�}|jd�d}|j�}t|d�d}t|d�d}t|d�d}t|djdd	��}||||fS)
Nzdf -k %srrirj���%rI)rrrr�floatr)�devicer�r�Zfields�total�used�free�percentr#r#r$�df�sz*TestSystemAPIs.test_disk_usage.<locals>.dfr�iF)�allzno such file or directoryzraw devices not supportedzpermission denied)Zdeltarii@)
r3Zdisk_partitionsZ
disk_usageZ
mountpointr��RuntimeErrorrArMZassertAlmostEqualr�r�r�r�)
r6r�Z	tolerance�partZusager�r�r�r��errr#r#r$�test_disk_usage~s"
zTestSystemAPIs.test_disk_usageN)rxryrzr{rr�rr}rrrr�rr3r�r�r�r�r�r�rr�r#r#r#r$r~s


			r~�__main__)+r{rYr�rJrOr.r�rDr3rrrrrrrZpsutil._compatr	r
Zpsutil.testsrrr
rrrrrrrrrrrr%r)r+r}ZTestCaser,r~rx�__file__r#r#r#r$�<module>sT
E

tests/__pycache__/test_misc.cpython-36.pyc000064400000102234150466730550014553 0ustar003

��JZ���@s|dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
mZddl
mZddl
m
Z
ddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*dd lm+Z+dd!lm,Z,dd"lm-Z-dd#lm.Z.dd$lm/Z/dd%lm0Z0dd&lm1Z1dd'lm2Z2dd(lm3Z3dd)lm4Z4dd*lm5Z5dd+lm6Z6dd,lm7Z7dd-lm8Z8dd.lm9Z9dd/lm:Z:dd0lm;Z;dd1lm<Z<ddl
Z
ddlZ
Gd2d3�d3e8j=�Z>ej?d4d5�Z@Gd6d7�d7e8j=�ZAe8jBe6d8�e8jBe7�o�ejCjDe2�d9�Gd:d;�d;e8j=���ZEGd<d=�d=e8j=�ZFGd>d?�d?e8j=�ZGGd@dA�dAe8j=�ZHGdBdC�dCe8j=�ZIGdDdE�dEe8j=�ZJGdFdG�dGe8j=�ZKeLdHk�rxe0eM�dS)Iz
Miscellaneous tests.
�N)�LINUX)�POSIX)�WINDOWS)�memoize)�memoize_when_activated)�
supports_ipv6)�wrap_numbers)�PY3)�APPVEYOR)�bind_socket)�bind_unix_socket)�
call_until)�chdir)�create_proc_children_pair)�create_sockets)�create_zombie_proc)�DEVNULL)�
get_free_port)�get_test_subprocess)�HAS_BATTERY)�HAS_CONNECTIONS_UNIX)�HAS_MEMORY_FULL_INFO)�HAS_MEMORY_MAPS)�HAS_SENSORS_BATTERY)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�import_module_by_path)�
is_namedtuple)�mock)�
PYTHON_EXE)�
reap_children)�
reload_module)�retry)�ROOT_DIR)�run_test_module_by_name)�safe_rmpath)�SCRIPTS_DIR)�sh)�tcp_socketpair)�TESTFN)�TOX)�TRAVIS)�unittest)�unix_socket_path)�unix_socketpair)�
wait_for_file)�wait_for_pidc@s�eZdZefdd�Zdd�Zefdd�Zefdd�Zefd	d
�Zefdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)S)*�TestMisccCsntj�}||�}|jd|�|jd|j|�|jd|�|j|j�|�tjjtjdtjt	j
��d��@tj�}||�}|jd|j|�|jd|�|jd|�WdQRXtjjtjdtjt	j
��d��@tj�}||�}|jd|j|�|jd|�|jd|�WdQRXtjjtjdtj
t	j
��d��4tj�}||�}|jd|j|�|jd|�WdQRXdS)Nzpsutil.Processzpid=%szname=�name)�side_effectZzombieZ
terminated)�psutil�Process�assertIn�pidr2r�patch�object�
ZombieProcess�os�getpid�assertNotIn�
NoSuchProcess�AccessDenied)�self�func�p�r�rD�!/usr/lib64/python3.6/test_misc.py�test_process__repr__Os4zTestMisc.test_process__repr__cCs|jtd�dS)N)rA)rF�str)r@rDrDrE�test_process__str__kszTestMisc.test_process__str__cCsN|jttjd��d�|jttjddd��d�|jttjddd��d�dS)NiAz7psutil.NoSuchProcess process no longer exists (pid=321)�foo)r2zCpsutil.NoSuchProcess process no longer exists (pid=321, name='foo'))�msgzpsutil.NoSuchProcess foo)�assertEqual�reprr4r>)r@rArDrDrE�test_no_such_process__repr__nsz%TestMisc.test_no_such_process__repr__cCsj|jttjd��d�|jttjddd��d�|jttjdddd��d�|jttjddd	��d
�dS)NiAzEpsutil.ZombieProcess process still exists but it's a zombie (pid=321)rI)r2zQpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo')�)r2�ppidzYpsutil.ZombieProcess process still exists but it's a zombie (pid=321, name='foo', ppid=1))rJzpsutil.ZombieProcess foo)rKrLr4r:)r@rArDrDrE�test_zombie_process__repr__zsz$TestMisc.test_zombie_process__repr__cCsN|jttjd��d�|jttjddd��d�|jttjddd��d�dS)NiAzpsutil.AccessDenied (pid=321)rI)r2z)psutil.AccessDenied (pid=321, name='foo'))rJzpsutil.AccessDenied foo)rKrLr4r?)r@rArDrDrE�test_access_denied__repr__�sz#TestMisc.test_access_denied__repr__cCsP|jttjd��d�|jttjddd��d�|jttjdddd��d�dS)	NiAz/psutil.TimeoutExpired timeout after 321 seconds�o)r7z9psutil.TimeoutExpired timeout after 321 seconds (pid=111)rI)r7r2zEpsutil.TimeoutExpired timeout after 321 seconds (pid=111, name='foo'))rKrLr4ZTimeoutExpired)r@rArDrDrE�test_timeout_expired__repr__�sz%TestMisc.test_timeout_expired__repr__cCs>tj�}tj�}|j||�d|_|j||�|j|d�dS)NrrI)rr)r4r5rKZ_ident�assertNotEqual)r@�p1�p2rDrDrE�test_process__eq__�szTestMisc.test_process__eq__cCs(ttj�tj�g�}|jt|�d�dS)NrN)�setr4r5rK�len)r@�srDrDrE�test_process__hash__�szTestMisc.test_process__hash__cCs�tt�}x�|D]~}|d
krq|jd
�syt|�Wqtk
r�|tjkr�tt|�}|dkr`w|jdk	r�d|jj�kr�|j	d|�YqXqWxtjD]}|j
||�q�WdS)N�callable�error�
namedtuple�tests�long�test�NUM_CPUS�	BOOT_TIME�TOTAL_PHYMEM�_Z
deprecatedz%r not in psutil.__all__)	r\r]r^r_r`rarbrcrd)�dirr4�
startswith�
__import__�ImportError�__all__�getattr�__doc__�lower�failr6)r@Z
dir_psutilr2ZfunrDrDrE�test__all__�s&




zTestMisc.test__all__cCs$|jdjdd�tjD��tj�dS)N�.cSsg|]}t|��qSrD)rG)�.0�xrDrDrE�
<listcomp>�sz)TestMisc.test_version.<locals>.<listcomp>)rK�joinr4�version_info�__version__)r@rDrDrE�test_version�szTestMisc.test_versioncCs"tj�}d|_|jd|j��dS)N�1rI)r4r5rIr=�as_dict)r@rBrDrDrE�!test_process_as_dict_no_new_names�sz*TestMisc.test_process_as_dict_no_new_namescst�fdd��}g�x:td�D].}|�}fif}|j||�|jt��d�qWx<td�D]0}|d�}d
if}|j||�|jt��d�qZWxDtd�D]8}|ddd�}dddif}|j||�|jt��d�q�W|j�|�}fif}|j||�|jt��d�|j|jd	�dS)Ncs�jd�||fS)z
foo docstringN)�append)�args�kwargs)�callsrDrErI�s
z"TestMisc.test_memoize.<locals>.foo�rN)�barr���z
foo docstring)rN)rN)r�rangerKrY�cache_clearrl)r@rIrr�retZexpectedrD)r~rE�test_memoize�s.zTestMisc.test_memoizecs�G�fdd�d�}|�}g�|j�|j�|jt��d�g�|jj�|j�|j�|jt��d�g�|jj�|j�|j�|jt��d�dS)NcseZdZe�fdd��ZdS)z1TestMisc.test_memoize_when_activated.<locals>.Foocs�jd�dS)N)r{)r@)r~rDrErI�sz5TestMisc.test_memoize_when_activated.<locals>.Foo.fooN)�__name__�
__module__�__qualname__rrIrD)r~rDrE�Foo�sr�rrN)rIrKrYZcache_activateZcache_deactivate)r@r��frD)r~rE�test_memoize_when_activated�s 

z$TestMisc.test_memoize_when_activatedcCs�ddlm}dd�}|j|d�|d�di�|j|d�|d�d|d	�d
i�|j|d�|d�d|d	�di�|j|d
�|d�d|d	�d
i�|j|d�|d�di�|j|d�|d�di�|j|d�|d�di�dS)Nr)�parse_environ_blockcSstr|j�S|S)N)r�upper)rZrDrDrE�ksz,TestMisc.test_parse_environ_block.<locals>.kza=1�arxz	a=1b=2�b�2za=1b=�z
a=1b=2c=3zxxxa=1z	a=1=b=2za=1b=2)�psutil._commonr�rK)r@r�r�rDrDrE�test_parse_environ_blocks



z!TestMisc.test_parse_environ_blockcCs8|jtj�t��rtjd�� }d|_tj�t�s:t�WdQRXtj�tjdtjd��}t�sjt�|j	stt�WdQRXtj�tjdtj
d��$}t�s�t�tj�|j	s�t�WdQRXtj�tjdtj
d��$}t�s�t�tj�|j	s�t�WdQRXn0|jt�� tjtj
tj�}|jd�WdQRXdS)	Nzpsutil._common.socketFzpsutil._common.socket.socket)r3z!psutil._common.socket.socket.bind�::1r)r�r)�
addCleanuprr�rr8Zhas_ipv6�AssertionError�socketr]�calledZgaierror�assertRaises�	Exception�AF_INET6�SOCK_STREAMZbind)r@rZ�sockrDrDrE�test_supports_ipv6%s4zTestMisc.test_supports_ipv6cCs�ddlm}tjjt�}||�s$t�|tjj|��s:t�tj	dt
tjd�d��|j
t
||�WdQRXtj	dt
tjd�d��|j
t
||�WdQRXtj	dt
tjd�d��||�s�t�WdQRXtj	ddd��||�s�t�WdQRXdS)	Nr)�
isfile_strictzpsutil._common.os.statrI)r3zpsutil._common.stat.S_ISREGF)�return_value)r�r�r;�path�abspath�__file__r��dirnamerr8�OSError�errnoZEPERMr�ZEACCES�EINVAL)r@r�Z	this_filerDrDrE�test_isfile_strictEszTestMisc.test_isfile_strictcs��fdd�}|tj�j��|tj��|tj��|tj��|tjdd��|tj��trpt	j
jd�rpnts�|tj
��|tj��|tjt	j���|tj��dS)Ncs<tdk	rtjtj|��tj|�}tj|�}�j||�dS)N)�json�loads�dumps�picklerK)r�r�r�)r@rDrE�checkWs


z*TestMisc.test_serialization.<locals>.checkr)�intervalz/proc/diskstats)r4r5ryZvirtual_memoryZswap_memoryZ	cpu_timesZcpu_times_percent�net_io_countersrr;r��existsr
�disk_io_countersZdisk_partitionsZ
disk_usage�getcwd�users)r@r�rD)r@rE�test_serializationVszTestMisc.test_serializationcCsVtjjtd�}tr*tjj|�r*|jd�St|�}|jt	|j
�|j|j�t
j�dS)Nzsetup.pyzcan't find setup.py)r;r�rtr#r+r�ZskipTestrr��
SystemExitZsetuprKZget_versionr4rv)r@Zsetup_py�modulerDrDrE�test_setup_scriptms
zTestMisc.test_setup_scriptcCs�tjjtjdtjd��}tj�|js*t�WdQRXtjjtjdtjd�d��}tj�|jsbt�WdQRXtjjtjdt	d��.}|j
t	��tj�WdQRX|js�t�WdQRXdS)NZcreate_time)r3rN)rr8r9r4r5r?r�r�r:�
ValueErrorr�)r@�methrDrDrE�test_ad_on_process_creationus
z$TestMisc.test_ad_on_process_creationcCsRtjddd��:|jt��}tt�WdQRX|jdt|j�j	��WdQRXdS)Nzpsutil._psplatform.cext.versionz0.0.0)r�zversion conflict)
rr8r�rir!r4r6rG�	exceptionrm)r@�cmrDrDrE�test_sanity_version_check�s
z"TestMisc.test_sanity_version_checkN)r�r�r�rLrFrHrMrPrQrSrWr[rorwrzr�r�r�r�r�r�r�r�r�rDrDrDrEr1Ms(# r1rIza b cc@s�eZdZdd�ZeZdd�Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zejej�p�ej�d�dd��ZdS)�TestWrapNumberscCstj�dS)N)rr�)r@rDrDrE�setUp�szTestWrapNumbers.setUpcCs&dtddd�i}|jt|d�|�dS)N�disk1��disk_io)�ntrKr)r@�inputrDrDrE�test_first_call�szTestWrapNumbers.test_first_callcCs8dtddd�i}|jt|d�|�|jt|d�|�dS)Nr�r�r�)r�rKr)r@r�rDrDrE�test_input_hasnt_changed�sz(TestWrapNumbers.test_input_hasnt_changedcCs�dtddd�i}|jt|d�|�dtddd�i}|jt|d�|�dtddd�i}|jt|d�|�dtddd�i}|jt|d�|�dS)	Nr�r�r��
����)r�rKr)r@r�rDrDrE�test_increase_but_no_wrap�sz)TestWrapNumbers.test_increase_but_no_wrapcCs�dtddd�i}|jt|d�|�dtddd�i}|jt|d�dtddd�i�dtddd�i}|jt|d�dtddd�i�dtddd�i}|jt|d�dtddd�i�dtddd�i}|jt|d�dtddd	�i�dtddd�i}|jt|d�dtddd	�i�dtd
dd�i}|jt|d�dtddd	�i�dtddd�i}|jt|d�dtddd	�i�dtddd�i}|jt|d�dtddd	�i�dS)
Nr��dr�r��n�Z�r����2��()r�rKr)r@r�rDrDrE�	test_wrap�s4zTestWrapNumbers.test_wrapcCstdtddd�i}|jt|d�|�tddd�tddd�d�}|jt|d�|�dtddd�i}|jt|d�|�dS)Nr�r�r��)r��disk2�)r�rKr)r@r�rDrDrE�test_changing_keys�s
z"TestWrapNumbers.test_changing_keyscCs.tddd�tddd�d�}|jt|d�|�tddd�tddd�d�}|jt|d�tddd�tddd�d��dtddd�i}|jt|d�|�tddd�tddd�d�}|jt|d�|�tddd�tddd�d�}|jt|d�|�tddd�tddd�d�}|jt|d�tddd�tddd�d��dS)Nr�r�)r�r�r�r�r�r�)r�rKr)r@r�rDrDrE�test_changing_keys_w_wrap�s*






z)TestWrapNumbers.test_changing_keys_w_wrapcCsbd'd(d)d*d"�}|jt|d#�|�|jt|d#�|�d+d,d-d.d"�}t|d#�}|j|d%dd&�dS)/N�,���#�R������ȷ�r�tU��rr��6��$��Nr��r����U	��"r����4����\)�nvme0n1Z	nvme0n1p1Z	nvme0n1p2Z	nvme0n1p3r�r�r�i�)	r�r�r�r�r�r�r�r�r�)	r�rr�r�r�rrrr�)	r�r�r�r�r�r�r�r�r�)	r�r�r�r�r�r�r�r�r�)	r�r�r�r�r�r�r�r�r�)	r�rr�r�r�rrrr�)	r�r�r�r�r�r�r�r�r�)	r�r�r�r�r�r�r�r�r�)rKr)r@�d�outrDrDrE�test_real_datas
zTestWrapNumbers.test_real_datacCsbdtddd�i}t|d�tj�}|j|dd|i�|j|ddii�|j|ddii�dS)Nr�r�r�rrNr)r�r�
cache_inforK)r@r��cacherDrDrE�test_cache_first_calls
z%TestWrapNumbers.test_cache_first_callc	Cs�dtddd�i}t|d�dtddd�i}t|d�tj�}|j|dd|i�|j|ddddd	dd
dii�|j|ddii�dS)Nr�r�r�r�rrNr)r�r)r�rN)r�r)r�rr�rK)r@r�r�rDrDrE�test_cache_call_twices

z%TestWrapNumbers.test_cache_call_twicec	s�dtddd�i}t|d�dtddd�i}t|d�tj�}�j|dd|i��j|ddd
dddddii��j|dddtdg�ii��fdd	�}dtddd�i}t|d�tj�}�j|dd|i�|�dtddd
�i}t|d�tj�}�j|dd|i�|�dtddd�i}t|d�tj�}�j|dd|i��j|ddddddddii��j|dddtdg�ii�dS)Nr�r�r�r�rrNrc	sJtj�}�j|ddddddd	dii��j|dddtd
g�ii�dS)NrNr�r�rrr�)r�r)r�rN)r�r)r�r)rr�rKrX)r�)r@rDrE�assert_4s

z0TestWrapNumbers.test_cache_wrap.<locals>.assert_r�r�r�)r�r)r�rN)r�r)r�r)r�r)r�rN)r�r)r�r)r�rr�rKrX)r@r�r�rrD)r@rE�test_cache_wrap%s:





zTestWrapNumbers.test_cache_wrapc	Cs�dtddd�i}t|d�tddd�tddd�d�}t|d�tj�}|j|dd|i�|j|ddd	dd
dddii�|j|ddii�dS)Nr�r�r�r�)r�r�rrNr)r�r)r�rN)r�r)r�rr�rK)r@r�r�rDrDrE�test_cache_changing_keysUs


z(TestWrapNumbers.test_cache_changing_keyscCs\dtddd�i}t|d�t|d�tjd�|jtj�iiif�tjd�tjd�dS)Nr�r�r�z?!?)r�rr�rKr�)r@r�rDrDrE�test_cache_clearbs



z TestWrapNumbers.test_cache_clearzno disks or NICs availablecCs�tj�tj�tj�}x$|D]}|jd|�|jd|�qWtjj�tj�}x$|D]}|jd|�|jd|�qVWtjj�tj�}|j|iiif�dS)Nzpsutil.disk_io_counterszpsutil.net_io_counters)	r4r�r�rr�r6r�r=rK)r@Zcachesr�rDrDrE�test_cache_clear_public_apisks



z,TestWrapNumbers.test_cache_clear_public_apisN)r�r�r�r��tearDownr�r�r�r�r�r�r�r�r�rrrr,�skipIfr4r�r�rrDrDrDrEr��s"
%0
	r�zcan't test on TOXzcan't locate scripts directoryc@s�eZdZdZedd��Zed=dd��Zdd�Zej	e
d	�d
d��Zdd
�Zdd�Z
dd�Zdd�Zej	epxeoxej�d�dd��Zdd�Zdd�Zdd�Zej	ed�dd��Zej	ed �d!d"��Zej	ed �d#d$��Zd%d&�Zd'd(�Zd)d*�Zd+d,�Z d-d.�Z!ej	e"d/�d0d1��Z#d2d3�Z$ej	e%d �ej	ed�d4d5���Z&ej	e'd �ej	ed�d6d7���Z(ej	e)d �ej	e*d8�d9d:���Z+d;d<�Z,dS)>�TestScriptsz-Tests for scripts in the "scripts" directory.cOs�dtjjt|�}t|g}x|D]}|j|�q Wyt|f|�j�}Wn8tk
r~}zdt	|�krlt	|�S�WYdd}~XnX|s�t
|��|S)Nz%sr?)r;r�rtr&rr{r'�strip�RuntimeErrorrGr�)�exer|r}�cmd�argr��errrDrDrE�
assert_stdout�s
zTestScripts.assert_stdoutNc	CsRtjjt|�}tr"t|ddd�}n
t|d�}|�|j�}WdQRXtj|�dS)NZrt�utf8)�encoding)	r;r�rtr&r	�open�read�ast�parse)r
r|r��srcrDrDrE�
assert_syntax�s
zTestScripts.assert_syntaxcCsZt|�}xLtjt�D]>}|jd�rdtjj|�d|kr|jdtjjt|��qWdS)Nz.pyZtest_rzno test defined for %r script)	rfr;�listdirr&�endswithr��splitextrnrt)r@Zmethsr2rDrDrE�
test_coverage�s
zTestScripts.test_coveragez
POSIX onlycCsTxNtjt�D]@}|jd�rtjjt|�}tjtj|�tj@s|j	d|�qWdS)Nz.pyz%r is not executable)
r;rr&rr�rt�stat�S_IXUSR�ST_MODErn)r@r2r�rDrDrE�test_executable�s

zTestScripts.test_executablecCs|jd�dS)Nz
disk_usage.py)r)r@rDrDrE�test_disk_usage�szTestScripts.test_disk_usagecCs|jd�dS)Nzfree.py)r)r@rDrDrE�	test_free�szTestScripts.test_freecCs|jd�dS)Nz
meminfo.py)r)r@rDrDrE�test_meminfo�szTestScripts.test_meminfocCs|jdttj���dS)Nzprocinfo.py)rrGr;r<)r@rDrDrE�
test_procinfo�szTestScripts.test_procinfoz unreliable on APPVEYOR or TRAVIScCs|jd�dS)Nzwho.py)r)r@rDrDrE�test_who�szTestScripts.test_whocCs|jd�dS)Nzps.py)r)r@rDrDrE�test_ps�szTestScripts.test_pscCs|jd�dS)Nz	pstree.py)r)r@rDrDrE�test_pstree�szTestScripts.test_pstreecCs|jd�dS)Nz
netstat.py)r)r@rDrDrE�test_netstat�szTestScripts.test_netstatzunreliable on TRAVIScCs|jd�dS)Nzifconfig.py)r)r@rDrDrE�
test_ifconfig�szTestScripts.test_ifconfigz
not supportedcCs|jdttj���dS)Nzpmap.py)rrGr;r<)r@rDrDrE�	test_pmap�szTestScripts.test_pmapcCs|jdtd�dS)Nzprocsmem.py)�stderr)rr)r@rDrDrE�
test_procsmem�szTestScripts.test_procsmemcCs|jd�dS)Nz
killall.py)r)r@rDrDrE�test_killall�szTestScripts.test_killallcCs|jd�dS)Nz	nettop.py)r)r@rDrDrE�test_nettop�szTestScripts.test_nettopcCs|jd�dS)Nztop.py)r)r@rDrDrE�test_top�szTestScripts.test_topcCs|jd�dS)Nziotop.py)r)r@rDrDrE�
test_iotop�szTestScripts.test_iotopcCs,|jdtj�j��}|jttj��|�dS)Nzpidof.py)rr4r5r2r6rGr;r<)r@�outputrDrDrE�
test_pidof�szTestScripts.test_pidofzWINDOWS onlycCs|jd�dS)Nzwinservices.py)r)r@rDrDrE�test_winservices�szTestScripts.test_winservicescCs|jd�dS)Nzcpu_distribution.py)r)r@rDrDrE�test_cpu_distribution�sz!TestScripts.test_cpu_distributioncCs|jd�dS)Nztemperatures.py)r)r@rDrDrE�test_temperatures�szTestScripts.test_temperaturescCs|jd�dS)Nzfans.py)r)r@rDrDrE�	test_fans�szTestScripts.test_fansz
no batterycCs|jd�dS)Nz
battery.py)r)r@rDrDrE�test_batteryszTestScripts.test_batterycCs|jd�dS)Nz
sensors.py)r)r@rDrDrE�test_sensorsszTestScripts.test_sensors)N)-r�r�r�rl�staticmethodrrrr,rrrrr r!r"r
r+r4r�r#r$r%r&r'rr(rr*r+r,r-r.r0rr1r2rr3rr4rrr5r6rDrDrDrEr�s@

rc@sxeZdZejd�dd��Zejd�dd��Zejd�dd��Zejd�dd	��Zejd�d
d��Z	ejd�dd
��Z
dS)�TestRetryDecoratorz
time.sleepcsFtdddd��fdd��}ttd���|j|�d�|j|jd�dS)Nr�rN)�retriesr��logfuncsx�r�j�ddqWdS)NrNr)�poprD)�queuerDrErIsz2TestRetryDecorator.test_retry_success.<locals>.foor�)r"�listr�rK�
call_count)r@�sleeprIrD)r<rE�test_retry_successsz%TestRetryDecorator.test_retry_successcsDtdddd��fdd��}ttd���|jt|�|j|jd�dS)Nr�rN)r9r�r:csx�r�j�ddqWdS)NrNr)r;rD)r<rDrErI&sz2TestRetryDecorator.test_retry_failure.<locals>.foo�)r"r=r�r��ZeroDivisionErrorrKr>)r@r?rIrD)r<rE�test_retry_failure"sz%TestRetryDecorator.test_retry_failurecCs2ttdd�dd��}|jt|�|j|jd�dS)NrN)r�r�cSst�dS)N)�	TypeErrorrDrDrDrErI3sz2TestRetryDecorator.test_exception_arg.<locals>.foor)r"r�r�rDrKr>)r@r?rIrDrDrE�test_exception_arg1sz%TestRetryDecorator.test_exception_argcCs4tdddd�dd��}|jt|�|j|jd�dS)Nr�)r9r�r:cSsdddS)NrNrrDrDrDrDrErI>sz4TestRetryDecorator.test_no_interval_arg.<locals>.foor)r"r�rBrKr>)r@r?rIrDrDrE�test_no_interval_arg:sz'TestRetryDecorator.test_no_interval_argcCs4tdddd�dd��}|jt|�|j|jd�dS)Nr�rN)r9r�r:cSsdddS)NrNrrDrDrDrDrErIHsz0TestRetryDecorator.test_retries_arg.<locals>.foo)r"r�rBrKr>)r@r?rIrDrDrE�test_retries_argEsz#TestRetryDecorator.test_retries_argcCs|jttddd�dS)Nr�rN)r9Ztimeout)r�r�r")r@r?rDrDrE�test_retries_and_timeout_argsOsz0TestRetryDecorator.test_retries_and_timeout_argsN)r�r�r�rr8r@rCrErFrGrHrDrDrDrEr8s	
r8c@sDeZdZdd�Zdd�Zdd�Zdd�Zd	d
�Zdd�Zd
d�Z	dS)�TestSyncTestUtilscCstt�dS)N)r%r))r@rDrDrErVszTestSyncTestUtils.tearDowncCsPttj��ttj��d}tjdtdg�d��|j	tj
t|�WdQRXdS)Ni��zpsutil.tests.retry.__iter__r)r�)r0r;r<�maxr4Zpidsrr8�iterr�r>)r@ZnopidrDrDrE�test_wait_for_pidYsz#TestSyncTestUtils.test_wait_for_pidc	Cs>ttd��}|jd�WdQRXtt�tjjt�s:t�dS)N�wrI)rr)�writer/r;r�r�r�)r@r�rDrDrE�test_wait_for_file_sz$TestSyncTestUtils.test_wait_for_filecCs8ttd��WdQRXttdd�tjjt�s4t�dS)NrMT)�empty)rr)r/r;r�r�r�)r@rDrDrE�test_wait_for_file_emptyes
z*TestSyncTestUtils.test_wait_for_file_emptycCs2tjdtdg�d��|jttt�WdQRXdS)Nzpsutil.tests.retry.__iter__r)r�)rr8rKr��IOErrorr/r))r@rDrDrE�test_wait_for_file_no_fileksz,TestSyncTestUtils.test_wait_for_file_no_filecCs@ttd��}|jd�WdQRXttdd�tjjt�s<t�dS)NrMrIF)�delete)rr)rNr/r;r�r�r�)r@r�rDrDrE�test_wait_for_file_no_deleteosz.TestSyncTestUtils.test_wait_for_file_no_deletecCstdd�d�}|j|d�dS)NcSsdS)NrNrDrDrDrDrE�<lambda>vsz3TestSyncTestUtils.test_call_until.<locals>.<lambda>zret == 1rN)r
rK)r@r�rDrDrE�test_call_untilusz!TestSyncTestUtils.test_call_untilN)
r�r�r�rrLrOrQrSrUrWrDrDrDrErITsrIc@s(eZdZdd�ZeZdd�Zdd�ZdS)�TestFSTestUtilscCstt�dS)N)r%r))r@rDrDrEr�|szTestFSTestUtils.setUpcCs�ttd�j�tt�tjjt�s(t�tt�tjt�tt�tjjt�sTt�t	j
dttj
d�d��.}|jt��tt�WdQRX|js�t�WdQRXdS)NrMzpsutil.tests.os.statr�)r3)rr)�closer%r;r�r�r��mkdirrr8r�r�r�r�r�)r@�mrDrDrE�test_safe_rmpath�s
z TestFSTestUtils.test_safe_rmpathcCsTtj�}tjt�tt�� |jtj�tjj|t��WdQRX|jtj�|�dS)N)r;r�rZr)rrKr�rt)r@�baserDrDrE�
test_chdir�s


$zTestFSTestUtils.test_chdirN)r�r�r�r�rr\r^rDrDrDrErXzsrXc@s2eZdZdd�Zdd�Zejed�dd��ZdS)	�TestProcessUtilscCsRt�}tj|j�}|j�st�t�|j�s2t�tjjs@t�tjj	sNt�dS)N)
rr4r5r7�
is_runningr�r r_�
_pids_started�_subprocesses_started)r@ZsubprBrDrDrE�test_reap_children�sz#TestProcessUtils.test_reap_childrencCs�t�\}}|j|j|j�|j�s&t�|j�s2t�tj�jdd�}|jt	|�d�|j
||�|j
||�|j|j�tj
��|j|j�|j�t�|j�s�t�|j�s�t�tjjs�t�tjjs�t�dS)NT)�	recursiver)rrTr7r`r�r4r5�childrenrKrYr6rOr;r<r r_rarb)r@rUrVrerDrDrE�test_create_proc_children_pair�s
z/TestProcessUtils.test_create_proc_children_pairz
POSIX onlycCs4t�}|jtdd�tj|�}|j|j�tj�dS)NT)rd)rr�r r4r5rKZstatusZ
STATUS_ZOMBIE)r@ZzpidrBrDrDrE�test_create_zombie_proc�s
z(TestProcessUtils.test_create_zombie_procN)	r�r�r�rcrfr,rrrgrDrDrDrEr_�s	r_c@sPeZdZdd�Zejed�dd��Zdd�Zejed�dd	��Z	d
d�Z
dS)
�TestNetUtilsc
Cs>t�}tjtd|fd���}|j|j�d|�WdQRXdS)Nr�)�addrrN)r�
contextlib�closingrrK�getsockname)r@ZportrZrDrDrEr�szTestNetUtils.bind_socketz
POSIX onlycCs�t��z}t|�}tj|��\|j|jtj�|j|jtj	�|j|j
�|�tjj
|�s\t�tjtj|�j�srt�WdQRXWdQRXt��:}t|tjd�}tj|��|j|jtj�WdQRXWdQRXdS)N)�type)r-rrjrkrK�familyr��AF_UNIXrmr�rlr;r�r�r�r�S_ISSOCK�st_mode�
SOCK_DGRAM)r@r2r�rDrDrE�test_bind_unix_socket�s*z"TestNetUtils.test_bind_unix_socketcCs|dt�f}ttj|d�\}}tj|��Ltj|��6|j|j�|�|j|j�|�|j	|j�|�WdQRXWdQRXdS)Nz	127.0.0.1)ri)
rr(r��AF_INETrjrkrKrl�getpeernamerT)r@ri�server�clientrDrDrE�tcp_tcp_socketpair�s
zTestNetUtils.tcp_tcp_socketpaircCs�tj�}|j�}|jdd�s"t�t���}t|�\}}zvtjj	|�sHt�t
jtj
|�j�s^t�|j
|j�|d�|j
t|jdd��d�|j
|j�|�|j
|j�|�Wd|j�|j�XWdQRXdS)NZunix)Zkindr)r4r5�num_fdsZconnectionsr�r-r.r;r�r�rrprqrKrYrlrurY)r@rBryr2rvrwrDrDrE�test_unix_socketpair�sz!TestNetUtils.test_unix_socketpaircCs�t���}tjt�}tjt�}x:|D]2}||jd7<||jtjtj�d7<q"W|j	|tj
d�t�r�|j	|tjd�t
r�tr�|j	|tjd�|j	|tjd�|j	|tjd�WdQRXdS)NrNr)r�collections�defaultdict�intrnZ
getsockoptr�Z
SOL_SOCKETZSO_TYPEZassertGreaterEqualrtrr�rrror�rr)r@ZsocksZfams�typesrZrDrDrE�test_create_sockets�s


 z TestNetUtils.test_create_socketsN)r�r�r�rr,rrrsrxrzrrDrDrDrErh�s
rhc@seZdZdd�ZdS)�TestOtherUtilscCs0ttjdd�ddd��st�tt��s,t�dS)NrIza b crNrr�)rr{r^r��tuple)r@rDrDrE�test_is_namedtuplesz!TestOtherUtils.test_is_namedtupleN)r�r�r�r�rDrDrDrEr�sr��__main__)Nrlrr{rjr�r�r;r�r�rr4rrrr�rrrrZpsutil._compatr	Zpsutil.testsr
rrr
rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0ZTestCaser1r^r�r�rr�r�rr8rIrXr_rhr�r�r�rDrDrDrE�<module>	s�Ip
C&!&E
tests/__pycache__/test_linux.cpython-36.pyc000064400000200277150466730550014765 0ustar003

��JZ�3�@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ej,j-ej,j.e/��Z0dZ1dZ2dZ3e�r�dZ4dd �Z5d!d"�Z6d#d$�Z7d%d&�Z8d'd(�Z9d)d*�Z:e*j;ed+�Gd,d-�d-e*j<��Z=e*j;ed+�Gd.d/�d/e*j<��Z>e*j;ed+�Gd0d1�d1e*j<��Z?e*j;ed+�Gd2d3�d3e*j<��Z@e*j;ed+�Gd4d5�d5e*j<��ZAe*j;ed+�Gd6d7�d7e*j<��ZBe*j;ed+�Gd8d9�d9e*j<��ZCe*j;ed+�e*j;ed:�Gd;d<�d<e*j<���ZDe*j;ed+�Gd=d>�d>e*j<��ZEe*j;ed+�Gd?d@�d@e*j<��ZFe*j;ed+�GdAdB�dBe*j<��ZGe*j;ed+�GdCdD�dDe*j<��ZHe*j;ed+�GdEdF�dFe*j<��ZIeJdGk�r�e#e/�dS)HzLinux specific tests.�)�divisionN)�LINUX)�PY3)�u)�
call_until)�HAS_BATTERY)�HAS_CPU_FREQ)�
HAS_RLIMIT)�MEMORY_TOLERANCE)�mock)�PYPY)�pyrun)�
reap_children)�
reload_module)�retry_before_failing)�run_test_module_by_name)�safe_rmpath)�sh)�skip_on_not_implemented)�TESTFN)�
ThreadTask)�TRAVIS)�unittest)�whichi�i�i'�icCspddl}|dd�}tr"t|d�}tjtjtj�}tj|��*tj|j	|j
�ttj
d|��dd��SQRXdS)Nr��ascii�256s��)�fcntlr�bytes�socket�AF_INET�
SOCK_DGRAM�
contextlib�closingZ	inet_ntoa�ioctl�fileno�SIOCGIFADDR�struct�pack)�ifnamer�s�r-�"/usr/lib64/python3.6/test_linux.py�get_ipv4_address@s

r/c
s�ddl}|dd�}tr"t|d�}tjtjtj�}tj|��`|j|j	�t
tjd|��}trfdd��nddl
}|j�dj�fdd	�|d
d�D��dd
�SQRXdS)NrrrrcSs|S)Nr-)�xr-r-r.�ordWszget_mac_address.<locals>.ord�csg|]}d�|��qS)z%02x:r-)�.0�char)r1r-r.�
<listcomp>\sz#get_mac_address.<locals>.<listcomp>�r����)rrr r!r"r#r$r%r&r'�
SIOCGIFHWADDRr)r*�__builtin__r1�join)r+rr,�infor:r-)r1r.�get_mac_addressMs

r=cCsttd�}|jd�}xJ|D]B}|jd�r|j�\}}}}tjdd�}|t|�t|�t|��SqWtddj|���dS)zQParse 'free' cmd and return swap memory's s total, used and free
    values.
    zfree -b�
ZSwap�freeztotal used freez&can't find 'Swap' in 'free' output:
%sN)r�split�
startswith�collections�
namedtuple�int�
ValueErrorr;)�out�lines�line�_�total�usedr?�ntr-r-r.�	free_swap_s


rMcCs~td�}|jd�}xT|D]L}|jd�rdd�|j�dd�D�\}}}}tjdd	�}||||||�SqWtd
dj|���dS)zSParse 'free' cmd and return physical memory's total, used
    and free values.
    zfree -br>ZMemcSsg|]}t|��qSr-)rD)r3r0r-r-r.r5{sz free_physmem.<locals>.<listcomp>r7�r?ztotal used free shared outputz%can't find 'Mem' in 'free' output:
%sN)rr@rArBrCrEr;)rFrGrHrJrKr?�sharedrLr-r-r.�free_physmemns


"rPcCsNtd�}x4|jd�D]&}|j�}||krt|jd�d�SqWtd|��dS)Nz	vmstat -sr>� rz can't find %r in 'vmstat' output)rr@�striprDrE)�statrFrHr-r-r.�vmstat�srTcCs(td�j�}ttt|j�djd���S)Nzfree -Vr7�.r8)rrR�tuple�maprDr@)rFr-r-r.�get_free_version_info�srXz
LINUX onlyc@s�eZdZdd�Zejeo e�d kd�e�dd���Z	eje
d�e�d	d
���Ze�dd��Zeje
d�e�d
d���Z
eje
d�e�dd���Ze�dd��Ze�dd��Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)!�TestSystemVirtualMemorycCs&td�d}tj�j}|j||�dS)Nztotal memoryi)rT�psutil�virtual_memoryrJ�assertAlmostEqual)�self�vmstat_value�psutil_valuer-r-r.�
test_total�s
z"TestSystemVirtualMemory.test_total��zold free versioncCs8t�}|j}tj�j}|j||td|||jfd�dS)Nz	%s %s 
%s)�delta�msg)rPrKrZr[r\r
�output)r]r?�
free_valuer_r-r-r.�	test_used�s
z!TestSystemVirtualMemory.test_usedzunreliable on TRAVIScCs*td�d}tj�j}|j||td�dS)Nzfree memoryi)rc)rTrZr[r?r\r
)r]r^r_r-r-r.�	test_free�s
z!TestSystemVirtualMemory.test_freecCs*td�d}tj�j}|j||td�dS)Nz
buffer memoryi)rc)rTrZr[�buffersr\r
)r]r^r_r-r-r.�test_buffers�s
z$TestSystemVirtualMemory.test_bufferscCs*td�d}tj�j}|j||td�dS)Nz
active memoryi)rc)rTrZr[�activer\r
)r]r^r_r-r-r.�test_active�s
z#TestSystemVirtualMemory.test_activecCs*td�d}tj�j}|j||td�dS)Nzinactive memoryi)rc)rTrZr[�inactiver\r
)r]r^r_r-r-r.�
test_inactive�s
z%TestSystemVirtualMemory.test_inactivecCsJt�}|j}|dkrtjd��tj�j}|j||td|||jfd�dS)Nrz%free does not support 'shared' columnz	%s %s 
%s)rcrd)	rPrOr�SkipTestrZr[r\r
re)r]r?rfr_r-r-r.�test_shared�s

z#TestSystemVirtualMemory.test_sharedcCshtd�}|jd�}d|dkr*tjd��n:t|dj�d	�}tj�j}|j||t	d|||fd�dS)
Nzfree -br>�	availablerz(free does not support 'available' columnr7z	%s %s 
%s)rcrdr8)
rr@rrorDrZr[rqr\r
)r]rFrGrfr_r-r-r.�test_available�s

z&TestSystemVirtualMemory.test_availablecsn�fdd�}t�trdnd}tj|d|d���6}tjdd���}tjd�tj�}|j	s\t
�|jt|�d	�|d
}|j
jd�s�t
�|jdt|j��|jd
t|j��|jdt|j��|jdt|j��|jdt|j��|jdt|j��|jdt|j��|j|jd
�|j|jd
�|j|jd
�|j|jd
�|j|jd
�|j|jd
�WdQRXWdQRXdS)Ncs0|dkrtjtjd�j��S�|f|�|�SdS)Nz
/proc/meminfoa�                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemAvailable:         -1 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    SReclaimable:     346648 kB
                    )�io�BytesIO�textwrap�dedent�encode)�name�args�kwargs)�	orig_openr-r.�	open_mock�s	zBTestSystemVirtualMemory.test_warnings_on_misses.<locals>.open_mockz
builtins.openz__builtin__.openT)�create�side_effect)�record�alwaysr7rzpsutil/_pslinux.pyz#memory stats couldn't be determined�cachedrOrkrmrirq)�openrr�patch�warnings�catch_warnings�simplefilterrZr[�called�AssertionError�assertEqual�len�filename�endswith�assertIn�str�messager�rkrmrOrirq)r]r|�patch_point�m�ws�ret�wr-)r{r.�test_warnings_on_misses�s2

z/TestSystemVirtualMemory.test_warnings_on_missesc
Cs�ddlm}ddlm}i}|d��4}x,|D]$}|j�}t|d�d||d<q,WWdQRX||�}d|kr�|d}t||�|d}	|j|	d	�dS)
Nr)�calculate_avail_vmem)�open_binaryz
/proc/meminfor7is
MemAvailable:�d�
)�psutil._pslinuxr�r�r@rD�absZ
assertLess)
r]r�r�Zmems�frH�fields�a�bZdiff_percentr-r-r.�test_avail_old_percents

&z.TestSystemVirtualMemory.test_avail_old_percentcs��fdd�}t�trdnd}tj|d|d��X}tjdd��}tj�}WdQRX|jsXt	�|j
|jd�|d
}|jdt
|j��WdQRXdS)
Ncs0|dkrtjtjd�j��S�|f|�|�SdS)Nz
/proc/meminfoa�                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemAvailable:    6574984 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    SReclaimable:     346648 kB
                    )rsrtrurvrw)rxryrz)r{r-r.r|0szKTestSystemVirtualMemory.test_avail_old_comes_from_kernel.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)ri�Sdirz,inactive memory stats couldn't be determinedl �")r�rrr�r�r�rZr[r�r�r�rqr�r�r�)r]r|r�r�r�r�r�r-)r{r.� test_avail_old_comes_from_kernel-s
z8TestSystemVirtualMemory.test_avail_old_comes_from_kernelcs��fdd�}t�trdnd}tj|d|d��X}tjdd��}tj�}WdQRX|jsXt	�|j
|jd�|d}|jdt
|j��WdQRXdS)Ncs0|dkrtjtjd�j��S�|f|�|�SdS)Nz
/proc/meminfoa�                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    )rsrtrurvrw)rxryrz)r{r-r.r|Ss
zHTestSystemVirtualMemory.test_avail_old_missing_fields.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)ri�dii�Irz,inactive memory stats couldn't be determinedi�}l'Ll`LG)r�rrr�r�r�rZr[r�r�r�rqr�r�r�)r]r|r�r�r�r�r�r-)r{r.�test_avail_old_missing_fieldsOs
z5TestSystemVirtualMemory.test_avail_old_missing_fieldscs��fdd�}t�trdnd}tj|d|d��X}tjdd��}tj�}WdQRX|jsXt	�|j
|jd�|d}|jdt
|j��WdQRXdS)NcsF|dkrtjtjd�j��S|dkr2ttjd��n�|f|�|�SdS)Nz
/proc/meminfoaT                    Active:          9444728 kB
                    Active(anon):    6145416 kB
                    Active(file):    2950064 kB
                    Buffers:          287952 kB
                    Cached:          4818144 kB
                    Inactive(file):  1578132 kB
                    Inactive(anon):   574764 kB
                    Inactive(file):  1567648 kB
                    MemFree:         2057400 kB
                    MemTotal:       16325648 kB
                    Shmem:            577588 kB
                    SReclaimable:     346648 kB
                    z/proc/zoneinfozno such file or directory)rsrtrurvrw�IOError�errno�ENOENT)rxryrz)r{r-r.r|qs
zJTestSystemVirtualMemory.test_avail_old_missing_zoneinfo.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)ri�dii�Irz,inactive memory stats couldn't be determinedi�}l'Ll`LG)r�rrr�r�r�rZr[r�r�r�rqr�r�r�)r]r|r�r�r�r�r�r-)r{r.�test_avail_old_missing_zoneinfons
z7TestSystemVirtualMemory.test_avail_old_missing_zoneinfoN)rararb)�__name__�
__module__�__qualname__r`r�skipIfrrXrrgrrhrjrlrnrprrr�r�r�r�r�r-r-r-r.rY�s$	


,"rYc@s\eZdZedd��Zdd�Ze�dd��Ze�dd��Zd	d
�Z	dd�Z
d
d�Zdd�ZdS)�TestSystemSwapMemoryc	Cs,td��}|j�}WdQRXd|ko*d|kS)z3Return True if /proc/meminfo provides swap metrics.z
/proc/meminfoNz
SwapTotal:z	SwapFree:)r��read)r��datar-r-r.�meminfo_has_swap_info�s
z*TestSystemSwapMemory.meminfo_has_swap_infocCs"t�j}tj�j}|j||td�S)N)rc)rMrJrZ�swap_memoryr\r
)r]rfr_r-r-r.r`�s
zTestSystemSwapMemory.test_totalcCs"t�j}tj�j}|j||td�S)N)rc)rMrKrZr�r\r
)r]rfr_r-r-r.rg�s
zTestSystemSwapMemory.test_usedcCs"t�j}tj�j}|j||td�S)N)rc)rMr?rZr�r\r
)r]rfr_r-r-r.rh�s
zTestSystemSwapMemory.test_freecCs�tjddd���}tjdd��x}tjd�tj�}|js:t�|j	t
|�d�|d}|jjd�sbt�|j
d	t|j��|j	|jd�|j	|jd�WdQRXWdQRXdS)
Nzpsutil._pslinux.openT)r})rr�r7rzpsutil/_pslinux.pyz9'sin' and 'sout' swap memory stats couldn't be determined)rr�r�r�r�rZr�r�r�r�r�r�r�r�r�r��sin�sout)r]r�r�r�r�r-r-r.�test_missing_sin_sout�s

z*TestSystemSwapMemory.test_missing_sin_soutcs��fdd�}t�trdnd}tj|d|d���}tjdd��x}tjd�tj�}|j	sXt
�|jt|�d	�|d
}|j
jd�s�t
�|jdt|j��|j|jd
�|j|jd
�WdQRXWdQRXdS)
Ncs*|dkrttjd��n�|f|�|�SdS)Nz/proc/vmstatzno such file or directory)r�r�r�)rxryrz)r{r-r.r|�sz=TestSystemSwapMemory.test_no_vmstat_mocked.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)rr�r7rzpsutil/_pslinux.pyzK'sin' and 'sout' swap memory stats couldn't be determined and were set to 0)r�rrr�r�r�r�rZr�r�r�r�r�r�r�r�r�r�r�r�)r]r|r�r�r�r�r�r-)r{r.�test_no_vmstat_mocked�s 

z*TestSystemSwapMemory.test_no_vmstat_mockedcCs�|j�stjd�Stjd��}tj�}WdQRX|js<t�ddl	j
}|j�\}}}}}}}||9}||9}|j|j
|�|j|j|�dS)Nz!/proc/meminfo has no swap metricsz"psutil._pslinux.cext.linux_sysinfor)r�r�skiprr�rZr�r�r�Zpsutil._psutil_linuxZ
_psutil_linuxZ
linux_sysinfor�rJr?)r]r��swapZcextrIrJr?Zunit_multiplierr-r-r.�test_meminfo_against_sysinfo�s

z1TestSystemSwapMemory.test_meminfo_against_sysinfoc	sN�fdd�}t�trdnd}tj|d|d��}tj�|js@t�WdQRXdS)Ncs&|dkrtjd�S�|f|�|�SdS)Nz
/proc/meminfo�)rsrt)rxryrz)r{r-r.r|�s
zKTestSystemSwapMemory.test_emulate_meminfo_has_no_metrics.<locals>.open_mockz
builtins.openz__builtin__.openT)r}r~)r�rrr�rZr�r�r�)r]r|r�r�r-)r{r.�#test_emulate_meminfo_has_no_metrics�sz8TestSystemSwapMemory.test_emulate_meminfo_has_no_metricsN)
r�r�r��staticmethodr�r`rrgrhr�r�r�r�r-r-r-r.r��sr�c@s&eZdZejed�dd��Zejejj	d�d�dd��Z
ejejj	d�d	�d
d��Zejed�d
�dd��Z
ejed�d�dd��Zdd�Zdd�Zejed�dd��Zejed�ejed�dd���Zejed�dd��Zejed�d d!��Zejed�ejed�d"d#���Zd$S)%�
TestSystemCPUzunknown failure on traviscCs�tj�j}tjdtj�d�d}ttt	|j
d���}|dkrL|jd|�n|jd|�|d
krn|jd	|�n|jd	|�|dkr�|jd|�n|jd|�dS)Nz
\d+\.\d+\.\d+�rrU��ZstealrZguestraZ
guest_nice)r�r�r�)r�r�r)rar�r)
rZ�	cpu_times�_fields�re�findall�os�unamerVrWrDr@r��assertNotIn)r]r�Z
kernel_verZkernel_ver_infor-r-r.�test_cpu_timess
zTestSystemCPU.test_cpu_timesz/sys/devices/system/cpu/onlinez-/sys/devices/system/cpu/online does not existc
CsVtd��}|j�j�}WdQRXdt|�krRt|jd�d�d}|jtj�|�dS)Nz/sys/devices/system/cpu/online�-r7)	r�r�rRr�rDr@r�rZ�	cpu_count)r]r��valuer-r-r.�*test_cpu_count_logical_w_sysdev_cpu_onlines

z8TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_onlinez/sys/devices/system/cpuz&/sys/devices/system/cpu does not existcCs0tjd�}tdd�|D��}|jtj�|�dS)Nz/sys/devices/system/cpucSs g|]}tjd|�dk	r|�qS)zcpu\d+$N)r��search)r3r0r-r-r.r5%szITestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_num.<locals>.<listcomp>)r��listdirr�r�rZr�)r]Zls�countr-r-r.�'test_cpu_count_logical_w_sysdev_cpu_num!s
z5TestSystemCPU.test_cpu_count_logical_w_sysdev_cpu_numZnprocznproc utility not availablecCs$ttd��}|jtjdd�|�dS)Nznproc --allT)�logical)rDrr�rZr�)r]�numr-r-r.�test_cpu_count_logical_w_nproc(sz,TestSystemCPU.test_cpu_count_logical_w_nprocZlscpuzlscpu utility not availablecCs8td�}tdd�|jd�D��}|jtjdd�|�dS)Nzlscpu -pcSsg|]}|jd�s|�qS)�#)rA)r3r0r-r-r.r50sz@TestSystemCPU.test_cpu_count_logical_w_lscpu.<locals>.<listcomp>r>T)r�)rr�r@r�rZr�)r]rFr�r-r-r.�test_cpu_count_logical_w_lscpu-sz,TestSystemCPU.test_cpu_count_logical_w_lscpuc	&s<ddl}|jj�}tjdtd���}|j|jj�|�|js@t�tjddd��:}|j	|jj��|j|j
d�|j|jddd�WdQRXtd	d
��}|j
�}WdQRXtj|�}tjd|dd��}|j|jj�|�WdQRX�fdd
�}t�tr�dnd}tj||dd��|j|jj�|�WdQRXWdQRXdS)Nrzpsutil._pslinux.os.sysconf)r~zpsutil._pslinux.openT)r}r�z
/proc/statz
/proc/cpuinfo�rb)�return_valuer}cs(|jd�rtjd�S�|f|�|�SdS)Nz
/proc/cpuinfor�)rArsrt)rxryrz)r{r-r.r|Ps

z>TestSystemCPU.test_cpu_count_logical_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~r})r��_pslinuxZcpu_count_logicalrr�rEr�r�r��assertIsNoneZ
call_count�	call_argsr�r�rsrtr)	r]rZ�originalr�r�Zcpuinfo_data�	fake_filer|r�r-)r{r.�test_cpu_count_logical_mocked3s*

 
z+TestSystemCPU.test_cpu_count_logical_mockedc	Cs8tjddd�� }|jtjj��|js*t�WdQRXdS)Nzpsutil._pslinux.openT)r})rr�r�rZr�Zcpu_count_physicalr�r�)r]r�r-r-r.�test_cpu_count_physical_mocked[sz,TestSystemCPU.test_cpu_count_physical_mockedz
not supportedc	Cs,tjdgd��|jtj��WdQRXdS)Nzpsutil._pslinux.glob.glob)r�)rr�r�rZ�cpu_freq)r]r-r-r.�test_cpu_freq_no_resultbsz%TestSystemCPU.test_cpu_freq_no_resultzfails on Travisc
sT��fdd�}g�tj�tjd|dd��"tj�s6t�|jt��d�WdQRXdS)Ncs.|jd�r�jd�gS�jd��|�SdS)Nz&/sys/devices/system/cpu/cpufreq/policy)rA�append)�pattern)�flags�	orig_globr-r.�	glob_mockks



z>TestSystemCPU.test_cpu_freq_use_second_file.<locals>.glob_mockzpsutil._pslinux.glob.globT)r~r}r�)�globrr�rZr�r�r�r�)r]r�r-)r�r�r.�test_cpu_freq_use_second_filegs
z+TestSystemCPU.test_cpu_freq_use_second_filecs��fdd�}t�trdnd}tj||d��Ttjddgd��8tj�}|j|jd	�|j|jd
�|j|j	d�WdQRXWdQRXdS)NcsP|jd�rtjd�S|jd�r(tjd�S|jd�r<tjd�S�|f|�|�SdS)Nz/scaling_cur_freqs500000z/scaling_min_freqs600000z/scaling_max_freqs700000)r�rsrt)rxryrz)r{r-r.r||s





z;TestSystemCPU.test_cpu_freq_emulate_data.<locals>.open_mockz
builtins.openz__builtin__.open)r~z	glob.globz'/sys/devices/system/cpu/cpufreq/policy0)r�g@@g��@g�@)
r�rrr�rZr�r��current�min�max)r]r|r��freqr-)r{r.�test_cpu_freq_emulate_datazs
z(TestSystemCPU.test_cpu_freq_emulate_datacs��fdd�}t�trdnd}dddg}tj||d��Rtjd	|d
��8tj�}|j|jd�|j|jd�|j|j	d
�WdQRXWdQRXdS)NcsP|jd�rtjd�S|jd�r(tjd�S|jd�r<tjd�S�|f|�|�SdS)Nz/scaling_cur_freqs100000z/scaling_min_freqs200000z/scaling_max_freqs300000)r�rsrt)rxryrz)r{r-r.r|�s





z@TestSystemCPU.test_cpu_freq_emulate_multi_cpu.<locals>.open_mockz
builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z	glob.glob)r�gY@gi@g�r@)
r�rrr�rZr�r�r�r�r�)r]r|r��policiesr�r-)r{r.�test_cpu_freq_emulate_multi_cpu�s
z-TestSystemCPU.test_cpu_freq_emulate_multi_cpucs��fdd�}t�trdnd}dddg}tj||d��6tjd	|d
��tj�}|j|jd�WdQRXWdQRX�fdd�}t�tr�dnd}tj||d��.tjd	|d
��|jt	tj�WdQRXWdQRXdS)
Ncs@|jd�rttjd��n$|jd�r,tjd�S�|f|�|�SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freqs200000)r�r�r�r�rsrt)rxryrz)r{r-r.r|�s



zGTestSystemCPU.test_cpu_freq_no_scaling_cur_freq_file.<locals>.open_mockz
builtins.openz__builtin__.openz'/sys/devices/system/cpu/cpufreq/policy0z'/sys/devices/system/cpu/cpufreq/policy1z'/sys/devices/system/cpu/cpufreq/policy2)r~z	glob.glob)r���csD|jd�rttjd��n(|jd�r0ttjd��n�|f|�|�SdS)Nz/scaling_cur_freqr2z/cpuinfo_cur_freq)r�r�r�r�)rxryrz)r{r-r.r|�s


)
r�rrr�rZr�r�r��assertRaises�NotImplementedError)r]r|r�r�r�r-)r{r.�&test_cpu_freq_no_scaling_cur_freq_file�s "z4TestSystemCPU.test_cpu_freq_no_scaling_cur_freq_fileN)r�r�r�rr�rr�r��path�existsr�r�rr�r�r�r�rr�r�r�r�r�r-r-r-r.r�s (

r�c@s4eZdZejed�dd��Zejed�dd��ZdS)�TestSystemCPUStatszfails on TraviscCs&td�}tj�j}|j||dd�dS)Nzcontext switchesi�)rc)rTrZ�	cpu_statsZctx_switchesr\)r]r^r_r-r-r.�test_ctx_switches�s
z$TestSystemCPUStats.test_ctx_switchescCs&td�}tj�j}|j||dd�dS)N�
interruptsi�)rc)rTrZr�r�r\)r]r^r_r-r-r.�test_interrupts�s
z"TestSystemCPUStats.test_interruptsN)r�r�r�rr�rr�r�r-r-r-r.r��sr�c@s|eZdZdd�Zdd�Ze�dd��Zeje	d�d�eje
d	�d
d���Zej
ded
�ej
ddd�dd���Zdd�ZdS)�TestSystemNetworkcCsjxdtj�j�D]T\}}xJ|D]B}|jtjkr@|j|jt|��q|jtj	kr|j|jt
|��qWqWdS)N)rZ�net_if_addrs�itemsZfamilyZAF_LINKr�Zaddressr=r!r"r/)r]rxZaddrsZaddrr-r-r.�test_net_if_addrs_ips�s
z'TestSystemNetwork.test_net_if_addrs_ipscCsbx\tj�j�D]L\}}ytd|�}Wntk
r:YqX|j|jttj	d|�d��qWdS)Nzifconfig %sz(?i)MTU[: ](\d+)r)
rZ�net_if_statsr�r�RuntimeErrorr�ZmturDr�r�)r]rx�statsrFr-r-r.�test_net_if_stats�sz#TestSystemNetwork.test_net_if_statscs�fdd�}tjddd�}x�|j�D]�\�}y|��}Wntk
rNw$YnX|j|j|ddd	�|j|j|d
dd	�|j|j|ddd	�|j|j|ddd	�|j|j	|d
dd	�|j|j
|ddd	�|j|j|ddd	�|j|j|ddd	�q$WdS)Ncs�i}td��}ttjd|�d�|d<ttjd|�d�|d<ttjd|�d�|d<ttjd|�d	�|d
<ttjd|�d�|d<ttjd|�d	�|d
<ttjd|�d�|d<ttjd|�d�|d<|S)Nzifconfig %szRX packets[: ](\d+)r�packets_recvzTX packets[: ](\d+)�packets_sentzerrors[: ](\d+)�errinr7�erroutzdropped[: ](\d+)�dropin�dropoutz#RX (?:packets \d+ +)?bytes[: ](\d+)�
bytes_recvz#TX (?:packets \d+ +)?bytes[: ](\d+)�
bytes_sent)rrDr�r�)Znicr�rF)rxr-r.�ifconfigsz8TestSystemNetwork.test_net_io_counters.<locals>.ifconfigTF)Zpernic�nowraprirN)rcrr�rrr�rrrii)
rZ�net_io_countersr�r�r\rrr�rrrrr)r]rZnior�Zifconfig_retr-)rxr.�test_net_io_counterss.z&TestSystemNetwork.test_net_io_countersZipz'ip' utility not availablezskipped on TraviscCs�td�j�}dd�tj�j�D�}d}xL|jd�D]>}|j�}tjd|�r2|d7}|jd�dj�}|j||�q2W|j	t
|�|d	tj|�|fd
�dS)Nzip addrcSsg|]}d|kr|�qS)�:r-)r3r0r-r-r.r52sz7TestSystemNetwork.test_net_if_names.<locals>.<listcomp>rr>z^\d+:r7rz	%s
---
%s)rd)
rrRrZr��keysr@r�r�r�r�r��pprintZpformat)r]rFZnics�foundrHrxr-r-r.�test_net_if_names.sz#TestSystemNetwork.test_net_if_namesz psutil._pslinux.socket.inet_ntop)r~zpsutil._pslinux.supports_ipv6F)r�cCsRy*tjtjtj�}|j|j�|jd�Wntjk
r@YnXtjdd�dS)N�::1rZinet6)�kind)rr)	r!ZAF_INET6ZSOCK_STREAM�
addCleanup�closeZbind�errorrZ�net_connections)r]Z
supports_ipv6Z	inet_ntopr,r-r-r.�%test_net_connections_ipv6_unsupported=sz7TestSystemNetwork.test_net_connections_ipv6_unsupportedc
sP�fdd�}t�trdnd}tj||d��}tjdd�|jsBt�WdQRXdS)Ncs,|dkrtjtjd��S�|f|�|�SdS)Nz/proc/net/unixaB                    0: 00000003 000 000 0001 03 462170 @/tmp/dbus-Qw2hMPIU3n
                    0: 00000003 000 000 0001 03 35010 @/tmp/dbus-tB2X8h69BQ
                    0: 00000003 000 000 0001 03 34424 @/tmp/dbus-cHy80Y8O
                    000000000000000000000000000000000000000000000000000000
                    )rs�StringIOrurv)rxryrz)r{r-r.r|Jsz@TestSystemNetwork.test_net_connections_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~Zunix)r)r�rrr�rZrr�r�)r]r|r�r�r-)r{r.�test_net_connections_mockedIsz-TestSystemNetwork.test_net_connections_mockedN)r�r�r�r�r�rr
rr�rrrrr�rErrr-r-r-r.r��s	*r�c@sNeZdZejeed�d�e�dd���Zdd�Z	dd�Z
d	d
�Zdd�Zd
S)�TestSystemDisks�statvfszos.statvfs() not availablecCs�dd�}x�tjdd�D]|}tj|j�}||j�\}}}}|j|j|�t|j|�d	krl|jd|j|f�t|j	|�dkr|jd|j	|f�qWdS)NcSsztd|�j�}|jd�}|jd�|jd�}|j�dd�\}}}}|dkrRd}t|�t|�t|�}}}||||fS)Nzdf -P -B 1 "%s"r>r�Znoner2)rrRr@�poprD)r�rFrGrH�devrJrKr?r-r-r.�dfis


z:TestSystemDisks.test_disk_partitions_and_usage.<locals>.dfF)�allr�izpsutil=%s, df=%si(i�i(i�)
rZ�disk_partitionsZ
disk_usageZ
mountpointr�rJr�r?�failrK)r]r�partZusagerrJrKr?r-r-r.�test_disk_partitions_and_usagedsz.TestSystemDisks.test_disk_partitions_and_usagecCs�tdd��}|j�}WdQRXd|krPx�tj�D]}|jdkr0Pq0W|jd�n|tjtd��}t	j
d|dd��X}t	j
d	dgd
��<}tj�}|js�t�|js�t�|s�t�|j
|djd�WdQRXWdQRXdS)Nz/proc/filesystems�r�zfszcouldn't find any ZFS partitionz
nodev	zfs
zpsutil._pslinux.openT)r�r}z$psutil._pslinux.cext.disk_partitions�	/dev/sdb3�/�rw)r�r)r&r'r%r()r�r�rZr Zfstyper!rsrrrr�r�r�r�)r]r�r�r"r��m1�m2r�r-r-r.�test_disk_partitions_mocked~s$


z+TestSystemDisks.test_disk_partitions_mockedcs��fdd�}t�trdnd}tj||d���}tjdd�}|jsBt�|j|j	d�|j|j
d	�|j|jd
t�|j|j
d�|j|jd�|j|jd
�|j|jdt�|j|jd�|j|jd�WdQRXdS)NcsB|dkrtjtjd��S|dkr.tjtd��S�|f|�|�SdS)Nz/proc/partitionszu                    major minor  #blocks  name

                       8        0  488386584 hda
                    z/proc/diskstatsz+   3     0   1 hda 2 3 4 5 6 7 8 9 10 11 12)rsrrurvr)rxryrz)r{r-r.r|�s
zJTestSystemDisks.test_disk_io_counters_kernel_2_4_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)rr7r�rarrNr���r�)r�rrr�rZ�disk_io_countersr�r�r��
read_count�read_merged_count�
read_bytes�SECTOR_SIZE�	read_time�write_count�write_merged_count�write_bytes�
write_time�	busy_time)r]r|r�r�r�r-)r{r.�'test_disk_io_counters_kernel_2_4_mocked�s

z7TestSystemDisks.test_disk_io_counters_kernel_2_4_mockedcs��fdd�}t�trdnd}tj||d���}tjdd�}|jsBt�|j|j	d�|j|j
d	�|j|jd
t�|j|j
d�|j|jd�|j|jd
�|j|jdt�|j|jd�|j|jd�WdQRXdS)NcsB|dkrtjtjd��S|dkr.tjtd��S�|f|�|�SdS)Nz/proc/partitionszu                    major minor  #blocks  name

                       8        0  488386584 hda
                    z/proc/diskstatsz'   3    0   hda 1 2 3 4 5 6 7 8 9 10 11)rsrrurvr)rxryrz)r{r-r.r|�s
zOTestSystemDisks.test_disk_io_counters_kernel_2_6_full_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)rr7r�rarrNr�r,r-r�)r�rrr�rZr.r�r�r�r/r0r1r2r3r4r5r6r7r8)r]r|r�r�r�r-)r{r.�,test_disk_io_counters_kernel_2_6_full_mocked�s

z<TestSystemDisks.test_disk_io_counters_kernel_2_6_full_mockedcs��fdd�}t�trdnd}tj||d���}tjdd�}|jsBt�|j|j	d�|j|j
d	t�|j|jd
�|j|j
dt�|j|jd�|j|jd�|j|jd�|j|jd�|j|jd�WdQRXdS)
NcsB|dkrtjtjd��S|dkr.tjtd��S�|f|�|�SdS)Nz/proc/partitionszu                    major minor  #blocks  name

                       8        0  488386584 hda
                    z/proc/diskstatsz   3    1   hda 1 2 3 4)rsrrurvr)rxryrz)r{r-r.r|�s
zRTestSystemDisks.test_disk_io_counters_kernel_2_6_limited_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)rr7r�rarr)r�rrr�rZr.r�r�r�r/r1r2r4r6r0r3r5r7r8)r]r|r�r�r�r-)r{r.�/test_disk_io_counters_kernel_2_6_limited_mocked�s

z?TestSystemDisks.test_disk_io_counters_kernel_2_6_limited_mockedN)
r�r�r�rr��hasattrr�rr#r+r9r:r;r-r-r-r.ras rc@sVeZdZdd�Zejd�dd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�ZdS)�TestMisccCs(td�}tj�}|jt|�t|��dS)Nz	boot time)rTrZ�	boot_timer�rD)r]r^r_r-r-r.�test_boot_timeszTestMisc.test_boot_timezpsutil.traceback.print_excc"stj�}ttjj|d�d��$}|jd�|jd�|jd�WdQRX�z�t��fdd�}trbdnd	}tj	||d
���xt
t�|js�t
�|jttj�|jttjdd�|jttj�|jttjdd�|jttj�|jttjdd�|t_|jtj�d
�|jttj��d
�tjdd�}|jt|�d
�tjdd�}|jttt|��d
�ttjj|d�d��$}|jd�|jd�|jd�WdQRX|jtj�d
�|jttjdd��d
�|jttj��d
�|jttttjdd���d
�WdQRXWdtj|�t
t�X|jtjd�dS)NrSr�zcpu   0 0 0 0 0 0 0 0 0 0
zcpu0  0 0 0 0 0 0 0 0 0 0
zcpu1  0 0 0 0 0 0 0 0 0 0
cs&|jd�rttjd���|f|�|�S)Nz/proczrejecting access for test)rAr�r�r�)rxryrz)r{r-r.r|s
z4TestMisc.test_no_procfs_on_import.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)�percpurzcpu   1 0 0 0 0 0 0 0 0 0
zcpu0  1 0 0 0 0 0 0 0 0 0
zcpu1  1 0 0 0 0 0 0 0 0 0
z/proc)�tempfile�mkdtempr�r�r�r;�writerrr�rrZr�r�r�r�r�Zcpu_percentZcpu_times_percent�PROCFS_PATHr��sumrWZassertNotEqual�shutilZrmtree)r]�tbZ	my_procfsr�r|r�Zper_cpu_percentZper_cpu_times_percentr-)r{r.�test_no_procfs_on_importsN




(

z!TestMisc.test_no_procfs_on_importc
Cs8tjddd�� }|jttjj�|js*t�WdQRXdS)Nzpsutil._pslinux.openT)r})	rr�r�r�rZr�r>r�r�)r]r�r-r-r.�test_boot_time_mockedDs

zTestMisc.test_boot_time_mockedcCs�tjdd
gd��&}|jtj�d	jd
�|js2t�WdQRXtjddgd��&}|jtj�d	jd
�|jsnt�WdQRXtjddgd��&}|jtj�d	jd�|js�t�WdQRXdS)Nzpsutil._pslinux.cext.users�	giampaolo�pts/2�:0��h�ATr�)r�rZ	localhost�:0.0�foo)rJrKrLrMTr�)rJrKrNrMTr�)rJrKrOrMTr�)rr�r�rZZusers�hostr�r�)r]r�r-r-r.�test_users_mockedKszTestMisc.test_users_mockedcCs�tj�}z�|t_|jttj�|jttj�|jttjdd�|jttj�|jttj	�|jttj
�|jttj�|jttj�|jttj
�|jtjtj�Wddt_tj|�XdS)NT)r@z/proc)rArBrZrDr�r�r[r�r>rr	r�r.r Z
NoSuchProcess�Processr��rmdir)r]Ztdirr-r-r.�test_procfs_path_szTestMisc.test_procfs_pathc	sP��fdd�}g�t�trdnd}tj||d��tj��sBt�WdQRXdS)NcsJtrt|t�r|j�}d|kr6�jd�ttjd��n�|f|�|�SdS)NZhw_sector_sizer2)r�
isinstancer �decoder�r�r�r�)rxryrz)�flagr{r-r.r|us
z1TestMisc.test_sector_size_mock.<locals>.open_mockz
builtins.openz__builtin__.open)r~)r�rrr�rZr.r�)r]r|r�r-)rWr{r.�test_sector_size_mockrs	zTestMisc.test_sector_size_mockc
Csnt�}|j�zPtj�}|j�dj}tj|�s:t|��tj|�}|j�|j	|tj
��Wd|j�XdS)Nr7)r�startrZrR�threads�id�
pid_existsr�Zas_dictr�Zpids�stop)r]�t�p�tidZptr-r-r.�test_issue_687�s
zTestMisc.test_issue_687c	sL�fdd�}t�trdnd}tj||d��tjtj��s>t�WdQRXdS)Ncs2|dtj�krtjtd��S�|f|�|�SdS)Nz/proc/%s/statusr2)r��getpidrsrr)rxryrz)r{r-r.r|�sz:TestMisc.test_pid_exists_no_proc_status.<locals>.open_mockz
builtins.openz__builtin__.open)r~)	r�rrr�rZr\r�rbr�)r]r|r�r-)r{r.�test_pid_exists_no_proc_status�s
z'TestMisc.test_pid_exists_no_proc_statusN)
r�r�r�r?rr�rHrIrQrTrXrarcr-r-r-r.r=�s>r=z
no batteryc@s�eZdZejed�d�dd��Zejed�d�dd��Zdd�Zd	d
�Z	dd�Z
d
d�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdS)�TestSensorsBatteryZacpizacpi utility not availablecCsDtd�}t|jd�dj�jdd��}tj�j}|j||dd�dS)Nzacpi -b�,r7�%r2)rc)	rrDr@rR�replacerZ�sensors_battery�percentr\)r]rFZ
acpi_valuer_r-r-r.�test_percent�s
zTestSensorsBattery.test_percentcCsTtd�}d|j�krtjd�Sd|kr,d}nd|jd�dk}|jtj�j|�dS)	Nzacpi -b�unknownzacpi output not reliablezdischarging at zero rateTZChargingr>r)	r�lowerrr�r@r�rZrh�
power_plugged)r]rFZpluggedr-r-r.�test_power_plugged�s
z%TestSensorsBattery.test_power_pluggedc
sj�fdd�}t�trdnd}tj||d��6}|jtj�jd�|jtj�jtj	�|j
s\t�WdQRXdS)Ncs2|jd�s|jd�rtjd�S�|f|�|�SdS)Nz
AC0/onlinez	AC/online�1)r�rsrt)rxryrz)r{r-r.r|�s
z@TestSensorsBattery.test_emulate_power_plugged.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)r�rrr�r�rZrhrmZsecsleftZPOWER_TIME_UNLIMITEDr�r�)r]r|r�r�r-)r{r.�test_emulate_power_plugged�sz-TestSensorsBattery.test_emulate_power_pluggedc
sV�fdd�}t�trdnd}tj||d��"}|jtj�jd�|jsHt	�WdQRXdS)NcsN|jd�s|jd�r"ttjd��n(|jd�r:tjtd��S�|f|�|�SdS)Nz
AC0/onlinez	AC/onliner2z/statusZcharging)r�r�r�r�rsrr)rxryrz)r{r-r.r|�s

zBTestSensorsBattery.test_emulate_power_plugged_2.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)
r�rrr�r�rZrhrmr�r�)r]r|r�r�r-)r{r.�test_emulate_power_plugged_2�sz/TestSensorsBattery.test_emulate_power_plugged_2c
sV�fdd�}t�trdnd}tj||d��"}|jtj�jd�|jsHt	�WdQRXdS)Ncs2|jd�s|jd�rtjd�S�|f|�|�SdS)Nz
AC0/onlinez	AC/online�0)r�rsrt)rxryrz)r{r-r.r|�s
zDTestSensorsBattery.test_emulate_power_not_plugged.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)
r�rrr�r�rZrhrmr�r�)r]r|r�r�r-)r{r.�test_emulate_power_not_plugged�sz1TestSensorsBattery.test_emulate_power_not_pluggedc
sV�fdd�}t�trdnd}tj||d��"}|jtj�jd�|jsHt	�WdQRXdS)NcsN|jd�s|jd�r"ttjd��n(|jd�r:tjtd��S�|f|�|�SdS)Nz
AC0/onlinez	AC/onliner2z/statusZdischarging)r�r�r�r�rsrr)rxryrz)r{r-r.r|�s

zFTestSensorsBattery.test_emulate_power_not_plugged_2.<locals>.open_mockz
builtins.openz__builtin__.open)r~F)
r�rrr�r�rZrhrmr�r�)r]r|r�r�r-)r{r.� test_emulate_power_not_plugged_2�sz3TestSensorsBattery.test_emulate_power_not_plugged_2c	sT�fdd�}t�trdnd}tj||d�� }|jtj�j�|jsFt	�WdQRXdS)NcsJ|jd�s|jd�r"ttjd��n$|jd�r6tjd�S�|f|�|�SdS)Nz"/sys/class/power_supply/AC0/onlinez!/sys/class/power_supply/AC/onliner2z#/sys/class/power_supply/BAT0/statuss???)rAr�r�r�rsrt)rxryrz)r{r-r.r|s



zETestSensorsBattery.test_emulate_power_undetermined.<locals>.open_mockz
builtins.openz__builtin__.open)r~)
r�rrr�r�rZrhrmr�r�)r]r|r�r�r-)r{r.�test_emulate_power_undetermineds	z2TestSensorsBattery.test_emulate_power_undeterminedc	sR�fdd�}t�trdnd}tj||d��}|jtj��|jsDt�WdQRXdS)Ncs6|jd�s|jd�r"ttjd��n�|f|�|�SdS)Nz'/sys/class/power_supply/BAT0/energy_nowz'/sys/class/power_supply/BAT0/charge_nowr2)rAr�r�r�)rxryrz)r{r-r.r|s

z@TestSensorsBattery.test_emulate_no_base_files.<locals>.open_mockz
builtins.openz__builtin__.open)r~)	r�rrr�r�rZrhr�r�)r]r|r�r�r-)r{r.�test_emulate_no_base_filessz-TestSensorsBattery.test_emulate_no_base_filesc
sV�fdd�}t�trdnd}tj||d��"}|jtj�jd�|jsHt	�WdQRXdS)Ncs(|jd�rtjd�S�|f|�|�SdS)Nz(/sys/class/power_supply/BAT0/energy_fullrr)rArsrt)rxryrz)r{r-r.r|&s

z@TestSensorsBattery.test_emulate_energy_full_0.<locals>.open_mockz
builtins.openz__builtin__.open)r~r)
r�rrr�r�rZrhrir�r�)r]r|r�r�r-)r{r.�test_emulate_energy_full_0$sz-TestSensorsBattery.test_emulate_energy_full_0c
sV�fdd�}t�trdnd}tj||d��"}|jtj�jd�|jsHt	�WdQRXdS)NcsRd}d}|j|�s|j|�r*ttjd��n$|jd�r>tjd�S�|f|�|�SdS)Nz(/sys/class/power_supply/BAT0/energy_fullz(/sys/class/power_supply/BAT0/charge_fullr2z%/sys/class/power_supply/BAT0/capacitys88)rAr�r�r�rsrt)rxryrzZenergy_fullZcharge_full)r{r-r.r|5s

zHTestSensorsBattery.test_emulate_energy_full_not_avail.<locals>.open_mockz
builtins.openz__builtin__.open)r~�X)
r�rrr�r�rZrhrir�r�)r]r|r�r�r-)r{r.�"test_emulate_energy_full_not_avail2s
z5TestSensorsBattery.test_emulate_energy_full_not_availc	sD�fdd�}tjj�tjd|d��}tj�|js6t�WdQRXdS)Ncs|jd�rdS�|�SdS)Nz"/sys/class/power_supply/AC0/onlineF)rA)rx)�orig_path_existsr-r.�path_exists_mockGs
zGTestSensorsBattery.test_emulate_no_ac0_online.<locals>.path_exists_mockzpsutil._pslinux.os.path.exists)r~)	r�r�r�rr�rZrhr�r�)r]r{r�r-)rzr.�test_emulate_no_ac0_onlineEs
z-TestSensorsBattery.test_emulate_no_ac0_onlinec	sT�fdd�}t�trdnd}tj||d�� }|jtj�j�|jsFt	�WdQRXdS)Ncs@|jd�s|jd�s|jd�r,ttjd��n�|f|�|�SdS)Nz!/sys/class/power_supply/AC/onlinez"/sys/class/power_supply/AC0/onlinez#/sys/class/power_supply/BAT0/statusr2)rAr�r�r�)rxryrz)r{r-r.r|Us



z;TestSensorsBattery.test_emulate_no_power.<locals>.open_mockz
builtins.openz__builtin__.open)r~)
r�rrr�r�rZrhrmr�r�)r]r|r�r�r-)r{r.�test_emulate_no_powerSsz(TestSensorsBattery.test_emulate_no_powerN)r�r�r�rr�rrjrnrprqrsrtrurvrwryr|r}r-r-r-r.rd�srdc@s(eZdZejed�dd��Zdd�ZdS)�TestSensorsTemperatureszunreliable on TRAVIScs��fdd�}t�trdnd}tj||d��N}tjdd��6}|jtj�i�|j	sTt
�|jdt|d	j
��WdQRXWdQRXdS)
Ncs,|jd�rttjd��n�|f|�|�SdS)NZ_inputr2)r��OSErrorr�ZEIO)rxryrz)r{r-r.r|is
zATestSensorsTemperatures.test_emulate_eio_error.<locals>.open_mockz
builtins.openz__builtin__.open)r~T)rZignoringr)r�rrr�r�r�r�rZ�sensors_temperaturesr�r�r�r�r�)r]r|r�r�r�r-)r{r.�test_emulate_eio_errorgs
z.TestSensorsTemperatures.test_emulate_eio_errorcs��fdd�}t�trdnd}tj||d��jtjddgd��Ntj�d	d
}|j|jd�|j|jd�|j|j	d
�|j|j
d�WdQRXWdQRXdS)Ncs�|jd�rtjtd��S|jd�r0tjtd��S|jd�rDtjd�S|jd�rXtjd�S|jd	�rltjd
�S�|f|�|�SdS)Nz/namerxz/temp1_label�labelz/temp1_inputs30000z
/temp1_maxs40000z/temp1_crits50000)r�rsrrrt)rxryrz)r{r-r.r|xs







z<TestSensorsTemperatures.test_emulate_data.<locals>.open_mockz
builtins.openz__builtin__.open)r~z	glob.globz/sys/class/hwmon/hwmon0/temp1)r�rxrr�g>@gD@gI@)r�rrr�rZr�r�r�r�ZhighZcritical)r]r|r�Ztempr-)r{r.�test_emulate_datawsz)TestSensorsTemperatures.test_emulate_dataN)r�r�r�rr�rr�r�r-r-r-r.r~dsr~c@seZdZdd�ZdS)�TestSensorsFanscs��fdd�}t�trdnd}tj||d��Ntjddgd��2tj�d	d
}|j|jd�|j|jd�WdQRXWdQRXdS)
Ncs\|jd�rtjtd��S|jd�r0tjtd��S|jd�rHtjtd��S�|f|�|�SdS)Nz/namerxz/fan1_labelr�z/fan1_inputZ2000)r�rsrr)rxryrz)r{r-r.r|�s


z4TestSensorsFans.test_emulate_data.<locals>.open_mockz
builtins.openz__builtin__.open)r~z	glob.globz/sys/class/hwmon/hwmon2/fan1)r�rxrr�i�)	r�rrr�rZZsensors_fansr�r�r�)r]r|r�Zfanr-)r{r.r��s
z!TestSensorsFans.test_emulate_dataN)r�r�r�r�r-r-r-r.r��sr�c@s�eZdZdd�ZeZdd�Zejed�dd��Z	dd	�Z
d
d�Zdd
�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zejed�dd��Zdd�Zdd �Zd!d"�Zd#S)$�TestProcesscCstt�dS)N)rr)r]r-r-r.�setUp�szTestProcess.setUpcCs�tjdt�}t|�}|jt�tdd�dt�tj|j	�}t
jd�|j�}|j
dd�}|j|jtdd	�|D��d
d�|j|jtdd	�|D��d
d�|j|jtd
d	�|D��d
d�dS)Nzk
            import time
            with open("%s", "w") as f:
                time.sleep(10)
            cSs
tjd�S)NrU)r�r�r-r-r-r.�<lambda>�sz3TestProcess.test_memory_full_info.<locals>.<lambda>z'%s' not in retg�������?F)ZgroupedcSsg|]}|j|j�qSr-)Z
private_dirtyZ
private_clean)r3r0r-r-r.r5�sz5TestProcess.test_memory_full_info.<locals>.<listcomp>i)rccSsg|]
}|j�qSr-)�pss)r3r0r-r-r.r5�scSsg|]
}|j�qSr-)r�)r3r0r-r-r.r5�s)rurvrr
rrrrZrR�pid�timeZsleepZmemory_full_info�memory_mapsr\ZussrEr�r�)r]�srcZsprocr_Zmem�mapsr-r-r.�test_memory_full_info�s 


z!TestProcess.test_memory_full_infozunreliable on PYPYc;CsRdd�}ttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXttd��|j|�jd�WdQRXt�rNtt�ttd	��|j|�jd�WdQRXtt�ttd
��|j|�jd�WdQRXdS)NcSs\tj�}tj�d}x:x4|j�D](}|jtjjt�kr:|Stj�|kr Pq WqWtd��dS)Nr�ztimeout looking for test file)	rZrRr��
open_filesr�r��abspathrr�)r_Z	giveup_at�filer-r-r.�
get_test_file�s
z7TestProcess.test_open_files_mode.<locals>.get_test_filer�r$r�zr+zw+za+r0zx+)r�rr��moderr)r]r�r-r-r.�test_open_files_mode�s(z TestProcess.test_open_files_modecCs�tj�}|j�}tj���t|jdt|��tjdt	t
jd�d��"}|j�}|sXt�|j
sbt�WdQRXtjdt	t
jd�d�� }|j|j�g�|j
s�t�WdQRXWdQRXdS)Nzlen(ret) != %izpsutil._pslinux.os.readlinkr2)r~)rZrRr�rA�NamedTemporaryFilerr�rr�rr�r�r�r�ZEINVALr�)r]r_�filesr�r-r-r.�test_open_files_file_gone�s

z%TestProcess.test_open_files_file_gonecCs�tj�}|j�}tj��dt|jdt|��tr6dnd}tj	|t
tjd�d��"}|j�}|sdt
�|jsnt
�WdQRXWdQRXdS)Nzlen(ret) != %iz
builtins.openz__builtin__.openr2)r~)rZrRr�rAr�rr�rrr�r�r�r�r�r�)r]r_r�r�r�r-r-r.�test_open_files_fd_gones

z#TestProcess.test_open_files_fd_gonec
CsBtjdid��*}|jtjjtj��j��|j	s4t
�WdQRXdS)Nz)psutil._pslinux._psposix.get_terminal_map)r�)rr�r�rZr�rRr�rbZterminalr�r�)r]r�r-r-r.�test_terminal_mockeds
z TestProcess.test_terminal_mockedcCs�tj�}tjtd��}tjd|dd��$}|j|j�ddg�|j	sFt
�WdQRXtjtd��}tjd|dd��&}|j|j�dddg�|j	s�t
�WdQRXdS)	Nzfoobarzpsutil._pslinux.openT)r�r}rO�barz	foobarr2)rZrRrsrrrr�r��cmdliner�r�)r]r_r�r�r-r-r.�test_cmdline_mocked%szTestProcess.test_cmdline_mockedcCs�tj�}tjtd��}tjd|dd��$}|j|j�ddg�|j	sFt
�WdQRXtjtd��}tjd|dd��&}|j|j�dddg�|j	s�t
�WdQRXdS)	Nzfoo bar zpsutil._pslinux.openT)r�r}rOr�z	foo bar  r2)rZrRrsrrrr�r�r�r�r�)r]r_r�r�r-r-r.�test_cmdline_spaces_mocked3sz&TestProcess.test_cmdline_spaces_mockedc
CsFtjddd��.|jtj�j�d�|jtj�j�d�WdQRXdS)Nzpsutil._pslinux.os.readlinkz/home/foo (deleted))r�z	/home/foo)rr�r�rZrR�exe�cwd)r]r-r-r.�!test_readlink_path_deleted_mockedAs
z-TestProcess.test_readlink_path_deleted_mockedcs��fdd�}t�trdnd}tj||d��(}tj�j�}|jsBt�|j	|g�WdQRX�fdd�}tj||d��|j
tjtj�j�WdQRXdS)Ncs4|jdtj��r ttjd��n�|f|�|�SdS)Nz
/proc/%s/taskr2)rAr�rbr�r�r�)rxryrz)r{r-r.r|Lsz2TestProcess.test_threads_mocked.<locals>.open_mockz
builtins.openz__builtin__.open)r~cs4|jdtj��r ttjd��n�|f|�|�SdS)Nz
/proc/%s/taskr2)rAr�rbr�r�ZEPERM)rxryrz)r{r-r.r|[s)r�rrr�rZrRrZr�r�r�r��AccessDenied)r]r|r�r�r�r-)r{r.�test_threads_mockedGs
zTestProcess.test_threads_mockedcCs�tjdttjd�d���}tjdtjdd�d��`}tj�j�}|j	sFt
�|j	sPt
�|j|d�tjddd��|jtj
tj�j�WdQRXWdQRXWdQRXdS)	Nzpsutil._pslinux.readlinkr2)r~zpsutil.Process.cmdlinerzpsutil._pslinux.os.path.lexistsF)r�)rr�rr�r�rZr�rRr�r�r�r�r��
ZombieProcess)r]r)r*r�r-r-r.�test_exe_mockedds


zTestProcess.test_exe_mockedcs|�fdd�}t�trdnd}tj||d��H}tj�}|jt��}|j�WdQRX|j	|j
jtj�|j
snt�WdQRXdS)Ncs4|jdtj��r ttjd��n�|f|�|�SdS)Nz/proc/%s/smapsr2)rAr�rbr�r�r�)rxryrz)r{r-r.r||sz.TestProcess.test_issue_1014.<locals>.open_mockz
builtins.openz__builtin__.open)r~)r�rrr�rZrRr�r�r�r��	exceptionr�r�r�r�)r]r|r�r�r_�errr-)r{r.�test_issue_1014yszTestProcess.test_issue_1014z
not supportedcCs�tjdttjd�d��D}tj�}|j�|jtj	��}|j
tj�WdQRX|jsVt
�WdQRX|j|jj|j�|j|jj|j��dS)Nz"psutil._pslinux.cext.linux_prlimitr2)r~)rr�rr�ZENOSYSrZrRrxr�r�ZrlimitZ
RLIMIT_NOFILEr�r�r�r�r�)r]r�r_�excr-r-r.�test_rlimit_zombie�szTestProcess.test_rlimit_zombiecCs�tjdttjd�d��@}tj�}|j�|jtj	��}|j
�WdQRX|jsRt�WdQRX|j
|jj|j�|j
|jj|j��dS)Nzpsutil._pslinux.os.readlinkr2)r~)rr�rr�r�rZrRrxr�r�r�r�r�r�r�r�)r]r�r_r�r-r-r.�test_cwd_zombie�szTestProcess.test_cwd_zombiecs�ddlm}�fdd�}t�tr$dnd}tj||d���tj�}|j|j	�d�|j|j
�tj�|j|j�d	�|j|j
�d
|tj��|j�}|j|jd|�|j|jd|�|j|jd
|�|j|jd|�|j|j�d
�WdQRXdS)Nr)�CLOCK_TICKSc's�|jdtj��rxddddddddddddddddd	ddddd
ddddddddddddddddd
g'}tjdj|�j��S�|f|�|�SdS)Nz
/proc/%s/stat�0z(cat)�Z�1�2�3�4�5�6rQ)rAr�rbrsrtr;rw)rxryrz)r{r-r.r|�sTz5TestProcess.test_stat_file_parsing.<locals>.open_mockz
builtins.openz__builtin__.open)r~�catr7r�r�rarrN)r�r�r�rrr�rZrRr�rx�statusZ
STATUS_ZOMBIE�ppidZcreate_timer>r��user�system�
children_user�children_systemZcpu_num)r]r�r|r�r_Zcpur-)r{r.�test_stat_file_parsing�s"/z"TestProcess.test_stat_file_parsingc
s��fdd�}t�trdnd}tj||d���tj�}|j|j�jd�|j|j�j	d�|j|j
�d�|j�}|j|jd	�|j|j
d
�|j|jd�|j�}|j|jd�|j|j
d
�|j|jd�|j|jj�ttdd���WdQRXdS)Ncs:|jdtj��r&tjtjd�j��S�|f|�|�SdS)Nz/proc/%s/statusa+                    Uid:	1000	1001	1002	1003
                    Gid:	1004	1005	1006	1007
                    Threads:	66
                    Cpus_allowed:	f
                    Cpus_allowed_list:	0-7
                    voluntary_ctxt_switches:	12
                    nonvoluntary_ctxt_switches:	13)rAr�rbrsrtrurvrw)rxryrz)r{r-r.r|�sz7TestProcess.test_status_file_parsing.<locals>.open_mockz
builtins.openz__builtin__.open)r~rb�
�Bi�i�i�i�i�i�rr-)r�rrr�rZrRr��num_ctx_switches�	voluntary�involuntary�num_threads�uids�realZ	effectiveZsaved�gids�_proc�_get_eligible_cpus�list�range)r]r|r�r_r�r�r-)r{r.�test_status_file_parsing�s"
z$TestProcess.test_status_file_parsingN)r�r�r�r�ZtearDownr�rr�rr�r�r�r�r�r�r�r�r�r�r	r�r�r�r�r-r-r-r.r��s"$Br�c@sreZdZdZedd��Zdd�Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Ze
�dd��Zdd�Zdd�ZdS)�TestProcessAgainstStatusa/proc/pid/stat and /proc/pid/status have many values in common.
    Whenever possible, psutil uses /proc/pid/stat (it's faster).
    For all those cases we check that the value found in
    /proc/pid/stat (by psutil) matches the one found in
    /proc/pid/status.
    cCstj�|_dS)N)rZrR�proc)�clsr-r-r.�
setUpClasssz#TestProcessAgainstStatus.setUpClasscCs|tjjd|jj��^}xJ|D]B}|j�}|j|�r|jd�d}yt|�St	k
r\|SXqWt	d|��WdQRXdS)Nz/proc/%s/status�	r�z
can't find %r)
rZ�_psplatform�	open_textr�r�rRrA�	partitionrDrE)r]Z	linestartr�rHr�r-r-r.�read_status_files


z)TestProcessAgainstStatus.read_status_filecCs |jd�}|j|jj�|�dS)NzName:)r�r�r�rx)r]r�r-r-r.�	test_name!s
z"TestProcessAgainstStatus.test_namecCsH|jd�}||jd�d|jd��}|jdd�}|j|jj�|�dS)NzState:�(r7�)rQr�)r��find�rfindrgr�r�r�)r]r�r-r-r.�test_status%s
z$TestProcessAgainstStatus.test_statuscCs |jd�}|j|jj�|�dS)NzPPid:)r�r�r�r�)r]r�r-r-r.�	test_ppid+s
z"TestProcessAgainstStatus.test_ppidcCs |jd�}|j|jj�|�dS)NzThreads:)r�r�r�r�)r]r�r-r-r.�test_num_threads/s
z)TestProcessAgainstStatus.test_num_threadscCs:|jd�}ttt|j�dd���}|j|jj�|�dS)NzUid:r7r)r�rVrWrDr@r�r�r�)r]r�r-r-r.�	test_uids3s
z"TestProcessAgainstStatus.test_uidscCs:|jd�}ttt|j�dd���}|j|jj�|�dS)NzGid:r7r)r�rVrWrDr@r�r�r�)r]r�r-r-r.�	test_gids8s
z"TestProcessAgainstStatus.test_gidscCs@|jd�}|j|jj�j|�|jd�}|j|jj�j|�dS)Nzvoluntary_ctxt_switches:znonvoluntary_ctxt_switches:)r�r�r�r�r�r�)r]r�r-r-r.�test_num_ctx_switches=s

z.TestProcessAgainstStatus.test_num_ctx_switchescCsN|jd�}dt|�krJtt|jd��\}}|j|jj�tt	||d���dS)NzCpus_allowed_list:r�r7)
r�r�rWrDr@r�r�Zcpu_affinityr�r�)r]r�Zmin_Zmax_r-r-r.�test_cpu_affinityDs

z*TestProcessAgainstStatus.test_cpu_affinityc
CsT|jd�}tjd��}|jjj�WdQRXdt|�krF|jsPt�n
|jsPt�dS)NzCpus_allowed_list:zpsutil._pslinux.per_cpu_timesr�)	r�rr�r�r�r�r�r�r�)r]r�r�r-r-r.�test_cpu_affinity_eligible_cpusKs
z8TestProcessAgainstStatus.test_cpu_affinity_eligible_cpusN)r�r�r��__doc__�classmethodr�r�r�r�r�r�r�r�rr�r�r�r-r-r-r.r�s
r�c@s,eZdZdd�Zdd�Zdd�Zdd�Zd	S)
�	TestUtilsc
Cs*tjjt��}|j|jd�WdQRXdS)NZrt)rZr�r��__file__r�r�)r]r�r-r-r.�test_open_text]szTestUtils.test_open_textc
Cs*tjjt��}|j|jd�WdQRXdS)Nr�)rZr�r�r�r�r�)r]r�r-r-r.�test_open_binaryaszTestUtils.test_open_binaryc
Cs<tjddd��$}|jtjjd�d�|js.t�WdQRXdS)Nzos.readlinkz
foo (deleted))r�r�rO)rr�r�rZr��readlinkr�r�)r]r�r-r-r.�
test_readlinkeszTestUtils.test_readlinkcCs|tjjt�}t|d��}|jd�WdQRX|jtjj	tdd�d�|jtjj	tdd�d�|jtjj	tdd	d
�d	�dS)NZwtzfoo F)ZbinaryrOTsfooz??r�)Zfallback)
r�r�r�rr�rCr�rZr�r�)r]Zfnamer�r-r-r.�test_catjszTestUtils.test_catN)r�r�r�r�r�r�r�r-r-r-r.r�Zsr��__main__)Kr�Z
__future__rrBr$r�r�rsr�r
r�rFr!r)rArur�r�rZrZpsutil._compatrrZpsutil.testsrrrr	r
rrr
rrrrrrrrrrrrr�r��dirnamer�ZHEREr(ZSIOCGIFCONFr9r2r/r=rMrPrTrXr�ZTestCaserYr�r�r�r�rr=rdr~r�r�r�r�r�r-r-r-r.�<module>s�
	


k
T

t

.7
-

Y
R

tests/__pycache__/test_osx.cpython-36.pyc000064400000025051150466730550014432 0ustar003

��JZ�%�@s<dZddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddlm
Z
ddlmZdd	lmZdd
lm
Z
ddlmZddlmZer�ejd
�ndZdd�Zdd�Zdd�Zejed�Gdd�dej��Zejed�Gdd�dej��Zejed�Gdd�dej��Zedk�r8e
e�dS)zOSX specific tests.�N)�OSX)�create_zombie_proc)�get_test_subprocess)�HAS_BATTERY)�MEMORY_TOLERANCE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�unittest�SC_PAGE_SIZEcCs6t|�}|j�d}yt|�Stk
r0|SXdS)zmExpects a sysctl command with an argument and parse the result
    returning only the value of interest.
    �N)r
�split�int�
ValueError)�cmdline�out�result�r� /usr/lib64/python3.6/test_osx.py�sysctlsrcCsHtd�}x$|jd�D]}||krPqWtd��ttjd|�jd��tS)z)Wrapper around 'vm_stat' cmdline utility.�vm_stat�
zline not foundz\d+r)r
rrr�re�search�group�PAGESIZE)Zfieldr�linerrrr(src	
Cs�ddi}|}d}x@|r&|dd
�j�s6|dd
�dkrP||d7}|d
d�}qWt|�}|j�}xD|j�D]\}}||krlPqlW|dkr�|d}|j�}ntd|��|dd
i}x0t|d
d��D]\}}d
|d
d>||<q�Wt|||�S)NZ	customary�B�K�M�G�T�P�E�Z�Y�rr
�.�kzcan't interpret %r�
)	rrr r!r"r#r$r%r&)�isdigit�float�strip�items�upperr�	enumerater)	�sZSYMBOLSZinit�numZletter�nameZsset�prefix�irrr�human2bytes4s&&
r6zOSX onlyc@s,eZdZedd��Zedd��Zdd�ZdS)�TestProcesscCst�j|_dS)N)r�pid)�clsrrr�
setUpClassQszTestProcess.setUpClasscCs
t�dS)N)r)r9rrr�
tearDownClassUszTestProcess.tearDownClasscCs�td|j�}|jdd�j�}|jd�d	}|jd�d
}tj|j�j�}|j|t	j
dt	j|���|j|t	j
dt	j|���dS)Nzps -o lstart -p %sZSTARTEDr'� �r
z%H:%M:%Sz%Y������)r
r8�replacer-r�psutil�Process�create_time�assertEqual�timeZstrftimeZ	localtime)�self�outputZstart_psZhhmmssZyearZstart_psutilrrr�test_process_create_timeYsz$TestProcess.test_process_create_timeN)�__name__�
__module__�__qualname__�classmethodr:r;rHrrrrr7Nsr7c@s�eZdZedd��Zedd��Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!S)"�TestZombieProcessAPIscCst�}tj|�|_dS)N)rrArB�p)r9Zzpidrrrr:jsz TestZombieProcessAPIs.setUpClasscCstdd�dS)NT)�	recursive)r)r9rrrr;osz#TestZombieProcessAPIs.tearDownClasscCsJ|j|jj�tj�|jj�|jj�|jj�|jj�|jj	�dS)N)
rDrNZstatusrAZ
STATUS_ZOMBIEZppidZuidsZgidsZterminalrC)rFrrr�test_pidtask_infoss



z'TestZombieProcessAPIs.test_pidtask_infocCs|jtj|jj�dS)N)�assertRaisesrA�
ZombieProcessrNZexe)rFrrr�test_exe{szTestZombieProcessAPIs.test_execCs|jtj|jj�dS)N)rQrArRrNr)rFrrr�test_cmdline~sz"TestZombieProcessAPIs.test_cmdlinecCs|jtj|jj�dS)N)rQrArRrN�environ)rFrrr�test_environ�sz"TestZombieProcessAPIs.test_environcCs|jtj|jj�dS)N)rQrArRrN�cwd)rFrrr�test_cwd�szTestZombieProcessAPIs.test_cwdcCs|jtj|jj�dS)N)rQrArRrNZmemory_full_info)rFrrr�test_memory_full_info�sz+TestZombieProcessAPIs.test_memory_full_infocCs|jtj|jj�dS)N)rQrArRrNZ	cpu_times)rFrrr�test_cpu_times�sz$TestZombieProcessAPIs.test_cpu_timescCs|jtj|jj�dS)N)rQrArRrNZnum_ctx_switches)rFrrr�test_num_ctx_switches�sz+TestZombieProcessAPIs.test_num_ctx_switchescCs|jtj|jj�dS)N)rQrArRrNZnum_threads)rFrrr�test_num_threads�sz&TestZombieProcessAPIs.test_num_threadscCs|jtj|jj�dS)N)rQrArRrNZ
open_files)rFrrr�test_open_files�sz%TestZombieProcessAPIs.test_open_filescCs|jtj|jj�dS)N)rQrArRrNZconnections)rFrrr�test_connections�sz&TestZombieProcessAPIs.test_connectionscCs|jtj|jj�dS)N)rQrArRrNZnum_fds)rFrrr�test_num_fds�sz"TestZombieProcessAPIs.test_num_fdscCs|jtjtjf|jj�dS)N)rQrArRZAccessDeniedrNZthreads)rFrrr�test_threads�sz"TestZombieProcessAPIs.test_threadscCs|jtj|jj�dS)N)rQrArRrNZmemory_maps)rFrrr�test_memory_maps�sz&TestZombieProcessAPIs.test_memory_mapsN)rIrJrKrLr:r;rPrSrTrVrXrYrZr[r\r]r^r_r`rarrrrrMgs rMc@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Ze�dd��Z	e�d
d��Z
e�dd��Ze�dd��Ze�dd��Z
e�dd��Ze�dd��Zdd�Zejed�dd��ZdS)�TestSystemAPIscCs�dd�}x�tjdd�D]�}tj|j�}||j�\}}}}|j|j|�|j|j|�t|j|�d	krx|j	d|j|�t|j
|�dkr|j	d|j
|�qWdS)NcSs�td|�j�}|jd�}|jd�|jd�}|j�dd�\}}}}|dkrRd}t|�d}t|�d}t|�d}||||fS)Nz
df -k "%s"rr�Znoner'i)r
r-r�popr)�pathr�linesr�dev�total�used�freerrr�df�s


z%TestSystemAPIs.test_disks.<locals>.dfF)�allr*izpsutil=%s, df=%si(i�i(i�)rAZdisk_partitionsZ
disk_usageZ
mountpointrDZdevicerh�absrjZfailri)rFrk�partZusagergrhrirjrrr�
test_disks�s
zTestSystemAPIs.test_diskscCs td�}|j|tjdd��dS)Nzsysctl hw.logicalcpuT)�logical)rrDrA�	cpu_count)rFr2rrr�test_cpu_count_logical�sz%TestSystemAPIs.test_cpu_count_logicalcCs td�}|j|tjdd��dS)Nzsysctl hw.physicalcpuF)rp)rrDrArq)rFr2rrr�test_cpu_count_physical�sz&TestSystemAPIs.test_cpu_count_physicalcCsZtj�}|j|jddtd��|j|jddtd��|j|jddtd��dS)Ni�zsysctl hw.cpufrequencyzsysctl hw.cpufrequency_minzsysctl hw.cpufrequency_max)rAZcpu_freqrDZcurrentr�min�max)rFZfreqrrr�
test_cpu_freq�szTestSystemAPIs.test_cpu_freqcCstd�}|j|tj�j�dS)Nzsysctl hw.memsize)rrDrA�virtual_memoryrh)rFZsysctl_hwphymemrrr�test_vmem_total�szTestSystemAPIs.test_vmem_totalcCs&td�}tj�j}|j||td�dS)Nrj)�delta)rrArwrj�assertAlmostEqualr)rF�
vmstat_val�
psutil_valrrr�test_vmem_free�s
zTestSystemAPIs.test_vmem_freecCs.td�td�}tj�j}|j||td�dS)N�inactiverj)ry)rrArwZ	availablerzr)rFr{r|rrr�test_vmem_available�s
z"TestSystemAPIs.test_vmem_availablecCs&td�}tj�j}|j||td�dS)N�active)ry)rrArwr�rzr)rFr{r|rrr�test_vmem_active�s
zTestSystemAPIs.test_vmem_activecCs&td�}tj�j}|j||td�dS)Nr~)ry)rrArwr~rzr)rFr{r|rrr�test_vmem_inactive�s
z!TestSystemAPIs.test_vmem_inactivecCs&td�}tj�j}|j||td�dS)N�wired)ry)rrArwr�rzr)rFr{r|rrr�test_vmem_wired�s
zTestSystemAPIs.test_vmem_wiredcCs"td�}tj�j}|j||�dS)NZPageins)rrA�swap_memoryZsinrD)rFr{r|rrr�test_swapmem_sin�s
zTestSystemAPIs.test_swapmem_sincCs"td�}tj�j}|j||�dS)NZPageout)rrAr�ZsoutrD)rFr{r|rrr�test_swapmem_souts
z TestSystemAPIs.test_swapmem_soutcCsxxrtj�j�D]b\}}ytd|�}Wntk
r:YqX|j|jd|k|d�|j|jtt	j
d|�d��qWdS)Nzifconfig %sZRUNNING)�msgz	mtu (\d+)r)rAZnet_if_statsr.r
�RuntimeErrorrDZisupZmturr�findall)rFr3Zstatsrrrr�test_net_if_statssz TestSystemAPIs.test_net_if_statsz
no batterycCs`td�}tjd|�jd�}tjd|�jd�}|dk}tj�}|j|j|�|j|jt	|��dS)Nz
pmset -g battz(\d+)%r
zNow drawing from '([^']+)'zAC Power)
r
rrrrAZsensors_batteryrD�
power_plugged�percentr)rFrr�Zdrawing_fromr�Z
psutil_resultrrr�test_sensors_battery"sz#TestSystemAPIs.test_sensors_batteryN)rIrJrKrorrrsrvrxrr}rr�r�r�r�r�r�r�skipIfrr�rrrrrb�s
rb�__main__)�__doc__�osrrErArZpsutil.testsrrrrrrr	r
r�sysconfrrrr6r�ZTestCaser7rMrbrI�__file__rrrr�<module>s6

<
	
tests/__pycache__/test_unicode.cpython-36.pyc000064400000025672150466730550015260 0ustar003

��JZ[2�@s�dZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddlm
Z
ddlmZdd	lm
Z
dd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&ddlZddlZd!d"�Zd#d$�Z'e
�r�e"j(d%�d&j)d%d'�Z*ne"d(Z*Gd)d*�d*e+�Z,e%j-e	�o�e$d+�e%j-ed,�e%j-e'e#�d-�Gd.d/�d/e,e%j.����Z/e%j-e	�o*e$d+�e%j-e'e*�d0�Gd1d2�d2e,e%j.���Z0e%j-ed3�Gd4d5�d5e%j.��Z1Gd6d7�d7e%j.�Z2e3d8k�r�ee4�dS)9a�
Notes about unicode handling in psutil
======================================

In psutil these are the APIs returning or dealing with a string
('not tested' means they are not tested to deal with non-ASCII strings):

* Process.cmdline()
* Process.connections('unix')
* Process.cwd()
* Process.environ()
* Process.exe()
* Process.memory_maps()
* Process.name()
* Process.open_files()
* Process.username()             (not tested)

* disk_io_counters()             (not tested)
* disk_partitions()              (not tested)
* disk_usage(str)
* net_connections('unix')
* net_if_addrs()                 (not tested)
* net_if_stats()                 (not tested)
* net_io_counters()              (not tested)
* sensors_fans()                 (not tested)
* sensors_temperatures()         (not tested)
* users()                        (not tested)

* WindowsService.binpath()       (not tested)
* WindowsService.description()   (not tested)
* WindowsService.display_name()  (not tested)
* WindowsService.name()          (not tested)
* WindowsService.status()        (not tested)
* WindowsService.username()      (not tested)

In here we create a unicode path with a funky non-ASCII name and (where
possible) make psutil return it back (e.g. on name(), exe(), open_files(),
etc.) and make sure that:

* psutil never crashes with UnicodeDecodeError
* the returned path matches

For a detailed explanation of how psutil handles unicode see:
- https://github.com/giampaolo/psutil/issues/1040
- http://psutil.readthedocs.io/#unicode
�N)�closing)�BSD)�OPENBSD)�OSX)�POSIX)�WINDOWS)�PY3)�u)�APPVEYOR)�ASCII_FS)�bind_unix_socket)�chdir)�copyload_shared_lib)�
create_exe)�get_test_subprocess)�HAS_CONNECTIONS_UNIX)�HAS_ENVIRON)�HAS_MEMORY_MAPS)�mock)�
reap_children)�run_test_module_by_name)�
safe_mkdir)�safe_rmpath)�skip_on_access_denied)�TESTFILE_PREFIX)�TESTFN)�TESTFN_UNICODE)�TRAVIS)�unittest)�unix_socket_pathcCs8tr,yt|�Stk
r(tj�Yq4Xnt|�SdS)N)r
�_safe_rmpathZWindowsError�	traceback�	print_exc)�path�r$�$/usr/lib64/python3.6/test_unicode.pyr\srcCsTtrdSz>y t|�t|�t|gd�Wntk
r>dSXdSWdt�XdS)z`Return True if both the fs and the subprocess module can
    deal with a unicode file name.
    T)�cmdFN)rrrr�UnicodeEncodeErrorr)�namer$r$r%�subprocess_supports_unicodepsr)�utf8sf���surrogateescapeufc@s�eZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
ejed�dd��Zejed�ejed�e�dd����Zdd�Zejed�ejed�dd���ZdS) �_BaseFSAPIsTestsNcCst|j�t|j�dS)N)r�
funky_namer)�clsr$r$r%�
setUpClass�s
z_BaseFSAPIsTests.setUpClasscCst�t|j�dS)N)rrr-)r.r$r$r%�
tearDownClass�sz_BaseFSAPIsTests.tearDownClasscCs
t�dS)N)r)�selfr$r$r%�tearDown�sz_BaseFSAPIsTests.tearDowncCstd��dS)Nzmust be implemented in subclass)�NotImplementedError)r1r$r$r%�expect_exact_path_match�sz(_BaseFSAPIsTests.expect_exact_path_matchcCsHt|jgd�}tj|j�}|j�}|j|t�|j�rD|j	||j�dS)N)r&)
rr-�psutil�Process�pid�exe�assertIsInstance�strr4�assertEqual)r1�subp�pr8r$r$r%�
test_proc_exe�sz_BaseFSAPIsTests.test_proc_execCs�t|jgd�}trRtjdtjtj��d�� }tj	|j
�j�}|jsFt
�WdQRXntj	|j
�j�}|j|t�|j�r�|j|tjj|j��dS)N)r&z psutil._psplatform.cext.proc_exe)�side_effect)rr-rr�patchr5�AccessDenied�os�getpidr6r7r(�called�AssertionErrorr9r:r4r;r#�basename)r1r<�mr(r$r$r%�test_proc_name�sz_BaseFSAPIsTests.test_proc_namecCsXt|jgd�}tj|j�}|j�}x|D]}|j|t�q(W|j�rT|j	||jg�dS)N)r&)
rr-r5r6r7�cmdliner9r:r4r;)r1r<r=rI�partr$r$r%�test_proc_cmdline�s
z"_BaseFSAPIsTests.test_proc_cmdlinec
Csj|jd}|jt|�t|�t|��tj�}|j�}WdQRX|j|j�t	�|j
�rf|j||�dS)N�2)r-�
addCleanuprrr
r5r6�cwdr9r:r4r;)r1�dnamer=rNr$r$r%�
test_proc_cwd�s

z_BaseFSAPIsTests.test_proc_cwdcCs�tj�}t|j��}t|jd��t|j��}WdQRX||j�j}|j|t	�t
rf|rf|jd�S|j�r�|j
tjj|�tjj|j��dS)N�rbzopen_files on BSD is broken)r5r6�setZ
open_files�openr-�popr#r9r:rZskipTestr4r;rB�normcase)r1r=�start�newr#r$r$r%�test_proc_open_files�s

z%_BaseFSAPIsTests.test_proc_open_filesz
POSIX onlycCs�tjj|j�}t|d���}yt|�}Wn&tk
rLtr>�n
tj	d��YnXt
|��8tj�j
d�d}|j|jt�ts�|j|j|�WdQRXWdQRXdS)N)�suffixz
not supported�unixr)rBr#rFr-rrr'rr�SkipTestrr5r6Zconnectionsr9�laddrr:rr;)r1rYr(�sock�connr$r$r%�test_proc_connections�s
z&_BaseFSAPIsTests.test_proc_connectionszcan't list UNIX socketscCs�dd�}tjj|j�}t|d���}yt|�}Wn&tk
rTtrF�n
tj	d��YnXt
|��:tjdd�}t
s�||�}|j|jt�|j|j|�WdQRXWdQRXdS)NcSs2x$|D]}tjj|j�jt�r|SqWtd��dS)Nzconnection not found)rBr#rFr\�
startswithr�
ValueError)�consr^r$r$r%�	find_sock�s
z8_BaseFSAPIsTests.test_net_connections.<locals>.find_sock)rYz
not supportedrZ)Zkind)rBr#rFr-rrr'rrr[rr5Znet_connectionsrr9r\r:r;)r1rcrYr(r]rbr^r$r$r%�test_net_connections�s
z%_BaseFSAPIsTests.test_net_connectionscCs,|jd}|jt|�t|�tj|�dS)NrL)r-rMrrr5Z
disk_usage)r1rOr$r$r%�test_disk_usage	s
z _BaseFSAPIsTests.test_disk_usagez
not supportedz&ctypes does not support unicode on PY2csvt|jd��`}dd���fdd�tj�j�D�}dd�|D�}|j�|�|�x|D]}|j|t�qTWWdQRXdS)N)Z
dst_prefixcSstjjtjj|��S)N)rBr#�realpathrU)r=r$r$r%�normpathsz3_BaseFSAPIsTests.test_memory_maps.<locals>.normpathcsg|]}�|j��qSr$)r#)�.0�x)rgr$r%�
<listcomp>sz5_BaseFSAPIsTests.test_memory_maps.<locals>.<listcomp>cSsg|]}t|kr|�qSr$)r)rhrir$r$r%rjs)rr-r5r6Zmemory_mapsZassertInr9r:)r1Z
funky_pathZlibpathsr#r$)rgr%�test_memory_mapss

z!_BaseFSAPIsTests.test_memory_maps)�__name__�
__module__�__qualname__r-�classmethodr/r0r2r4r>rHrKrPrXr�skipIfrr_rrrdrerrrkr$r$r$r%r,�s"	r,zunreliable on TRAVISzASCII fsz"subprocess can't deal with unicodec@s eZdZdZeZedd��ZdS)�
TestFSAPIsz1Test FS APIs with a funky, valid, UTF8 path name.c
CsNtrdSt|jt�rdntd�}tj��tjd�|jtj	|�kSQRXdS)NT�.�ignore)
r�
isinstancer-r:r	�warnings�catch_warnings�simplefilterrB�listdir)r.�herer$r$r%r4(s

z"TestFSAPIs.expect_exact_path_matchN)rlrmrn�__doc__rr-ror4r$r$r$r%rq srqz*subprocess can't deal with invalid unicodec@s eZdZdZeZedd��ZdS)�TestFSAPIsWithInvalidPathz-Test FS APIs with a funky, invalid path name.cCsdS)NTr$)r.r$r$r%r4<sz1TestFSAPIsWithInvalidPath.expect_exact_path_matchN)rlrmrnrz�INVALID_NAMEr-ror4r$r$r$r%r{5sr{zWINDOWS onlyc@seZdZdd�ZdS)�TestWinProcessNamec
CsFtjdtjtj��d��$}|jtj�j�t	�|j
s8t�WdQRXdS)Nz psutil._psplatform.cext.proc_exe)r?)rr@r5rArBrCr9r6r(r:rDrE)r1rGr$r$r%�test_name_typeEsz!TestWinProcessName.test_name_typeN)rlrmrnr~r$r$r$r%r}Bsr}c@s.eZdZdZdd�Zejed�dd��ZdS)�
TestNonFSAPISz&Unicode tests for non fs-related APIs.cCs
t�dS)N)r)r1r$r$r%r2WszTestNonFSAPIS.tearDownz
not supportedcCs~tjj�}trtnd}||d<t|d�}tj|j�}|j�}x,|j	�D] \}}|j
|t�|j
|t�qFW|j|d|�dS)N�èZ	FUNNY_ARG)�env)
rB�environ�copyrrrr5r6r7�itemsr9r:r;)r1r�Z	funky_strZsprocr=�k�vr$r$r%�test_proc_environZs

zTestNonFSAPIS.test_proc_environN)	rlrmrnrzr2rrprr�r$r$r$r%rTsr�__main__)5rzrBr!ru�
contextlibrr5rrrrrZpsutil._compatrr	Zpsutil.testsr
rrr
rrrrrrrrrrrr rrrrrrrr)�encode�decoder|�objectr,rpZTestCaserqr{r}rrl�__file__r$r$r$r%�<module>4sr




tests/__pycache__/test_memory_leaks.cpython-36.pyc000064400000052742150466730550016317 0ustar003

��JZ=G�@s<dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZ
ddl
mZddl
m
Z
ddl
mZddl
mZddl
mZdd	l
mZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(dZ)d Z*d!Z+e'�r�d"nd#Z,e
j-j.Z.e
j/�Z0e'�r�d"nd#Z,d$d%�Z1d&d'�Z2Gd(d)�d)e(j3�Z4Gd*d+�d+e4�Z5Gd,d-�d-e5�Z6Gd.d/�d/e4�Z7e8d0k�r8e#e9�dS)1a)
Tests for detecting function memory leaks (typically the ones
implemented in C). It does so by calling a function many times and
checking whether process memory usage keeps increasing between
calls or over time.
Note that this may produce false positives (especially on Windows
for some reason).
�)�print_functionN)�LINUX)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�xrange)�create_sockets)�get_test_subprocess)�HAS_CPU_AFFINITY)�HAS_CPU_FREQ)�HAS_ENVIRON)�
HAS_IONICE)�HAS_MEMORY_MAPS)�HAS_PROC_CPU_NUM)�HAS_PROC_IO_COUNTERS)�
HAS_RLIMIT)�HAS_SENSORS_BATTERY)�HAS_SENSORS_FANS)�HAS_SENSORS_TEMPERATURES)�
reap_children)�run_test_module_by_name)�safe_rmpath)�skip_on_access_denied)�TESTFN)�TRAVIS)�unittesti�i�TFcCstjto
td�S)Nz worthless on LINUX (pure python))r�skipIfr�SKIP_PYTHON_IMPL�r!r!�)/usr/lib64/python3.6/test_memory_leaks.py�
skip_if_linuxFs
r#cCstd
}i}x(t|�D]\}}d	|d	d
>||<qWx8t|�D],}|||kr<t|�||}d||fSq<Wd|S)z�
    http://code.activestate.com/recipes/578019
    >>> bytes2human(10000)
    '9.8K'
    >>> bytes2human(100001221)
    '95.4M'
    �K�M�G�T�P�E�Z�Y��
z%.2f%sz%sB)r$r%r&r'r(r)r*r+)�	enumerate�reversed�float)�nZsymbols�prefix�i�s�valuer!r!r"�bytes2humanKsr6c@sLeZdZdZeZeZeZ	dd�Z
dd�Zdd�Ze
dd	��Ze
d
d��ZdS)
�TestMemLeakz�Base framework class which calls a function many times and
    produces a failure if process memory usage keeps increasing
    between calls or over time.
    cCstj�dS)N)�gc�collect)�selfr!r!r"�setUpgszTestMemLeak.setUpcs~�����fdd�}�jdd�p$�j}�jdd�p6�j��jdd�pH�j}x"td�D]}�j�f����qTW�jtjg��jt	j
�d��jtj�g�|��j
�}|��j
�}	|	|}
|
|k�rzd	}tj�|}x,tj�|k�r�j�f����|d7}q�W~tj��j
�}
|
|	}|
|	k�rzt|
|�}td
|tjd�d}|d
7}|t|
��t|�||f}�j|�dS)zTest a callable.cs2x"t��D]}�j�f����q
W~tj�dS)N)r	�_callr8r9)�x)�args�fun�kwargs�loopsr:r!r"�call_many_timeslsz,TestMemLeak.execute.<locals>.call_many_times�
tolerance_NZloops_Z
retry_for_r-r,rzexta proc mem: %s)�filez0+%s after %s calls, +%s after another %s calls, z+%s extra proc mem)�pop�	tolerancerA�	retry_for�ranger<ZassertEqualr8Zgarbage�	threadingZactive_count�thisproc�children�_get_mem�timer9r6�print�sys�stderrZfail)r:r?r>r@rBrFrGr=Zmem1Zmem2Zdiff1ZncallsZstop_atZmem3Zdiff2Zextra_proc_mem�msgr!)r>r?r@rAr:r"�executejsB

zTestMemLeak.executecs"�����fdd�}�j|�dS)zRConvenience function which tests a callable raising
        an exception.
        cs�j��f����dS)N)ZassertRaisesr!)r>�excr?r@r:r!r"�call�sz'TestMemLeak.execute_w_exc.<locals>.callN)rR)r:rSr?r>r@rTr!)r>rSr?r@r:r"�
execute_w_exc�szTestMemLeak.execute_w_exccCs$tststrtj�jStj�jSdS)N)rrrrJ�memory_full_infoZuss�memory_infoZrssr!r!r!r"rL�s
zTestMemLeak._get_memcOs|||�dS)Nr!)r?r>r@r!r!r"r<�szTestMemLeak._callN)�__name__�
__module__�__qualname__�__doc__�MEMORY_TOLERANCErF�LOOPSrA�	RETRY_FORrGr;rRrU�staticmethodrLr<r!r!r!r"r7^s;		r7c@s�eZdZdZeZdd�Ze�dd��Ze�dd��Z	e�dd	��Z
e�d
d��Zej
ed�e�d
d���Zej
ed�e�dd���Ze�dd��Zdd�Zdd�Zej
ed�dd��Zej
ed�dd��Zej
ed�e�dd���Zej
ed�dd ��Ze�d!d"��Ze�eed#�d$d%���Zej
ed&�d'd(��Zej
ed�e�d)d*���Z e�d+d,��Z!e�eed#�d-d.���Z"e�d/d0��Z#e�ej
e$d�d1d2���Z%e�d3d4��Z&e�d5d6��Z'ej
ed�e�d7d8���Z(ej
e�o�e)d9�d:d;��Z*e�d<d=��Z+ej
e,d�d>d?��Z-ej
e,d�d@dA��Z.e�dBdC��Z/ej
e0dD�ej
e1d�e�dEdF����Z2ej
e3dG�ej
e4d�dHdI���Z5ej
e3dG�ej
e4d�dJdK���Z6e�ej
edL�dMdN���Z7ej
e8d�dOdP��Z9ej
ed&�dQdR��Z:dSS)T�TestProcessObjectLeaksz$Test leaks of Process class methods.cCsNtd�}x@ttj�D]2}|jd�r$q||kr.q|jt|d|�|d�qWdS)N�pid�as_dictrK�cpu_affinity�cpu_percent�ionice�
is_running�kill�memory_info_ex�memory_percent�nice�oneshot�parent�rlimit�send_signal�suspend�	terminate�wait�_�test_)rQ)rarbrKrcrdrerfrgrhrirjrkrlrmrnrorprq)�set�dir�psutil�Process�
startswith�
assertTrue�hasattr)r:�skip�namer!r!r"�
test_coverage�s
z$TestProcessObjectLeaks.test_coveragecCs|j|jj�dS)N)rR�procr|)r:r!r!r"�	test_name�sz TestProcessObjectLeaks.test_namecCs|j|jj�dS)N)rRr~Zcmdline)r:r!r!r"�test_cmdline�sz#TestProcessObjectLeaks.test_cmdlinecCs|j|jj�dS)N)rRr~Zexe)r:r!r!r"�test_exe�szTestProcessObjectLeaks.test_execCs|j|jj�dS)N)rRr~Zppid)r:r!r!r"�	test_ppid�sz TestProcessObjectLeaks.test_ppidz
POSIX onlycCs|j|jj�dS)N)rRr~Zuids)r:r!r!r"�	test_uids�sz TestProcessObjectLeaks.test_uidscCs|j|jj�dS)N)rRr~Zgids)r:r!r!r"�	test_gids�sz TestProcessObjectLeaks.test_gidscCs|j|jj�dS)N)rRr~Zstatus)r:r!r!r"�test_status�sz"TestProcessObjectLeaks.test_statuscCs|j|jj�dS)N)rRr~rj)r:r!r!r"�
test_nice_get�sz$TestProcessObjectLeaks.test_nice_getcCstj�}|j|jj|�dS)N)rJrjrRr~)r:Znicenessr!r!r"�
test_nice_set�sz$TestProcessObjectLeaks.test_nice_setz
not supportedcCs|j|jj�dS)N)rRr~re)r:r!r!r"�test_ionice_get�sz&TestProcessObjectLeaks.test_ionice_getcCsVtrtj�}|j|jj|�n4|j|jjtj�tjt	j
tj�dd�}|j
t|�dS)Nr,r���)rrJrerRr~rvZIOPRIO_CLASS_NONE�	functools�partial�cextZproc_ioprio_set�os�getpidrU�OSError)r:r5r?r!r!r"�test_ionice_set�sz&TestProcessObjectLeaks.test_ionice_setcCs|j|jj�dS)N)rRr~Zio_counters)r:r!r!r"�test_io_counterssz'TestProcessObjectLeaks.test_io_counterszworthless on POSIXcCs|j|jj�dS)N)rRr~Zusername)r:r!r!r"�
test_usernamesz$TestProcessObjectLeaks.test_usernamecCs|j|jj�dS)N)rRr~Zcreate_time)r:r!r!r"�test_create_timesz'TestProcessObjectLeaks.test_create_time)Zonly_ifcCs|j|jj�dS)N)rRr~Znum_threads)r:r!r!r"�test_num_threadssz'TestProcessObjectLeaks.test_num_threadszWINDOWS onlycCs|j|jj�dS)N)rRr~Znum_handles)r:r!r!r"�test_num_handlessz'TestProcessObjectLeaks.test_num_handlescCs|j|jj�dS)N)rRr~Znum_fds)r:r!r!r"�test_num_fdssz#TestProcessObjectLeaks.test_num_fdscCs|j|jj�dS)N)rRr~Znum_ctx_switches)r:r!r!r"�test_num_ctx_switches!sz,TestProcessObjectLeaks.test_num_ctx_switchescCs|j|jj�dS)N)rRr~Zthreads)r:r!r!r"�test_threads%sz#TestProcessObjectLeaks.test_threadscCs|j|jj�dS)N)rRr~�	cpu_times)r:r!r!r"�test_cpu_times*sz%TestProcessObjectLeaks.test_cpu_timescCs|j|jj�dS)N)rRr~Zcpu_num)r:r!r!r"�test_cpu_num.sz#TestProcessObjectLeaks.test_cpu_numcCs|j|jj�dS)N)rRr~rW)r:r!r!r"�test_memory_info3sz'TestProcessObjectLeaks.test_memory_infocCs|j|jj�dS)N)rRr~rV)r:r!r!r"�test_memory_full_info7sz,TestProcessObjectLeaks.test_memory_full_infocCs|j|jj�dS)N)rRr~Zterminal)r:r!r!r"�
test_terminal;sz$TestProcessObjectLeaks.test_terminalz worthless on POSIX (pure python)cCs|j|jj�dS)N)rRr~�resume)r:r!r!r"�test_resume@sz"TestProcessObjectLeaks.test_resumecCs|j|jj�dS)N)rRr~�cwd)r:r!r!r"�test_cwdEszTestProcessObjectLeaks.test_cwdcCs|j|jj�dS)N)rRr~rc)r:r!r!r"�test_cpu_affinity_getIsz,TestProcessObjectLeaks.test_cpu_affinity_getcCs4tj�}|j|jj|�ts0|jt|jjdg�dS)Nr,r�)rJrcrRr~rrU�
ValueError)r:Zaffinityr!r!r"�test_cpu_affinity_setMsz,TestProcessObjectLeaks.test_cpu_affinity_setc	Cs0tt�ttd��|j|jj�WdQRXdS)N�w)rr�openrRr~Z
open_files)r:r!r!r"�test_open_filesTsz&TestProcessObjectLeaks.test_open_filesztoo slow on OSXcCs|j|jj�dS)N)rRr~Zmemory_maps)r:r!r!r"�test_memory_maps[sz'TestProcessObjectLeaks.test_memory_mapsz
LINUX onlycCs|j|jjtj�dS)N)rRr~rmrv�
RLIMIT_NOFILE)r:r!r!r"�test_rlimit_getasz&TestProcessObjectLeaks.test_rlimit_getcCs6tjtj�}|j|jjtj|�|jt|jjd�dS)Nr,r�)rJrmrvr�rRr~rUr�)r:�limitr!r!r"�test_rlimit_setfsz&TestProcessObjectLeaks.test_rlimit_setzworthless on WINDOWSc
Cs2t��"trdnd}|j|jj|�WdQRXdS)NZinet�all)r
rrRr~Zconnections)r:Zkindr!r!r"�test_connectionsmsz'TestProcessObjectLeaks.test_connectionscCs|j|jj�dS)N)rRr~�environ)r:r!r!r"�test_environysz#TestProcessObjectLeaks.test_environcCs|jtjtj��dS)N)rRr��	proc_infor�r�)r:r!r!r"�test_proc_info}sz%TestProcessObjectLeaks.test_proc_infoN);rXrYrZr[rJr~r}r#rr�r�r�rrrr�r�r�r�r�rr�r�rr�r�r�rrr�rr�r�r�r�r�rr�r�r�r�r r�r�rr�r�r�rrr�rrr�r�r�rr�r�r!r!r!r"r`�sh


	r`cspeZdZdZe�fdd��Ze�fdd��Zdd�Zerhdd	�Z	d
d�Z
dd
�Zdd�Zdd�Z
dd�Z�ZS)�TestTerminatedProcessLeaksz�Repeat the tests above looking for leaks occurring when dealing
    with terminated processes raising NoSuchProcess exception.
    The C functions are still invoked but will follow different code
    paths. We'll check those code paths.
    cs:tt|�j�t�}tj|j�|_|jj�|jj	�dS)N)
�superr��
setUpClassrrvrwrar~rgrq)�cls�p)�	__class__r!r"r��s

z%TestTerminatedProcessLeaks.setUpClasscstt|�j�t�dS)N)r�r��
tearDownClassr)r�)r�r!r"r��sz(TestTerminatedProcessLeaks.tearDownClasscOs*y|||�Wntjk
r$YnXdS)N)rvZ
NoSuchProcess)r:r?r>r@r!r!r"r<�sz TestTerminatedProcessLeaks._callcCs|j|jj�dS)N)rRr~rg)r:r!r!r"�	test_kill�sz$TestTerminatedProcessLeaks.test_killcCs|j|jj�dS)N)rRr~rp)r:r!r!r"�test_terminate�sz)TestTerminatedProcessLeaks.test_terminatecCs|j|jj�dS)N)rRr~ro)r:r!r!r"�test_suspend�sz'TestTerminatedProcessLeaks.test_suspendcCs|j|jj�dS)N)rRr~r�)r:r!r!r"r��sz&TestTerminatedProcessLeaks.test_resumecCs|j|jj�dS)N)rRr~rq)r:r!r!r"�	test_wait�sz$TestTerminatedProcessLeaks.test_waitcs�fdd�}�j|�dS)NcsDytj�jj�Stk
r>}z|jtjkr.�WYdd}~XnXdS)N)r�r�r~rar��errnoZESRCH)�err)r:r!r"rT�s
z7TestTerminatedProcessLeaks.test_proc_info.<locals>.call)rR)r:rTr!)r:r"r��sz)TestTerminatedProcessLeaks.test_proc_info)rXrYrZr[�classmethodr�r�r<rr�r�r�r�r�r��
__classcell__r!r!)r�r"r��sr�c@s�eZdZdZdd�Ze�dd��Ze�dd��Ze�dd	��Ze�d
d��Z	dd
�Z
e�eje
d�dd���Zdd�Zejed�dd��Zejeo�ed�dd��Zejeo�ed�dd��Zdd�Zejeo�ejjd�d�e�dd ���Ze�d!d"��Ze�d#d$��Zejed%�eje�o&ej�d&kd'�d(d)���Z d*d+�Z!eje"d,�d-d.��Z#e�eje$d�d/d0���Z%e�eje&d�d1d2���Z'e�eje(d�d3d4���Z)e�d5d6��Z*eje+d7�d8d9��Z,e+�r�d:d;�Z-d<d=�Z.d>d?�Z/d@dA�Z0dBdC�Z1dDS)E�TestModuleFunctionsLeaksz&Test leaks of psutil module functions.cCsHtd
�}x:tjD]0}|j�sq||kr(q|jt|d|�|d	�qWdS)N�version_info�__version__�process_iter�
wait_procsrd�cpu_times_percent�	cpu_countrs)rQ)r�r�r�r�rdr�r�)rtrv�__all__�islowerryrz)r:r{r|r!r!r"r}�sz&TestModuleFunctionsLeaks.test_coveragecCs|jtjdd�dS)NT)�logical)rRrvr�)r:r!r!r"�test_cpu_count_logical�sz/TestModuleFunctionsLeaks.test_cpu_count_logicalcCs|jtjdd�dS)NF)r�)rRrvr�)r:r!r!r"�test_cpu_count_physical�sz0TestModuleFunctionsLeaks.test_cpu_count_physicalcCs|jtj�dS)N)rRrvr�)r:r!r!r"r��sz'TestModuleFunctionsLeaks.test_cpu_timescCs|jtjdd�dS)NT)Zpercpu)rRrvr�)r:r!r!r"�test_per_cpu_times�sz+TestModuleFunctionsLeaks.test_per_cpu_timescCs|jtj�dS)N)rRrvZ	cpu_stats)r:r!r!r"�test_cpu_stats�sz'TestModuleFunctionsLeaks.test_cpu_statsz
not supportedcCs|jtj�dS)N)rRrvZcpu_freq)r:r!r!r"�
test_cpu_freq�sz&TestModuleFunctionsLeaks.test_cpu_freqcCs|jtj�dS)N)rRrvZvirtual_memory)r:r!r!r"�test_virtual_memory�sz,TestModuleFunctionsLeaks.test_virtual_memoryz&worthless on SUNOS (uses a subprocess)cCs|jtj�dS)N)rRrvZswap_memory)r:r!r!r"�test_swap_memory�sz)TestModuleFunctionsLeaks.test_swap_memoryz worthless on POSIX (pure python)cCs|jtjtj��dS)N)rRrvZ
pid_existsr�r�)r:r!r!r"�test_pid_exists�sz(TestModuleFunctionsLeaks.test_pid_existscCs|jtjd�dS)N�.)rRrvZ
disk_usage)r:r!r!r"�test_disk_usage�sz(TestModuleFunctionsLeaks.test_disk_usagecCs|jtj�dS)N)rRrvZdisk_partitions)r:r!r!r"�test_disk_partitions�sz-TestModuleFunctionsLeaks.test_disk_partitionsz/proc/diskstatsz3/proc/diskstats not available on this Linux versioncCs|jtjdd�dS)NF)�nowrap)rRrvZdisk_io_counters)r:r!r!r"�test_disk_io_counterssz.TestModuleFunctionsLeaks.test_disk_io_counterscCs|jtj�dS)N)rRrvZpids)r:r!r!r"�	test_pidssz"TestModuleFunctionsLeaks.test_pidscCs|jtjdd�dS)NF)r�)rRrvZnet_io_counters)r:r!r!r"�test_net_io_counterssz-TestModuleFunctionsLeaks.test_net_io_countersz worthless on Linux (pure python)rzneed root accessc	Cs"t��|jtj�WdQRXdS)N)r
rRrvZnet_connections)r:r!r!r"�test_net_connectionssz-TestModuleFunctionsLeaks.test_net_connectionscCs|jtjtrdndd�dS)N�Pi)rCi@)rRrvZnet_if_addrsr)r:r!r!r"�test_net_if_addrssz*TestModuleFunctionsLeaks.test_net_if_addrszEPERM on traviscCs|jtj�dS)N)rRrvZnet_if_stats)r:r!r!r"�test_net_if_statssz*TestModuleFunctionsLeaks.test_net_if_statscCs|jtj�dS)N)rRrvZsensors_battery)r:r!r!r"�test_sensors_battery$sz-TestModuleFunctionsLeaks.test_sensors_batterycCs|jtj�dS)N)rRrvZsensors_temperatures)r:r!r!r"�test_sensors_temperatures)sz2TestModuleFunctionsLeaks.test_sensors_temperaturescCs|jtj�dS)N)rRrvZsensors_fans)r:r!r!r"�test_sensors_fans.sz*TestModuleFunctionsLeaks.test_sensors_fanscCs|jtj�dS)N)rRrvZ	boot_time)r:r!r!r"�test_boot_time5sz'TestModuleFunctionsLeaks.test_boot_timez(XXX produces a false positive on WindowscCs|jtj�dS)N)rRrvZusers)r:r!r!r"�
test_users:sz#TestModuleFunctionsLeaks.test_userscCs|jtj�dS)N)rRr�Zwinservice_enumerate)r:r!r!r"�test_win_service_iterBsz.TestModuleFunctionsLeaks.test_win_service_itercCsdS)Nr!)r:r!r!r"�test_win_service_getEsz-TestModuleFunctionsLeaks.test_win_service_getcCs"ttj��j�}|jtj|�dS)N)�nextrv�win_service_iterr|rRr�Zwinservice_query_config)r:r|r!r!r"�test_win_service_get_configHsz4TestModuleFunctionsLeaks.test_win_service_get_configcCs"ttj��j�}|jtj|�dS)N)r�rvr�r|rRr�Zwinservice_query_status)r:r|r!r!r"�test_win_service_get_statusLsz4TestModuleFunctionsLeaks.test_win_service_get_statuscCs"ttj��j�}|jtj|�dS)N)r�rvr�r|rRr�Zwinservice_query_descr)r:r|r!r!r"� test_win_service_get_descriptionPsz9TestModuleFunctionsLeaks.test_win_service_get_descriptionN)2rXrYrZr[r}r#r�r�r�r�r�rrr
r�r�rr�rr r�r�r�rr��path�existsr�r�r�r�getuidr�r�rr�rr�rr�rr�r�rr�r�r�r�r�r�r!r!r!r"r��sR


$r��__main__):r[Z
__future__rr�r�r8r�rOrIrMrvZpsutil._commonrrrrrrZpsutil._compatr	Zpsutil.testsr
rrr
rrrrrrrrrrrrrrrrr]r\r^r Z_psplatformr�rwrJr#r6ZTestCaser7r`r�r�rX�__file__r!r!r!r"�<module>
slcB<
tests/__pycache__/__main__.cpython-36.pyc000064400000004767150466730550014315 0ustar003

��JZ�
�
@s:dZddlZddlZddlZddlZddlZddlZyddlmZWn e	k
rdddl
mZYnXddlmZddlm
Z
ejjejje��ZdZgZejdd�dkr�ejd	d
ddg�nVejdd�dks�ejdd�dk�r�ejd	dg�n ejdd�dk�rejd	g�dd�Zddd�Zdd�Ze�dS)z?
Run unit tests. This is invoked by:

$ python -m psutil.tests
�N)�urlopen)�
PYTHON_EXE)�	run_suitez$https://bootstrap.pypa.io/get-pip.py��Z	ipaddressZ	unittest2�argparsezmock==1.0.1��ZmockcCs�yddl}Wn�tk
r�tjdd�}tj|���tdt|jf�t	t
d�rZt
j�}nd}|rlt|d�ni}t
tf|�}|j�}|j|�|j�td�tjdt|jf�}|SQRXYnXdS)	Nrz.py)�suffixzdownloading %s to %s�_create_unverified_context)�contextzinstalling pipz%s %s --user)�pip�ImportError�tempfileZNamedTemporaryFile�
contextlib�closing�print�GET_PIP_URL�name�hasattr�sslr�dictr�read�write�flush�os�systemr)r
�fZctx�kwargsZreq�data�code�r!� /usr/lib64/python3.6/__main__.py�install_pip&s"


r#cCsV|dkrt}t|�}|rRttd�}|s*dnd}t�tjdt|dj|�f�}|SdS)z"Install test dependencies via pip.NZreal_prefixz--user�z!%s -m pip install %s --upgrade %s� )	�	TEST_DEPS�setr�sysr#rrr�join)ZdepsZis_venv�optsr r!r!r"�install_test_deps<s
r+cCs�dt}tj|dd�}|jdddddd	�|j�\}}|jrJt�t�nRxJtD]B}yt	|j
d
�d�WqPtk
r�tj
d|tf�YqPXqPWt�dS)
Nz%s -m psutil.tests [opts]zrun unit tests)�usage�descriptionz-iz--install-deps�
store_trueFz%don't print status messages to stdout)�action�default�helpz==rz>%r lib is not installed; run %s -m psutil.tests --install-deps)r�optparseZOptionParserZ
add_option�
parse_argsZinstall_depsr#r+r&�
__import__�splitrr(�exitr)r,�parserr*�argsZdepr!r!r"�mainJs 
r9)rr)rr)r	r)r	r	)N)�__doc__rr2rrr(rZurllib.requestrrZurllib2Zpsutil.testsrr�path�abspath�dirname�__file__ZHERErr&�version_info�extendr#r+r9r!r!r!r"�<module>
s2&
tests/__pycache__/__main__.cpython-36.opt-1.pyc000064400000004767150466730550015254 0ustar003

��JZ�
�
@s:dZddlZddlZddlZddlZddlZddlZyddlmZWn e	k
rdddl
mZYnXddlmZddlm
Z
ejjejje��ZdZgZejdd�dkr�ejd	d
ddg�nVejdd�dks�ejdd�dk�r�ejd	dg�n ejdd�dk�rejd	g�dd�Zddd�Zdd�Ze�dS)z?
Run unit tests. This is invoked by:

$ python -m psutil.tests
�N)�urlopen)�
PYTHON_EXE)�	run_suitez$https://bootstrap.pypa.io/get-pip.py��Z	ipaddressZ	unittest2�argparsezmock==1.0.1��ZmockcCs�yddl}Wn�tk
r�tjdd�}tj|���tdt|jf�t	t
d�rZt
j�}nd}|rlt|d�ni}t
tf|�}|j�}|j|�|j�td�tjdt|jf�}|SQRXYnXdS)	Nrz.py)�suffixzdownloading %s to %s�_create_unverified_context)�contextzinstalling pipz%s %s --user)�pip�ImportError�tempfileZNamedTemporaryFile�
contextlib�closing�print�GET_PIP_URL�name�hasattr�sslr�dictr�read�write�flush�os�systemr)r
�fZctx�kwargsZreq�data�code�r!� /usr/lib64/python3.6/__main__.py�install_pip&s"


r#cCsV|dkrt}t|�}|rRttd�}|s*dnd}t�tjdt|dj|�f�}|SdS)z"Install test dependencies via pip.NZreal_prefixz--user�z!%s -m pip install %s --upgrade %s� )	�	TEST_DEPS�setr�sysr#rrr�join)ZdepsZis_venv�optsr r!r!r"�install_test_deps<s
r+cCs�dt}tj|dd�}|jdddddd	�|j�\}}|jrJt�t�nRxJtD]B}yt	|j
d
�d�WqPtk
r�tj
d|tf�YqPXqPWt�dS)
Nz%s -m psutil.tests [opts]zrun unit tests)�usage�descriptionz-iz--install-deps�
store_trueFz%don't print status messages to stdout)�action�default�helpz==rz>%r lib is not installed; run %s -m psutil.tests --install-deps)r�optparseZOptionParserZ
add_option�
parse_argsZinstall_depsr#r+r&�
__import__�splitrr(�exitr)r,�parserr*�argsZdepr!r!r"�mainJs 
r9)rr)rr)r	r)r	r	)N)�__doc__rr2rrr(rZurllib.requestrrZurllib2Zpsutil.testsrr�path�abspath�dirname�__file__ZHERErr&�version_info�extendr#r+r9r!r!r!r"�<module>
s2&
tests/__pycache__/test_windows.cpython-36.opt-1.pyc000064400000067057150466730550016266 0ustar003

��JZK�@s`dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlm
Z
ddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZej��Zejd�y$ddlZddlZddlZddlZWn$e k
�rDej!dk�r@�YnXWdQRXej"j#Z#e	j$d$kZ%dd�Z&ej'e
d�Gdd�dej(��Z)ej'e
d�Gdd�dej(��Z*ej'e
d�Gdd�dej(��Z+ej'e
d�Gdd�dej(��Z,ej'e
d�Gdd�dej(��Z-ej'e
d�Gdd �d ej(��Z.ej'e
d�Gd!d"�d"ej(��Z/e0d#k�r\ee1�dS)%zWindows specific tests.�N)�WINDOWS)�callable)�APPVEYOR)�get_test_subprocess)�HAS_BATTERY)�mock)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�unittest�ignore�nt�� cs�fdd�}|S)Ncsty�|f|�|�Stk
rn}zBddlm}|j|krDtjdd��|jtjkr\tjdd���WYdd}~XnXdS)Nr)�ACCESS_DENIED_SET)�OSErrorZpsutil._pswindowsr�errno�psutil�AccessDeniedZESRCH�
NoSuchProcess)�self�args�kwargs�errr)�fun��$/usr/lib64/python3.6/test_windows.py�wrapper5s
z wrap_exceptions.<locals>.wrapperr)rrr)rr�wrap_exceptions4s
rzWINDOWS onlyc@s�eZdZdd�Zejdejkd�dd��Zdd�Z	d	d
�Z
dd�Zejed
�e
�dd���Ze
�dd��Zdd�Zdd�Zdd�Zdd�Zdd�ZdS)�TestSystemAPIscCsVtd�}tjdd�j�}x8|D]0}d|jdd�j�kr8q||kr|jd|�qWdS)Nz
ipconfig /allT)Zperniczpseudo-interface� �-z-%r nic wasn't found in 'ipconfig /all' output)rrZnet_io_counters�keys�replace�lower�fail)r�outZnicsZnicrrr�test_nic_namesJs
zTestSystemAPIs.test_nic_names�NUMBER_OF_PROCESSORSz-NUMBER_OF_PROCESSORS env var is not availablecCs"ttjd�}|j|tj��dS)Nr))�int�os�environ�assertEqualr�	cpu_count)rZnum_cpusrrr�test_cpu_countTszTestSystemAPIs.test_cpu_countcCs$tj�d}tj�}|j||�dS)N�)�win32apiZ
GetSystemInforr.r-)r�	sys_value�psutil_valuerrr�test_cpu_count_2ZszTestSystemAPIs.test_cpu_count_2cCs@tj�}|j�d}|j|jtj�j�|j|jtj�j	�dS)Nr)
�wmi�WMIZWin32_Processorr-ZCurrentClockSpeedrZcpu_freqZcurrentZ
MaxClockSpeed�max)r�w�procrrr�
test_cpu_freq_szTestSystemAPIs.test_cpu_freqcCs,tj�j�d}|jt|j�tj�j�dS)Nr)	r5r6ZWin32_ComputerSystemr-r*ZTotalPhysicalMemoryrZvirtual_memory�total)rr8rrr�test_total_phymemesz TestSystemAPIs.test_total_phymemztest not relieable on appveyorcCs:tj�j�}tdd�|D��}ttj��}|j||�dS)NcSsg|]
}|j�qSr)�	ProcessId)�.0�xrrr�
<listcomp>|sz,TestSystemAPIs.test_pids.<locals>.<listcomp>)r5r6�
Win32_Process�setrZpidsr-)rr8Zwmi_pidsZpsutil_pidsrrr�	test_pidsvszTestSystemAPIs.test_pidscCstjdd�}tj�j�}x�|D]�}x�|D]�}|jjdd�|jkr(|jsHPytj	|j�}Wn4t
k
r�}z|jtjkrzPn�WYdd}~XnX|j
|jt|j��t|j�}|j
|j|�t|j|�d
kr�|jd|j|f�Pq(W|jdt|��qWdS)NT)�all�\��
izpsutil=%s, wmi=%szcan't find partition %si(i�)r�disk_partitionsr5r6ZWin32_LogicalDiskZdevicer$ZDeviceID�
mountpoint�
disk_usagerr�ENOENTr-r;r*ZSizeZ	FreeSpace�free�absr&�repr)rZps_partsZ	wmi_partsZps_partZwmi_partZusagerZwmi_freerrr�
test_disks�s*


zTestSystemAPIs.test_diskscCspxjtj�D]^}tj|j�}tj|j�}|j|d|jdd�|j|d|jdd�|j	|j
|j|j�q
WdS)Nri)�delta�ii)rrHr1ZGetDiskFreeSpaceExrIrJ�assertAlmostEqualrLr;r-Zused)rZdiskr2r3rrr�test_disk_usage�szTestSystemAPIs.test_disk_usagecCs>dd�tj�jd�D�}dd�tjdd�D�}|j||�dS)NcSs$g|]}|r|jd�r|d�qS)zA:rE)�
startswith)r>r?rrrr@�sz7TestSystemAPIs.test_disk_partitions.<locals>.<listcomp>z\cSsg|]
}|j�qSr)rI)r>r?rrrr@�sT)rD)r1ZGetLogicalDriveStrings�splitrrHr-)rr2r3rrr�test_disk_partitions�sz#TestSystemAPIs.test_disk_partitionscCs`ttj��}tj�j�}t�}x$|D]}|j|j�|j|j�q$W|j	||@d||f�dS)Nzno common entries in %s, %s)
rB�cextZnet_if_statsr5r6ZWin32_NetworkAdapter�add�NameZNetConnectionID�
assertTrue)rZps_namesZwmi_adaptersZ	wmi_namesZwmi_adapterrrr�test_net_if_stats�s

z TestSystemAPIs.test_net_if_statscCs^tj�j�}|djjd�d}tjj|d�}tjjtj	��}t
||j��}|j|d�dS)Nr�.z%Y%m%d%H%M%S�)
r5r6ZWin32_OperatingSystemZLastBootUpTimerU�datetimeZstrptimeZ
fromtimestampr�	boot_timerMZ
total_secondsZassertLessEqual)rZwmi_osZ
wmi_btime_strZwmi_btime_dtZ	psutil_dtZdiffrrr�test_boot_time�szTestSystemAPIs.test_boot_timecCs�tjddd��|jtj�d�WdQRXtjddd��|jtj�d�WdQRXtjddd��|jtj�d�WdQRXtjddd��|jtj�d�WdQRXdS)Nz psutil._pswindows.cext.boot_timer0)�return_value��iM)r�patchr-rr_)rrrr�test_boot_time_fluctuation�sz)TestSystemAPIs.test_boot_time_fluctuationN)�__name__�
__module__�__qualname__r(r�skipIfr+r,r/r4r:r<rr	rCrOrSrVr[r`rerrrrr Gs

	

r c@s`eZdZdd�Zejed�dd��Zejed�dd��Zdd	�Z	d
d�Z
dd
�Zdd�ZdS)�TestSensorsBatterycCs.tj�dr|jtj��n|jtj��dS)NZSystemBatteriesPresent)r1ZGetPwrCapabilitiesZassertIsNotNoner�sensors_battery�assertIsNone)rrrr�test_has_battery�sz#TestSensorsBattery.test_has_batteryz
no batterycCs6tj�}|jd�d}tj�}|j|j|jdd�dS)Nzselect * from Win32_BatteryrrQ)rP)r5r6�queryrrkrRZpercentZEstimatedChargeRemaining)rr8�battery_wmi�battery_psutilrrr�test_percent�szTestSensorsBattery.test_percentcCs6tj�}|jd�d}tj�}|j|j|jdk�dS)Nzselect * from Win32_Batteryrr)r5r6rnrrkr-Z
power_pluggedZ
BatteryStatus)rr8rorprrr�test_power_plugged�s
z%TestSensorsBattery.test_power_pluggedc	Cs,tjddd��}|jtj��WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr�)ra)rrsrr)rrdrlrrk)r�mrrr�test_emulate_no_battery�s
z*TestSensorsBattery.test_emulate_no_batteryc
Cs2tjddd��}|jtj�jtj�WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrQr)ra)rQrrr)rrdr-rrk�secsleft�POWER_TIME_UNLIMITED)rrtrrr�test_emulate_power_connected�s

z/TestSensorsBattery.test_emulate_power_connectedc
Cs2tjddd��}|jtj�jtj�WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryr�)ra)rryrr)rrdr-rrkrvrw)rrtrrr�test_emulate_power_charging�s

z.TestSensorsBattery.test_emulate_power_chargingc
Cs2tjddd��}|jtj�jtj�WdQRXdS)Nz&psutil._pswindows.cext.sensors_batteryrrQ)ra���)rrrr{)rrdr-rrkrvZPOWER_TIME_UNKNOWN)rrtrrr�test_emulate_secs_left_unknowns

z1TestSensorsBattery.test_emulate_secs_left_unknownN)
rfrgrhrmrrirrqrrrurxrzr|rrrrrj�s	
rjc@s�eZdZedd��Zedd��Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Ze
jejd+kd�dd��Zdd�Zdd�Zdd�Zdd�Zd d!�Zd"d#�Zd$d%�Zd&d'�Zd(d)�Zd*S),�TestProcesscCst�j|_dS)N)r�pid)�clsrrr�
setUpClassszTestProcess.setUpClasscCs
t�dS)N)r)rrrr�
tearDownClassszTestProcess.tearDownClasscCstjd�}|jtj|j�dS)Nr)r�Process�assertRaisesr�kill)r�prrr�
test_issue_24s
zTestProcess.test_issue_24cCs�tjd�}|j|j�d�t|�|j�|j|j�dk�y|j�dd�\}}Wn(tj	k
r|t
j�dd
krx�YnX|j|d	k�dS)NrbZSystemgrrQ�vista�win-7�win7r)r�r�r�)rr�r-�name�str�usernamerZ�create_time�memory_infor�platform�uname)rr��rss�vmsrrr�test_special_pid s
zTestProcess.test_special_pidcCs"tj|j�}|jt|jtj�dS)N)rr�r~r��
ValueError�send_signal�signal�SIGINT)rr�rrr�test_send_signal1szTestProcess.test_send_signalcCsNxHtj�D]<}y |jtjj|j��|j��Wq
tjk
rDYq
Xq
WdS)N)	r�process_iterr-r+�path�basename�exer��Error)rr�rrr�test_exe5s
 zTestProcess.test_execCsbtjtj��}|j�}tjtjtj	tj��}|j�}|j
||d�tj|�|j
|j�|�dS)NrQ)rr�r+�getpid�num_handlesr1�OpenProcess�win32con�PROCESS_QUERY_INFORMATION�FALSEr-�CloseHandle)rr�Zbefore�handle�afterrrr�test_num_handles_increment<s
z&TestProcess.test_num_handles_incrementc
s��fdd�}tj|j�}g}x�ttj�D]���jd�s(�dkrBq(q(y(||��|j�}||��|j�}Wntjtjfk
r�Yq(X||kr(d�||f}|j|�q(W|r�|j	ddj
|��dS)Ncs,t|�d�}|dk	r$t|�r$|�n|dS)N)�getattrr)r��attr)r�rr�callJsz+TestProcess.test_handles_leak.<locals>.call�_�	terminater��suspend�resume�nicer��wait�children�as_dict�memory_info_exz@failure while processing Process.%s method (before=%s, after=%s)�
)
r�r�r�r�r�r�r�r�r�r�)rr�r~�dirrTr�rr�appendr&�join)rr�r�ZfailuresZnum1Znum2r&r)r�r�test_handles_leakFs,


zTestProcess.test_handles_leakcCs:x4tj�D](}y|j�Wq
tjk
r0Yq
Xq
WdS)N)rr�r�r)rr�rrr�test_name_always_availablejs
z&TestProcess.test_name_always_availabler�zCTRL_* signals not supportedcCsbtjt�j�}|jtj�|jtj�|j�|j	�|j
tj|jtj�|j
tj|jtj�dS)N)rr�rr~r�r�ZCTRL_C_EVENTZCTRL_BREAK_EVENTr�r�r�r)rr�rrr�test_ctrl_signalssszTestProcess.test_ctrl_signalsc
Cs\xVtj�D]J}ytjj|j��}|j�}Wntjtjfk
rFYq
X|j	||�q
WdS)N)
rr�r+r�r�r�r�rrr-)rr��a�brrr�test_compare_name_exe�sz!TestProcess.test_compare_name_execCs |jtj�j�tjtj��dS)N)r-rr�r�r1Z
GetUserNameExr�ZNameSamCompatible)rrrr�
test_username�szTestProcess.test_usernamecCs8tjddtj��j�}djtj�j��}|j	||�dS)Nz +r!)
�re�subr1ZGetCommandLine�stripr�rr��cmdliner-)rr2r3rrr�test_cmdline�szTestProcess.test_cmdlinecCsJtjtjtjtj��}|jtj|�t	j
|�}tj�j
�}|j||�dS)N)r1r�r�r�r�r+r��
addCleanupr��win32processZGetPriorityClassrr�r�r-)rr�r2r3rrr�	test_nice�s
zTestProcess.test_nicecCs�tjtjtj|j�}|jtj|�tj	|�}t
j|j�j�}|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|d|j�|j
|j|j�|j
|j|j�dS)	NZPeakWorkingSetSize�WorkingSetSizeZQuotaPeakPagedPoolUsageZQuotaPagedPoolUsageZQuotaPeakNonPagedPoolUsageZQuotaNonPagedPoolUsageZ
PagefileUsageZPeakPagefileUsage)r1r�r�r�r�r~r�r�r�ZGetProcessMemoryInforr�r�r-Z	peak_wsetZwsetZpeak_paged_poolZ
paged_poolZpeak_nonpaged_poolZ
nonpaged_poolZpagefileZ
peak_pagefiler�r�)rr�r2r3rrr�test_memory_info�s0
zTestProcess.test_memory_infocCsXtjtjtj|j�}|jtj|�tj	|j�}|j
�|j�}tj
|�}|j||�dS)N)r1r�r�r�r�r~r�r�rr�r�r�r�ZGetExitCodeProcessr-)rr�r�r3r2rrr�	test_wait�s
zTestProcess.test_waitcCs\dd�}tjtjtj|j�}|jtj|�|tj	|�d�}t
j|j�j�}|j
||�dS)Ncs�fdd�td�D�S)Ncsg|]}d|>�@r|�qS)rQr)r>�i)r?rrr@�szGTestProcess.test_cpu_affinity.<locals>.from_bitmask.<locals>.<listcomp>�@)�range)r?r)r?r�from_bitmask�sz3TestProcess.test_cpu_affinity.<locals>.from_bitmaskr)r1r�r�r�r�r~r�r�r�ZGetProcessAffinityMaskrr�Zcpu_affinityr-)rr�r�r2r3rrr�test_cpu_affinity�szTestProcess.test_cpu_affinitycCs�tjtjtjtj��}|jtj|�t	j
|�}tj�j
�}|j|j|d�|j|j|d�|j|j|d�|j|j|d�|j|j|d�|j|j|d�dS)NZReadOperationCountZWriteOperationCountZReadTransferCountZWriteTransferCountZOtherOperationCountZOtherTransferCount)r1r�r�r�r�r+r�r�r�r�ZGetProcessIoCountersrr��io_countersr-Z
read_countZwrite_countZ
read_bytesZwrite_bytes�other_countZother_bytes)rr�r2r3rrr�test_io_counters�s"
zTestProcess.test_io_counterscCs�ddl}ddl}d}|jjj|dtj��}|j|jjj|�|j	j
�}|jjj||j|��|j
}tj�j�}|jjj|�|j||d�dS)NrirQ)�ctypesZctypes.wintypesZwindllZkernel32r�r+r�r�r�ZwintypesZDWORDZGetProcessHandleCountZbyref�valuerr�r�r-)rr�r�r�Zhndcntr2r3rrr�test_num_handles�s
zTestProcess.test_num_handlesN)rr�)rfrgrh�classmethodr�r�r�r�r�r�r�r�r�rri�sys�version_infor�r�r�r�r�r�r�r�r�r�rrrrr}s(
$	

r}c@s`eZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�Zdd�Z
dS)�TestProcessWMIz%Compare Process API results with WMI.cCst�j|_dS)N)rr~)rrrrr�szTestProcessWMI.setUpClasscCs
t�dS)N)r)rrrrr�szTestProcessWMI.tearDownClasscCs8tj�j|jd�d}tj|j�}|j|j�|j�dS)N)r=r)	r5r6rAr~rr�r-r�ZCaption)rr8r�rrr�	test_name
szTestProcessWMI.test_namecCs@tj�j|jd�d}tj|j�}|j|j�j�|j	j��dS)N)r=r)
r5r6rAr~rr�r-r�r%ZExecutablePath)rr8r�rrrr�szTestProcessWMI.test_execCsFtj�j|jd�d}tj|j�}|jdj|j��|j	j
dd��dS)N)r=rr!�"rF)r5r6rAr~rr�r-r�r�ZCommandLiner$)rr8r�rrrr�szTestProcessWMI.test_cmdlinecCsPtj�j|jd�d}tj|j�}|j�\}}}d||f}|j|j�|�dS)N)r=rz%s\%s)	r5r6rAr~rr�ZGetOwnerr-r�)rr8r�Zdomainr�r�rrrr�s
zTestProcessWMI.test_usernamecCsLtjd�tj�j|jd�d}tj|j�}|j�j	}|j
|t|j��dS)Ng�������?)r=r)
�time�sleepr5r6rAr~rr�r�r�r-r*r�)rr8r�r�rrr�test_memory_rss#s


zTestProcessWMI.test_memory_rsscCsjtjd�tj�j|jd�d}tj|j�}|j�j	}t
|j�}||krf||dkrf|jd||f�dS)Ng�������?)r=rizwmi=%s, psutil=%s)
r�r�r5r6rAr~rr�r�r�r*Z
PageFileUsager&)rr8r�r�Z	wmi_usagerrr�test_memory_vms*s


zTestProcessWMI.test_memory_vmscCs\tj�j|jd�d}tj|j�}t|jjd�d�}t	j
dt	j|j���}|j
||�dS)N)r=rr\z%Y%m%d%H%M%S)r5r6rAr~rr�r�ZCreationDaterUr�ZstrftimeZ	localtimer�r-)rr8r�Zwmic_createZ
psutil_createrrr�test_create_time7szTestProcessWMI.test_create_timeN)rfrgrh�__doc__r�r�r�r�r�r�r�r�r�r�rrrrr��s
r�c@sXeZdZdZedd��Zedd��Zdd�Zdd	�Zd
d�Z	dd
�Z
dd�Zdd�ZdS)�TestDualProcessImplementationa{
    Certain APIs on Windows have 2 internal implementations, one
    based on documented Windows APIs, another one based
    NtQuerySystemInformation() which gets called as fallback in
    case the first fails because of limited permission error.
    Here we test that the two methods return the exact same value,
    see:
    https://github.com/giampaolo/psutil/issues/304
    cCst�j|_dS)N)rr~)rrrrr�Lsz(TestDualProcessImplementation.setUpClasscCs
t�dS)N)r)rrrrr�Psz+TestDualProcessImplementation.tearDownClassc
CsPtj|j�j�}tjdtjtj��d��}|j	tj|j�j�|�WdQRXdS)Nz psutil._psplatform.cext.proc_exe)�side_effect)
rr�r~r�rrdrr+r�r-)rr�rrrrr�Ws
z'TestDualProcessImplementation.test_namec
Cs�tj|j�j�}tjdttjd�d��x}tj|j�j�}|j	t
|�t
|��xLtt
|��D]<}|j||d�|j||d�|j
||||dd�qZWWdQRXdS)Nz(psutil._psplatform.cext.proc_memory_info�msg)r�ri)rP)rr�r~r�rrdrr�EPERMr-�lenr�ZassertGreaterEqualrR)rZmem_1rZmem_2r�rrrr�^sz.TestDualProcessImplementation.test_memory_infoc
CsNtj|j�j�}tjdttjd�d��}|j	tj|j�j�|�WdQRXdS)Nz(psutil._psplatform.cext.proc_create_timer�)r�)
rr�r~r�rrdrrr�r-)rZctimerrrrr�js
z.TestDualProcessImplementation.test_create_timecCsntj|j�j�}tjdttjd�d��>}tj|j�j�}|j	|j
|j
dd�|j	|j|jdd�WdQRXdS)Nz&psutil._psplatform.cext.proc_cpu_timesr�)r�g{�G�z�?)rP)rr�r~Z	cpu_timesrrdrrr�rR�user�system)rZcpu_times_1rZcpu_times_2rrr�test_cpu_timesqsz,TestDualProcessImplementation.test_cpu_timesc
Csttj|j�j�}tjdttjd�d��D}tj|j�j�}x,t	t
|��D]}|j||||dd�qFWWdQRXdS)Nz(psutil._psplatform.cext.proc_io_countersr�)r�r0)rP)rr�r~r�rrdrrr�r�r�rR)rZ
io_counters_1rZ
io_counters_2r�rrrr�|sz.TestDualProcessImplementation.test_io_countersc
CsNtj|j�j�}tjdttjd�d��}|j	tj|j�j�|�WdQRXdS)Nz(psutil._psplatform.cext.proc_num_handlesr�)r�)
rr�r~r�rrdrrr�r-)rr�rrrrr��sz.TestDualProcessImplementation.test_num_handlesN)
rfrgrhr�r�r�r�r�r�r�r�r�r�rrrrr�@s

r�c@s|eZdZdZedd��Zedd��ZddgZdd	�Z	d
d�Z
edd
��Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�ZdS)�RemoteProcessTestCasez�Certain functions require calling ReadProcessMemory.
    This trivially works when called on the current process.
    Check that this works on other processes, especially when they
    have a different bitness.
    cCsTd}xJtjd�D]<}tj|d|gtjtjd�}|j�\}}|tt�kr|SqWdS)Nz6import sys; sys.stdout.write(str(sys.maxsize > 2**32))zC:\Python*\python.exez-c)r�stdout�stderr)�glob�
subprocess�Popen�PIPEZSTDOUT�communicater��	IS_64_BIT)�code�filenamer9�outputr�rrr�find_other_interpreter�s
z,RemoteProcessTestCase.find_other_interpretercCs@|j�}|dkrtjd��tr.tj|_||_n||_tj|_dS)Nz0could not find interpreter with opposite bitness)r�rZSkipTestr�r��
executable�python64�python32)rZother_pythonrrrr��sz RemoteProcessTestCase.setUpClassz-czimport sys; sys.stdin.read()cCsVtjj�}ttj��|d<t|jg|j|tj	d�|_
t|jg|j|tj	d�|_dS)N�THINK_OF_A_NUMBER)�env�stdin)
r+r,�copyr�r�rr��	test_argsr�r��proc32r��proc64)rr�rrr�setUp�s
zRemoteProcessTestCase.setUpcCs|jj�|jj�t�dS)N)rr�rr)rrrr�tearDown�s

zRemoteProcessTestCase.tearDowncCs
t�dS)N)r)rrrrr��sz#RemoteProcessTestCase.tearDownClasscCs@tj|jj�}|jt|j��d�|j|j�dd�|j�dS)Nr]rQ)rr�rr~r-r�r�r�)rr�rrr�test_cmdline_32�sz%RemoteProcessTestCase.test_cmdline_32cCs@tj|jj�}|jt|j��d�|j|j�dd�|j�dS)Nr]rQ)rr�rr~r-r�r�r�)rr�rrr�test_cmdline_64�sz%RemoteProcessTestCase.test_cmdline_64cCs&tj|jj�}|j|j�tj��dS)N)rr�rr~r-�cwdr+�getcwd)rr�rrr�test_cwd_32�sz!RemoteProcessTestCase.test_cwd_32cCs&tj|jj�}|j|j�tj��dS)N)rr�rr~r-rr+r)rr�rrr�test_cwd_64�sz!RemoteProcessTestCase.test_cwd_64cCs>tj|jj�}|j�}|jd|�|j|dttj	���dS)Nr�)
rr�rr~r,�assertIn�assertEqualsr�r+r�)rr��errr�test_environ_32�sz%RemoteProcessTestCase.test_environ_32cCs>tj|jj�}|j�}|jd|�|j|dttj	���dS)Nr�)
rr�rr~r,r
rr�r+r�)rr�rrrr�test_environ_64�sz%RemoteProcessTestCase.test_environ_64N)rfrgrhr��staticmethodr�r�r�r�rrr�rrrr	r
rrrrrr��s
r�c@seZdZdd�Zdd�ZdS)�TestServicescCsntdddddddg�}tdd	d
g�}tddddd
ddg�}�x,tj�D�]}|j�}|j|dt�|j|dj�d�|j|dt�|j|dt�|j|d|�|ddk	r�tj	|d�|j|dt�|j|dt�|j|dt�|j|d|�|j|d|�|j|dt�|j
�}|dk	�rLtj	|�}|j|j��tj
|j��}|j||�qFWdS)NZrunningZpaused�start�pause�continue�stopZstoppedZ	automaticZmanualZdisabledZ
start_pendingZ
pause_pendingZcontinue_pendingZstop_pendingr�rF�display_namer��statusr~ZbinpathZ
start_type�description)rBr�win_service_iterr�ZassertIsInstancer�ZassertNotEqualr�r
r�r~rZZ
is_running�win_service_getr�r-)rZvalid_statusesZvalid_start_typesZserv�datar~r��srrr�test_win_service_iter�sR

z"TestServices.test_win_service_iterc'Cspttj��j�}|jtj��}tj|d�WdQRX|j|jj|d�tj|�}t	tj
jjd�}t
jd|d��|jtj|j�WdQRXt
jd|d��|jtj|j�WdQRXt	tj
jjd�}t
jd|d��|jtj|j�WdQRXt
jd|d��|jtj|j�WdQRX|j|j�t|��|j|j�t|��|j|j�t|��|j|j�t|��dS)Nz???rFz/psutil._psplatform.cext.winservice_query_status)r�z/psutil._psplatform.cext.winservice_query_config)�nextrrr�r�rrr-Z	exceptionZWindowsError�_psplatformrWZERROR_SERVICE_DOES_NOT_EXISTrrdrr�ZERROR_ACCESS_DENIEDrr
r�rrN)rr��cmZservice�excrrr�test_win_service_get!s2




z!TestServices.test_win_service_getN)rfrgrhrr!rrrrr�s0r�__main__l)2r�r^rr�r+r�r�r�r�r�r��warningsrrZpsutil._compatrZpsutil.testsrrrrrr	r
rr�catch_warnings�simplefilterr1r�r�r5�ImportErrorr�rrW�maxsizer�rriZTestCaser rjr}r�r�r�rrf�__file__rrrr�<module>sl





<
m
A
N
^
U
tests/__pycache__/test_sunos.cpython-36.opt-1.pyc000064400000002646150466730550015734 0ustar003

��JZ�@sxdZddlZddlZddlmZddlmZddlmZddlmZejed�Gdd	�d	ej	��Z
ed
krtee�dS)zSun OS specific tests.�N)�SUNOS)�run_test_module_by_name)�sh)�unittestz
SUNOS onlyc@seZdZdd�Zdd�ZdS)�SunOSSpecificTestCasec
Cs�tdtjd�}|j�jd�dd�}|s4td��d}}xL|D]D}|j�}|d	d�\}}|tt|�d�7}|tt|�d�7}qBW||}tj�}	|j	|	j
|�|j	|	j|�|j	|	j|�dS)
Nz#env PATH=/usr/sbin:/sbin:%s swap -l�PATH�
�zno swap device(s) configuredr�i���)
r�os�environ�strip�split�
ValueError�int�psutilZswap_memory�assertEqual�total�used�free)
�self�out�linesrr�line�t�frZpsutil_swap�r�"/usr/lib64/python3.6/test_sunos.py�test_swap_memorys
z&SunOSSpecificTestCase.test_swap_memorycCs&td�}|jtj�t|jd���dS)Nz/usr/sbin/psrinfor)rrr�	cpu_count�lenr)rrrrr�test_cpu_count&sz$SunOSSpecificTestCase.test_cpu_countN)�__name__�
__module__�__qualname__rr"rrrrrsr�__main__)
�__doc__rrrZpsutil.testsrrrZskipIfZTestCaserr#�__file__rrrr�<module>s
tests/__pycache__/__init__.cpython-36.pyc000064400000072275150466730550014333 0ustar003

��JZ��L@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl
mZddl
mZddl
mZddl
mZddlZddlmZdd	lmZdd
lmZddlmZddl m!Z!dd
l"m#Z#ddl"m$Z$ddl"m%Z%ddl"m&Z&ej'd�k�rjddl(Z)nddl)Z)yddl)m*Z*Wne+k
�r�ddl*Z*YnXej'd�k�r�ddl,Z,ndZ,ddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYgDZ-ej.d"��pZdZd�kZ/d]ej0kZ1e�rpd�ndZ2e3ej4j5d#��Z6e3ej4j5d��Z7d_Z8d�Z9dZ:ej.db��s�e/�r�dcndZ;e6�s�e7�r�e8d9Z8e:d9Z:ddZ<ej=j>ej=j?ej@��e<�ZAeAdeZBeAe$df�ZCejD�jE�d�kZFej=jGej=j>ej=jHeI�didi��ZJej=j>eJdj�ZKej=jGej=jHeI��ZLeMejNdk�ZOeMedl�ZPe�ozeZQeMejNdm�ZReMejNdn�ZSeMejNdo�ZTdpejN�jU�jVkZWeMejNdq�ZXeMejNdr�ZYeMejNds�ZZeMejNdt�Z[eMedu�Z\e\�o�ej]�Z^eMedv�Z_eMedw�Z`dxdy�Zaea�Zbecejddz�Zed{d|�efe�D�Zgehe
d}ei��Zjehe
d~ei��Zkel�Zmel�Znel�Zoejpdd���Zqejpd�d���ZrGd�d��d�ejs�Ztd�d��Zueud�d�d5��Zveud�d7��Zwd�d6�Zxeud�d3��Zyeud�d���Zzd�d�d4�Z{d�dH�Z|d�dG�Z}Gd�d��d�ei�Z~e~ejde:d�d��d�dJ��Z�e~e�e�fde:d�d��d�d�dK��Z�e~e�de:d�d��d�dI��Z�d�dB�Z�d�d��Z�ej�d�dA��Z�d�d�dC�Z�e<dZfd�dF�Z�Gd�d��d�e)j��Z�e�e)_�d�d��Z�d�d=�Z�d�d>�Z�d�d<�Z�e8fd�d;�Z�d�d�d9�Z�d�d�d:�Z�d�d�dN�Z�ej�d�d�dO��Z�eedfd�dP�Z�e
jfd�dQ�Z�d�d�dR�Z�d�dS�Z�ej�d�dT��Z�d�dM�Z�d�dL�Z�d�dU�Z�d�dV�Z�d�dW�Z�d�dY�Z�e�r�ej�e<fd�dX��Z�nej�e<fd�dX��Z�dS)�z
Test utilities.
�)�print_functionN)�AF_INET)�AF_INET6)�
SOCK_DGRAM)�SOCK_STREAM)�OSX)�POSIX)�SUNOS)�WINDOWS)�
supports_ipv6)�PY3)�u)�unicode)�which��)�mock���APPVEYOR�DEVNULL�GLOBAL_TIMEOUT�MEMORY_TOLERANCE�
NO_RETRIES�PYPY�
PYTHON_EXE�ROOT_DIR�SCRIPTS_DIR�TESTFILE_PREFIX�TESTFN�TESTFN_UNICODE�TOX�TRAVIS�VALID_PROC_STATUSES�	VERBOSITY�HAS_CPU_AFFINITY�HAS_CPU_FREQ�HAS_ENVIRON�HAS_PROC_IO_COUNTERS�
HAS_IONICE�HAS_MEMORY_MAPS�HAS_PROC_CPU_NUM�
HAS_RLIMIT�HAS_SENSORS_BATTERY�HAS_BATTERY�HAS_SENSORS_FANS�HAS_SENSORS_TEMPERATURES�HAS_MEMORY_FULL_INFO�pyrun�
reap_children�get_test_subprocess�create_zombie_proc�create_proc_children_pairZThreadTaskunittest�skip_on_access_denied�skip_on_not_implemented�retry_before_failing�run_test_module_by_name�	get_suite�	run_suiteZinstall_pipZinstall_test_deps�chdir�safe_rmpath�
create_exeZdecode_pathZencode_path�unique_filename�
get_winver�get_kernel_version�
call_until�wait_for_pid�
wait_for_file�check_connection_ntuple�check_net_address�
get_free_port�unix_socket_path�bind_socket�bind_unix_socket�tcp_socketpair�unix_socketpair�create_sockets�
reload_module�import_module_by_path�warn�copyload_shared_lib�
is_namedtuple��1�trueZ__pypy__��
i�iZSILENT�z$testfnz	-internalu-ƒőő�ascii�us-asciiz..�scriptsZcpu_affinityZcpu_freq�environZio_countersZioniceZuss�memory_mapsZcpu_numZrlimitZthreads�sensors_batteryZsensors_fansZsensors_temperaturescCs�dd�}trb|tj�pP|tjjtj��pP|tdtjdd���pP|tj	�j
��}|s^td��|Stjjtj�}tjj|�s�t
|��|SdS)NcSs:ytj|dgtjtjd�Wntk
r0dSX|SdS)Nz-V)�stdout�stderr)�
subprocess�
check_call�PIPE�	Exception)�exe�rg� /usr/lib64/python3.6/__init__.py�attempt�sz_get_py_exe.<locals>.attemptzpython%s.%srz"can't find python exe real abspath)r�sys�
executable�os�path�realpathr�version_info�psutil�Processrf�
ValueError�exists�AssertionError)rirfrgrgrh�_get_py_exe�s	
ruzr+cCs g|]}|jd�rtt|��qS)ZSTATUS_)�
startswith�getattrrp)�.0�xrgrgrh�
<listcomp>�srz�AF_UNIX�SOCK_SEQPACKETcCs�tj�xbtjtd��D]P}t|t�r0tt�}nt}|j|�ryt	|�Wqt
k
rftj�YqXqWx6t
D].}yt	|�Wqrt
k
r�tj�YqrXqrWdS)N�.)r�closerl�listdirr
�
isinstancerrrvr>re�	traceback�	print_exc�_testfiles_created)�name�prefixrmrgrgrh�_cleanup_files�s



r�cCstdd�dS)NT)�	recursive)r3rgrgrgrh�_cleanup_procs�sr�c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�
ThreadTaskz6A thread task which does nothing expect staying alive.cCs&tjj|�d|_d|_tj�|_dS)NFg����MbP?)�	threading�Thread�__init__�_running�	_intervalZEvent�_flag)�selfrgrgrhr��szThreadTask.__init__cCs|jj}d||jt|�fS)Nz<%s running=%s at %#x>)�	__class__�__name__r��id)r�r�rgrgrh�__repr__�szThreadTask.__repr__cCs|j�|S)N)�start)r�rgrgrh�	__enter__�szThreadTask.__enter__cOs|j�dS)N)�stop)r��args�kwargsrgrgrh�__exit__�szThreadTask.__exit__cCs(|jrtd��tjj|�|jj�dS)zStart thread and keep it running until an explicit
        stop() request. Polls for shutdown every 'timeout' seconds.
        zalready startedN)r�rrr�r�r�r��wait)r�rgrgrhr�szThreadTask.startcCs,d|_|jj�x|jr&tj|j�qWdS)NT)r�r��set�time�sleepr�)r�rgrgrh�runs
zThreadTask.runcCs |jstd��d|_|j�dS)z8Stop thread execution and and waits until it is stopped.zalready stoppedFN)r�rr�join)r�rgrgrhr�szThreadTask.stopN)r��
__module__�__qualname__�__doc__r�r�r�r�r�r�r�rgrgrgrhr��s	r�cstj���fdd��}|S)Ncs,y
�||�Stk
r&t��YnXdS)N)rer3)r�r�)�funrgrh�wrappers

z _cleanup_on_err.<locals>.wrapper)�	functools�wraps)r�r�rg)r�rh�_cleanup_on_errsr�cKs�|jdt�|jdt�|jdtj��|jdtj�trF|jdd�|dkr�tt�dt}td	|g}t	j
|f|�}tj|�t
td
d
d�n"t	j
|f|�}tj|�t|j�|S)a{Creates a python subprocess which does nothing for 60 secs and
    return it as subprocess.Popen instance.
    If "cmd" is specified that is used instead of python.
    By default stdin and stdout are redirected to /dev/null.
    It also attemps to make sure the process is in a reasonably
    initialized state.
    The process is registered for cleanup on reap_children().
    �stdinr`�cwd�env�
creationflagsiNz:from time import sleep;open(r'%s', 'w').close();sleep(60);z-cT)�delete�empty)�
setdefaultrrl�getcwdr]r
r>�_TESTFNrrb�Popen�_subprocesses_started�addrErD�pid)�cmd�kwdsZpylineZsprocrgrgrhr4)s$




cCs�tjjt�d}tjd|tf�}tr4t|dd�}nt|�}t	j
|j�}t|ddd�}tj
|�t|�}tj|�t	j
|�}||fS)aCreate a subprocess which creates another one as in:
    A (us) -> B (child) -> C (grandchild).
    Return a (child, grandchild) tuple.
    The 2 processes are fully initialized and will live for 60 secs
    and are registered for cleanup on reap_children().
    �2a        import subprocess, os, sys, time
        s = "import os, time;"
        s += "f = open('%s', 'w');"
        s += "f.write(str(os.getpid()));"
        s += "f.close();"
        s += "time.sleep(60);"
        subprocess.Popen(['%s', '-c', s])
        time.sleep(60)
        r)r�F)r�r�)rlrm�basenamer��textwrap�dedentrr
r2rprqr�rE�remove�int�
_pids_startedr�)Z_TESTFN2�s�subpZchild1�dataZ
child2_pidZchild2rgrgrhr6Js	


cs�tjs
t�trtjtd�nt}tj	d|�}t
jtjtj
����}|jt�|j|�|jd�t|�|j�\}}zNtj|j�gggt�t|jd��}tj|�tj|��t�fdd�d�|S|j�XWdQRXdS)	z+Create a zombie process and return its PID.)r�a        import os, sys, time, socket, contextlib
        child_pid = os.fork()
        if child_pid > 0:
            time.sleep(3000)
        else:
            # this is the zombie process
            s = socket.socket(socket.AF_UNIX)
            with contextlib.closing(s):
                s.connect('%s')
                if sys.version_info < (3, ):
                    pid = str(os.getpid())
                else:
                    pid = bytes(str(os.getpid()), 'ascii')
                s.sendall(pid)
        rYics�j�S)N)�statusrg)�zprocrgrh�<lambda>�sz$create_zombie_proc.<locals>.<lambda>zret == psutil.STATUS_ZOMBIEN)rprrtr�tempfile�mktemprrr�r��
contextlib�closing�socketr{Z
settimeoutr�bind�listenr2�accept�select�filenor�Zrecvr�r�rqrCr~)Z	unix_file�src�sock�conn�_Zzpidrg)r�rhr5ms$






c
Ksr|jdd�|jdd�tjtddd��@}tj|j�|j|�|j�t	t
|jgf|�}t|j�WdQRX|S)zeRun python 'src' code string in a separate interpreter.
    Returns a subprocess.Popen instance.
    r`Nra�wtF)r��moder�)
r�r��NamedTemporaryFilerr�r�r��write�flushr4rrDr�)r�r��fr�rgrgrhr2�s
cKs�t|ttf�rdnd}tr"|r"dnd}|jd|�|jdtj�|jdtj�|jdd�|jd	|�tj|f|�}tj	|�|j
�\}}|jdkr�t|��|r�t
|�|jd
�r�|dd
�}|S)zUrun cmd in a subprocess and return its output.
    raises RuntimeError on error.
    TFir�shellr`raZuniversal_newlinesr��
NrY���)r��strrr
r�rbrdr�r�r�Zcommunicate�
returncode�RuntimeErrorrQ�endswith)r�r�r��flags�pr`rargrgrh�sh�s"


r�Fc	'Cs*dd�}|r"ttj�jdd��}nt�}x�tr�tj�}tj|j�y|j	�Wn0t
k
r~}z|jtjkrn�WYdd}~XnX|j
r�|j
j�|jr�|jj�z|jr�|jj�Wdy|j�Wn0t
k
r�}z|jtjkr�WYdd}~XnXXq*WxLt�rFtj�}ytj|�}Wn tjk
�r8||�Yq�X|j|�q�W|�r&x4|D],}y|j	�Wntjk
�r|YnX�qTWtj|td�\}}x@|D]8}td|�y|j�Wntjk
�r�YnX�q�Wtj|td�\}}|�rx|D]}td|��q�Wx|D]}||j��qWdS)	a#Terminate and wait() any subprocess started by this test suite
    and ensure that no zombies stick around to hog resources and
    create problems  when looking for refleaks.

    If resursive is True it also tries to terminate and wait()
    all grandchildren started by this process.
    cSsttj|�st|��|tj�ks(t|��y tj|�}|j�sFt|��Wntjk
r^YnXdsptd|��dS)Nrzpid %s is not gone)rpZ
pid_existsrtZpidsrqZ
is_running�
NoSuchProcess)r�r�rgrgrh�assert_gone�s
z"reap_children.<locals>.assert_goneT)r�N)�timeoutz0couldn't terminate process %r; attempting kill()zprocess %r survived kill())r�rprq�childrenr��popr�r�r�Z	terminate�OSError�errnoZESRCHr`r~rar�r�ZECHILDr�Z
wait_procsrrQ�kill)	r�r�r�r��errr�r�Zgone�alivergrgrhr3�sd





cCs�tstd��d}tj�d}x(|D] }|j�s6|dkr@||7}q"Pq"W|sVtd|��d}d}|jd�}t|d�}t|�dkr�t|d�}t|�dkr�t|d�}|||fS)	z"Return a tuple such as (2, 6, 36).z	not POSIXrTrr}zcan't parse %rrrYr)	r�NotImplementedErrorrl�uname�isdigitrr�splitr��len)r�r��c�minor�microZnums�majorrgrgrhrBs&


cCsdtstd��tj�}t|d�r*|jp&d}n(tjd|d�}|rNt|j	d��}nd}|d|d|fS)Nznot WINDOWS�service_pack_majorrz\s\d$rrY)
r
r�rjZgetwindowsversion�hasattrr��re�searchr��group)ZwvZsp�rrgrgrhrA3s
c@s@eZdZdZeddddd�fdd�Zdd	�Zd
d�Zdd
�ZdS)�retryzA retry decorator.Ng����MbP?cCst|tjd�S)N)�file)�printrjra)r�rgrgrhr�Oszretry.<lambda>cCs2|r|rtd��||_||_||_||_||_dS)Nz/timeout and retries args are mutually exclusive)rr�	exceptionr��retries�interval�logfun)r�r�r�rrrrgrgrhr�Jszretry.__init__ccs`|jr.tj�|j}xFtj�|kr*dVqWn.|jrPx&t|j�D]
}dVq@Wnx
dVqRWdS)N)r�r�r�range)r�Zstop_atr�rgrgrh�__iter__Yszretry.__iter__cCs|jdk	rtj|j�dS)N)rr�r�)r�rgrgrhr�es
zretry.sleepcs"tj����fdd��}�|_|S)Ncstd}x^�D]V}y
�||�S�jk
r^}z(|}�jdk	rD�j|��j�w
WYdd}~Xq
Xq
Wtrn|�n�dS)N)r�rr�r)r�r��excr�)r�r�rgrhr�js



zretry.__call__.<locals>.wrapper)r�r��	decorator)r�r�r�rg)r�r�rh�__call__iszretry.__call__)	r�r�r�r�rer�rr�rrgrgrgrhr�Gs
r�g����MbP?)r�rr�rcCstj|�trtjd�dS)z�Wait for pid to show up in the process list then return.
    Used in the test suite to give time the sub process to initialize.
    g{�G�z�?N)rprqr
r�r�)r�rgrgrhrD�s
Tc	Cs<t|d��}|j�}WdQRX|s*|s*t�|r8tj|�|S)z8Wait for a file to be written on disk with some content.�rbN)�open�readrtrlr�)Zfnamer�r�r�r�rgrgrhrE�s
cCs|�}t|�st�|S)zVKeep calling function for timeout secs and exit if eval()
    expression is True.
    )�evalrt)r��expr�retrgrgrhrC�scCsfy0tj|�}tj|j�r$tj|�n
tj|�Wn0tk
r`}z|jtjkrP�WYdd}~XnXdS)z>Convenience function for removing temporary test files or dirsN)	rl�stat�S_ISDIR�st_mode�rmdirr�r�r��ENOENT)rm�str�rgrgrhr>�s
cCsDytj|�Wn0tk
r>}z|jtjkr.�WYdd}~XnXdS)z-Convenience function for creating a directoryN)rl�mkdirr�r�ZEEXIST)�dirr�rgrgrh�
safe_mkdir�s
rccs.tj�}ztj|�dVWdtj|�XdS)z@Context manager which temporarily changes the current directory.N)rlr�r=)�dirname�curdirrgrgrhr=�s


cCs�tjj|�st|��|r�td�s*td��t|t�r>tj	d�}t|t
�sPt|��tjdddd��}|j
|�WdQRXztjd|jd	|g�Wdt|j�Xn.tjt|�tr�tj|�}tj||jtjB�dS)
z1Creates an executable file in the given location.�gcczgcc is not installedz�
                #include <unistd.h>
                int main() {
                    pause();
                    return 1;
                }
                z.cFr�)�suffixr�r�Nz-o)rlrmrsrtrrrr��boolr�r�r�r�r�r�rbrcr�r>�shutil�copyfilerrr�chmodr�S_IEXEC)ZoutpathZc_coder�rrgrgrhr?�s$

cCstj||d�S)N)r�r)r�r�)r�rrgrgrhr@�sc@s(eZdZdd�Zeejd�s$ejjZdS)�TestCasecCsd|jj|jj|jfS)Nz%s.%s.%s)r�r�r�Z_testMethodName)r�rgrgrh�__str__�szTestCase.__str__�assertRaisesRegexN)	r�r�r�r!r��unittestr ZassertRaisesRegexpr"rgrgrgrhr �sr cCs$dtjkrdtjd<tjjj�dS)NZPSUTIL_TESTINGrU)rlr]rpZ_psplatformZcextZset_testingrgrgrgrh�_setup_testss

r$cCs`dd�tjt�D�}dtjkr,dd�|D�}tj�}x&|D]}d|}|jtjj|��q:W|S)NcSs<g|]4}|jd�r|jd�r|jd�rtjj|�d�qS)z.pyZtest_Ztest_memory_leaksr)r�rvrlrm�splitext)rxryrgrgrhrzszget_suite.<locals>.<listcomp>ZWHEELHOUSE_UPLOADER_USERNAMEcSsg|]}|jd�s|�qS)�osx�posix�linux)r&r'r()r�)rxryrgrgrhrzszpsutil.tests.%s)	rlr�HEREr]r#�	TestSuite�addTest�defaultTestLoader�loadTestsFromName)Ztestmods�suiteZtmrgrgrhr;
s

cCs8t�tjtd�jt��}|j�}tj|r.dnd�dS)N)�	verbosityrrY)	r$r#�TextTestRunnerr$r�r;�
wasSuccessfulrj�exit)�result�successrgrgrhr<scCsht�tjjtjj|��d}tj�}|jtjj	|��tj
td�j|�}|j
�}tj|r^dnd�dS)Nr)r/rY)r$rlrmr%r�r#r*r+r,r-r0r$r�r1rjr2)r�r.r3r4rgrgrhr:#scCsttd|d�S)zZDecorator which runs a test function and retries N times before
    actually failing.
    N)r�r�r)r�rt)rrgrgrhr9/scs�fdd�}|S)z,Decorator to Ignore AccessDenied exceptions.cstj����fdd��}|S)Ncs>y
�||�Stjk
r8�dk	r*�s*�tjd��YnXdS)Nzraises AccessDenied)rpZAccessDeniedr#�SkipTest)r�r�)r��only_ifrgrhr�9s
z9skip_on_access_denied.<locals>.decorator.<locals>.wrapper)r�r�)r�r�)r6)r�rhr8s	z(skip_on_access_denied.<locals>.decoratorrg)r6rrg)r6rhr76scs�fdd�}|S)z3Decorator to Ignore NotImplementedError exceptions.cstj����fdd��}|S)NcsFy
�||�Stk
r@�dk	r(�s(�d�j}tj|��YnXdS)Nz4%r was skipped because it raised NotImplementedError)r�r�r#r5)r�r��msg)r�r6rgrhr�Is
z;skip_on_not_implemented.<locals>.decorator.<locals>.wrapper)r�r�)r�r�)r6)r�rhrHsz*skip_on_not_implemented.<locals>.decoratorrg)r6rrg)r6rhr8Fs
�	127.0.0.1cCsFtjtj���.}|jtjtjd�|j|df�|j�dSQRXdS)zReturn an unused TCP port.rYrN)r�r�r��
setsockopt�
SOL_SOCKET�SO_REUSEADDRr��getsockname)�hostr�rgrgrhrH]sccsJtjs
t�t|d�}z
|VWdytj|�Wntk
rBYnXXdS)zaA context manager which returns a non-existent file name
    and tries to delete it on exit.
    )rN)rprrtr@rl�unlinkr�)rrmrgrgrhrIes


cCs||dkr|ttfkrd}tj||�}y4|jtjtjd�|j|�|tjkrV|jd�|St	k
rv|j
��YnXdS)zBinds a generic socket.NrTrrYrX)rTr)rrr�r9r:r;r�rr�rer~)�family�type�addrr�rgrgrhrJus


cCsttjs
t�tjj|�s t|��tjtj|�}y"|j|�|tj	krN|j
d�Wntk
rn|j��YnX|S)zBind a UNIX socket.rX)
rprrtrlrmrsr�r{r�rr�rer~)r�r@r�rgrgrhrK�s


cCs�tjtj|t����}|j|�|jd�|j�}tj|t�}y@|j|�|j�}x(|j�\}}||krn||fS|j	�qRWWnt
k
r�|j	��YnXWdQRXdS)z^Build a pair of TCP sockets connected to each other.
    Return a (server, client) tuple.
    rXN)r�r�r�rr�r�r<�connectr�r~r�)r?rAZllr�Zcaddr�argrgrhrL�s 


cCs�tjs
t�d}}y@t|tjd�}|jd�tjtjtj�}|jd�|j|�Wn6t	k
r�|dk	rr|j
�|dk	r�|j
��YnX||fS)z�Build a pair of UNIX sockets connected to each other through
    the same UNIX file name.
    Return a (server, client) tuple.
    N)r@r)rprrtrKr�rZsetblockingr{rBrer~)r�ZserverZclientrgrgrhrM�s


ccs�g}d}}z�|jttjtj��|jttjtj��t�rd|jttjtj��|jttjtj��tr�t	r�t
�j�}t
�j�}t|�\}}t
|tjd�}x|||fD]}|j|�q�W|VWdx|D]}|j�q�W|dk	r�t|�|dk	r�t|�XdS)z1Open as many socket families / types as possible.N)r@)�appendrJr�rrrrrr�HAS_CONNECTIONS_UNIXrIr�rMrKr~r>)ZsocksZfname1Zfname2�s1�s2Zs3r�rgrgrhrN�s,



cCsddl}tr$tr$t|tj�s$t|��|tjkr�dd�|jd�D�}t	|�dksVt|��x,|D]$}d|kordkns\t|��q\Wts�t
|�}|j|�nb|tjkr�t|t
�s�t|��ts�t
|�}|j|�n.|tjkr�tjd|�dk	s�t|��n
td	|��dS)
z[Check a net address validity. Supported families are IPv4,
    IPv6 and MAC addresses.
    rNcSsg|]}t|��qSrg)r�)rxryrgrgrhrz�sz%check_net_address.<locals>.<listcomp>r}r�z([a-fA-F0-9]{2}[:|\-]?){6}zunknown family %r)�	ipaddress�enumrr��IntEnumrtr�rr�r�rZIPv4Addressrr�ZIPv6AddressrpZAF_LINKr��matchrr)rAr?rIZoctsZnumrgrgrhrG�s&

$

c(Cs�t|�dkst|��t|�dk}t|dd�dk}|d|jksBt�|d|jksTt�|d|jksft�|d|jksxt�|d|jks�t�|d	|jks�t�|r�|d|j	ks�t�|�rn|jdks�t|��t
td
�o�t�rnytj
|j|j|j�}Wn>tjtfk
�r2}z|jdtjk�r"�WYdd}~Xn<Xtj|��*|j|jk�sRt�|j|jk�sdt�WdQRX|jtttfk�s�tt|j���|jttfk�r"|jtk�rFtj|j|j�}tj|��Vy|j|jddf�Wn6tjk
�r}z|jtjk�r�WYdd}~XnXWdQRXn$|jtk�rF|jtjk�sFt|j��|jtttfk�sftt|j���|jtk�r�|jtjk�s�t|j��x�|j|jfD]�}|jttfk�rt |t!��s�t|��|�sʐq�t |j"t#��s�t|j"��d|j"k�o�dkn�s
t|j"��t$|j%|j�n |jtk�r�t |t&��s�t|���q�Wt |jt&��sVt|��d
d�t't�D�}|j|k�s|t|��dS)z*Check validity of a connection namedtuple.rWr�fdrYrrrr��fromfdNi��cSs g|]}|jd�rtt|��qS)ZCONN_)rvrwrp)rxryrgrgrhrz=sz+check_connection_ntuple.<locals>.<listcomp>)rWrr�r�)(r�rtrwrMr?r@ZladdrZraddrr�r�r�r�r
rO�errorr�r�r�ZEBADFr�r�rrr{�reprr�Z
EADDRNOTAVAILrpZ	CONN_NONErrr|r��tupleZportr�rGZipr�r)r�Zhas_pidZhas_fdZdupsockr�r�rAZvalidsrgrgrhrF�sf  (cCsLyddl}t|d�st�Wn"tk
r<ddl}|j|�SX|j|�SdS)z,Backport of importlib.reload of Python 3.3+.rN�reload)�	importlibr��ImportError�imprS)�modulerTrVrgrgrhrOFs
cCs�tjjtjj|��d}tjddkr:ddl}|j||�Stjdd�dkrfddlm	}|||�j
�Sddl}|jj
||�}|jj|�}|jj|�|SdS)Nrrrr)�SourceFileLoader)rr)rlrmr%r�rjrorVZload_sourceZimportlib.machineryrX�load_module�importlib.util�util�spec_from_file_location�module_from_spec�loader�exec_module)rmr�rVrXrT�spec�modrgrgrhrPSscCstj|t�dS)zRaise a warning msg.N)�warningsrQ�UserWarning)r7rgrgrhrQhscCsVt|�}|j}t|�dks&|dtkr*dSt|dd�}t|t�sDdStdd�|D��S)z-Check if object is an instance of namedtuple.rYrF�_fieldsNcss|]}t|�tkVqdS)N)r@r�)rx�nrgrgrh�	<genexpr>vsz is_namedtuple.<locals>.<genexpr>)r@�	__bases__r�rRrwr��all)ry�t�br�rgrgrhrSms
c#sfd�tj|�d�}�fdd�tj�j�D�}tj|�}tj||�zt	j
|�|VWdt|�XdS)z�Ctx manager which picks up a random shared CO lib used
        by this process, copies it in another location and loads it
        in memory via ctypes. Return the new absolutized path.
        z.so)r�rcs6g|].}tjj|j�d�krd|jj�kr|j�qS)rY�python)rlrmr%�lower)rxry)�extrgrhrz�sz'copyload_shared_lib.<locals>.<listcomp>N)r�r�rprqr^�random�choicerr�ctypesZCDLLr>)�
dst_prefix�dst�libsr�rg)rmrhrRzs


c	#s�ddlm}ddlm}d�tj|�d�}�fdd�tj�j�D�}tj	|�}t
j||�d}ztj|�}|VWd|dk	r�tj
jj}|jg|_||j�}|dkr�|�t|�XdS)	z�Ctx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        r)�wintypes)�WinErrorz.dll)r�rcsPg|]H}tjj|j�dj��krdtjj|j�j�krd|jj�kr|j�qS)rYrkZwow64)rlrmr%rlr�)rxry)rmrgrhrz�sz'copyload_shared_lib.<locals>.<listcomp>N)rprtrur�r�rprqr^rnrorrZWinDLLZwindllZkernel32�FreeLibraryZHMODULEZargtypesZ_handler>)	rqrtrurrrsr��cfilervr
rg)rmrhrR�s$





)rr)rr)rUrV)rWrri�)rZr[)N)F)TF)N)N)N)r8)rT�rTr)rx)�r�Z
__future__r�atexitr�rpr�r�rlrnr�r�rr�rrbrjr�r�r�r�r�rbrrrrrprrr	r
Zpsutil._commonrZpsutil._compatrr
rrroZ	unittest2r#rrUrJ�__all__�getenvr!�builtin_module_namesrZ	WIN_VISTArr]�getr"rrrrr$rrmr�rnr�rr�r �getfilesystemencodingrlZASCII_FS�abspathr�__file__rrr)r�rqr%r&rEr'r(r)Zmemory_full_infordr1r*r+r,ZHAS_THREADSr-r_r.r/r0rurr	�devnullrrr#rw�objectr{r|r�r�r�r��registerr�r�r�r�r�r4r6r5r2r�r3rBrAr�r�rD�EnvironmentErrorrtrErCr>r�contextmanagerr=r?r@r r$r;r<r:r9r7r8rHrIrJrKrLrMrNrGrFrOrPrQrSrRrgrgrgrh�<module>	sN








 




0 #%
_:


	
	



L
tests/__pycache__/__init__.cpython-36.opt-1.pyc000064400000067760150466730550015275 0ustar003

��JZ��L@s�dZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlZddlZddlZddlZddlZddlZddlZddlZddl
mZddl
mZddl
mZddl
mZddlZddlmZdd	lmZdd
lmZddlmZddl m!Z!dd
l"m#Z#ddl"m$Z$ddl"m%Z%ddl"m&Z&ej'd�k�rjddl(Z)nddl)Z)yddl)m*Z*Wne+k
�r�ddl*Z*YnXej'd�k�r�ddl,Z,ndZ,ddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYgDZ-ej.d"��pZdZd�kZ/d]ej0kZ1e�rpd�ndZ2e3ej4j5d#��Z6e3ej4j5d��Z7d_Z8d�Z9dZ:ej.db��s�e/�r�dcndZ;e6�s�e7�r�e8d9Z8e:d9Z:ddZ<ej=j>ej=j?ej@��e<�ZAeAdeZBeAe$df�ZCejD�jE�d�kZFej=jGej=j>ej=jHeI�didi��ZJej=j>eJdj�ZKej=jGej=jHeI��ZLeMejNdk�ZOeMedl�ZPe�ozeZQeMejNdm�ZReMejNdn�ZSeMejNdo�ZTdpejN�jU�jVkZWeMejNdq�ZXeMejNdr�ZYeMejNds�ZZeMejNdt�Z[eMedu�Z\e\�o�ej]�Z^eMedv�Z_eMedw�Z`dxdy�Zaea�Zbecejddz�Zed{d|�efe�D�Zgehe
d}ei��Zjehe
d~ei��Zkel�Zmel�Znel�Zoejpdd���Zqejpd�d���ZrGd�d��d�ejs�Ztd�d��Zueud�d�d5��Zveud�d7��Zwd�d6�Zxeud�d3��Zyeud�d���Zzd�d�d4�Z{d�dH�Z|d�dG�Z}Gd�d��d�ei�Z~e~ejde:d�d��d�dJ��Z�e~e�e�fde:d�d��d�d�dK��Z�e~e�de:d�d��d�dI��Z�d�dB�Z�d�d��Z�ej�d�dA��Z�d�d�dC�Z�e<dZfd�dF�Z�Gd�d��d�e)j��Z�e�e)_�d�d��Z�d�d=�Z�d�d>�Z�d�d<�Z�e8fd�d;�Z�d�d�d9�Z�d�d�d:�Z�d�d�dN�Z�ej�d�d�dO��Z�eedfd�dP�Z�e
jfd�dQ�Z�d�d�dR�Z�d�dS�Z�ej�d�dT��Z�d�dM�Z�d�dL�Z�d�dU�Z�d�dV�Z�d�dW�Z�d�dY�Z�e�r�ej�e<fd�dX��Z�nej�e<fd�dX��Z�dS)�z
Test utilities.
�)�print_functionN)�AF_INET)�AF_INET6)�
SOCK_DGRAM)�SOCK_STREAM)�OSX)�POSIX)�SUNOS)�WINDOWS)�
supports_ipv6)�PY3)�u)�unicode)�which��)�mock���APPVEYOR�DEVNULL�GLOBAL_TIMEOUT�MEMORY_TOLERANCE�
NO_RETRIES�PYPY�
PYTHON_EXE�ROOT_DIR�SCRIPTS_DIR�TESTFILE_PREFIX�TESTFN�TESTFN_UNICODE�TOX�TRAVIS�VALID_PROC_STATUSES�	VERBOSITY�HAS_CPU_AFFINITY�HAS_CPU_FREQ�HAS_ENVIRON�HAS_PROC_IO_COUNTERS�
HAS_IONICE�HAS_MEMORY_MAPS�HAS_PROC_CPU_NUM�
HAS_RLIMIT�HAS_SENSORS_BATTERY�HAS_BATTERY�HAS_SENSORS_FANS�HAS_SENSORS_TEMPERATURES�HAS_MEMORY_FULL_INFO�pyrun�
reap_children�get_test_subprocess�create_zombie_proc�create_proc_children_pairZThreadTaskunittest�skip_on_access_denied�skip_on_not_implemented�retry_before_failing�run_test_module_by_name�	get_suite�	run_suiteZinstall_pipZinstall_test_deps�chdir�safe_rmpath�
create_exeZdecode_pathZencode_path�unique_filename�
get_winver�get_kernel_version�
call_until�wait_for_pid�
wait_for_file�check_connection_ntuple�check_net_address�
get_free_port�unix_socket_path�bind_socket�bind_unix_socket�tcp_socketpair�unix_socketpair�create_sockets�
reload_module�import_module_by_path�warn�copyload_shared_lib�
is_namedtuple��1�trueZ__pypy__��
i�iZSILENT�z$testfnz	-internalu-ƒőő�ascii�us-asciiz..�scriptsZcpu_affinityZcpu_freq�environZio_countersZioniceZuss�memory_mapsZcpu_numZrlimitZthreads�sensors_batteryZsensors_fansZsensors_temperaturescCsxdd�}trb|tj�pP|tjjtj��pP|tdtjdd���pP|tj	�j
��}|s^td��|Stjjtj�}|SdS)NcSs:ytj|dgtjtjd�Wntk
r0dSX|SdS)Nz-V)�stdout�stderr)�
subprocess�
check_call�PIPE�	Exception)�exe�rg� /usr/lib64/python3.6/__init__.py�attempt�sz_get_py_exe.<locals>.attemptzpython%s.%srz"can't find python exe real abspath)r�sys�
executable�os�path�realpathr�version_info�psutil�Processrf�
ValueError)rirfrgrgrh�_get_py_exe�s	
rszr+cCs g|]}|jd�rtt|��qS)ZSTATUS_)�
startswith�getattrrp)�.0�xrgrgrh�
<listcomp>�srx�AF_UNIX�SOCK_SEQPACKETcCs�tj�xbtjtd��D]P}t|t�r0tt�}nt}|j|�ryt	|�Wqt
k
rftj�YqXqWx6t
D].}yt	|�Wqrt
k
r�tj�YqrXqrWdS)N�.)r�closerl�listdirr
�
isinstancerrrtr>re�	traceback�	print_exc�_testfiles_created)�name�prefixrmrgrgrh�_cleanup_files�s



r�cCstdd�dS)NT)�	recursive)r3rgrgrgrh�_cleanup_procs�sr�c@sHeZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dS)�
ThreadTaskz6A thread task which does nothing expect staying alive.cCs&tjj|�d|_d|_tj�|_dS)NFg����MbP?)�	threading�Thread�__init__�_running�	_intervalZEvent�_flag)�selfrgrgrhr��szThreadTask.__init__cCs|jj}d||jt|�fS)Nz<%s running=%s at %#x>)�	__class__�__name__r��id)r�r�rgrgrh�__repr__�szThreadTask.__repr__cCs|j�|S)N)�start)r�rgrgrh�	__enter__�szThreadTask.__enter__cOs|j�dS)N)�stop)r��args�kwargsrgrgrh�__exit__�szThreadTask.__exit__cCs(|jrtd��tjj|�|jj�dS)zStart thread and keep it running until an explicit
        stop() request. Polls for shutdown every 'timeout' seconds.
        zalready startedN)r�rrr�r�r�r��wait)r�rgrgrhr�szThreadTask.startcCs,d|_|jj�x|jr&tj|j�qWdS)NT)r�r��set�time�sleepr�)r�rgrgrh�runs
zThreadTask.runcCs |jstd��d|_|j�dS)z8Stop thread execution and and waits until it is stopped.zalready stoppedFN)r�rr�join)r�rgrgrhr�szThreadTask.stopN)r��
__module__�__qualname__�__doc__r�r�r�r�r�r�r�rgrgrgrhr��s	r�cstj���fdd��}|S)Ncs,y
�||�Stk
r&t��YnXdS)N)rer3)r�r�)�funrgrh�wrappers

z _cleanup_on_err.<locals>.wrapper)�	functools�wraps)r�r�rg)r�rh�_cleanup_on_errsr�cKs�|jdt�|jdt�|jdtj��|jdtj�trF|jdd�|dkr�tt�dt}td	|g}t	j
|f|�}tj|�t
td
d
d�n"t	j
|f|�}tj|�t|j�|S)a{Creates a python subprocess which does nothing for 60 secs and
    return it as subprocess.Popen instance.
    If "cmd" is specified that is used instead of python.
    By default stdin and stdout are redirected to /dev/null.
    It also attemps to make sure the process is in a reasonably
    initialized state.
    The process is registered for cleanup on reap_children().
    �stdinr`�cwd�env�
creationflagsiNz:from time import sleep;open(r'%s', 'w').close();sleep(60);z-cT)�delete�empty)�
setdefaultrrl�getcwdr]r
r>�_TESTFNrrb�Popen�_subprocesses_started�addrErD�pid)�cmd�kwdsZpylineZsprocrgrgrhr4)s$




cCs�tjjt�d}tjd|tf�}tr4t|dd�}nt|�}t	j
|j�}t|ddd�}tj
|�t|�}tj|�t	j
|�}||fS)aCreate a subprocess which creates another one as in:
    A (us) -> B (child) -> C (grandchild).
    Return a (child, grandchild) tuple.
    The 2 processes are fully initialized and will live for 60 secs
    and are registered for cleanup on reap_children().
    �2a        import subprocess, os, sys, time
        s = "import os, time;"
        s += "f = open('%s', 'w');"
        s += "f.write(str(os.getpid()));"
        s += "f.close();"
        s += "time.sleep(60);"
        subprocess.Popen(['%s', '-c', s])
        time.sleep(60)
        r)r�F)r�r�)rlrm�basenamer��textwrap�dedentrr
r2rprqr�rE�remove�int�
_pids_startedr�)Z_TESTFN2�s�subpZchild1�dataZ
child2_pidZchild2rgrgrhr6Js	


cs�trtjtd�nt}tjd|�}tjt	j	t	j
����}|jt�|j
|�|jd�t|�|j�\}}zNtj|j�gggt�t|jd��}tj|�tj|��t�fdd�d�|S|j�XWdQRXdS)	z+Create a zombie process and return its PID.)r�a        import os, sys, time, socket, contextlib
        child_pid = os.fork()
        if child_pid > 0:
            time.sleep(3000)
        else:
            # this is the zombie process
            s = socket.socket(socket.AF_UNIX)
            with contextlib.closing(s):
                s.connect('%s')
                if sys.version_info < (3, ):
                    pid = str(os.getpid())
                else:
                    pid = bytes(str(os.getpid()), 'ascii')
                s.sendall(pid)
        rYics�j�S)N)Zstatusrg)�zprocrgrh�<lambda>�sz$create_zombie_proc.<locals>.<lambda>zret == psutil.STATUS_ZOMBIEN)r�tempfile�mktemprrr�r��
contextlib�closing�socketryZ
settimeoutr�bind�listenr2�accept�select�filenor�Zrecvr�r�rprqrCr|)Z	unix_file�src�sock�conn�_Zzpidrg)r�rhr5ms"





c
Ksr|jdd�|jdd�tjtddd��@}tj|j�|j|�|j�t	t
|jgf|�}t|j�WdQRX|S)zeRun python 'src' code string in a separate interpreter.
    Returns a subprocess.Popen instance.
    r`Nra�wtF)r��moder�)
r�r��NamedTemporaryFilerr�r�r��write�flushr4rrDr�)r�r��fr�rgrgrhr2�s
cKs�t|ttf�rdnd}tr"|r"dnd}|jd|�|jdtj�|jdtj�|jdd�|jd	|�tj|f|�}tj	|�|j
�\}}|jdkr�t|��|r�t
|�|jd
�r�|dd
�}|S)zUrun cmd in a subprocess and return its output.
    raises RuntimeError on error.
    TFir�shellr`raZuniversal_newlinesr��
NrY���)r~�strrr
r�rbrdr�r�r�Zcommunicate�
returncode�RuntimeErrorrQ�endswith)r�r�r��flags�pr`rargrgrh�sh�s"


r�Fc	'Cs*dd�}|r"ttj�jdd��}nt�}x�tr�tj�}tj|j�y|j	�Wn0t
k
r~}z|jtjkrn�WYdd}~XnX|j
r�|j
j�|jr�|jj�z|jr�|jj�Wdy|j�Wn0t
k
r�}z|jtjkr�WYdd}~XnXXq*WxLt�rFtj�}ytj|�}Wn tjk
�r8||�Yq�X|j|�q�W|�r&x4|D],}y|j	�Wntjk
�r|YnX�qTWtj|td�\}}x@|D]8}td|�y|j�Wntjk
�r�YnX�q�Wtj|td�\}}|�rx|D]}td|��q�Wx|D]}||j��qWdS)	a#Terminate and wait() any subprocess started by this test suite
    and ensure that no zombies stick around to hog resources and
    create problems  when looking for refleaks.

    If resursive is True it also tries to terminate and wait()
    all grandchildren started by this process.
    cSs*ytj|�}Wntjk
r$YnXdS)N)rprq�
NoSuchProcess)r�r�rgrgrh�assert_gone�s
z"reap_children.<locals>.assert_goneT)r�N)�timeoutz0couldn't terminate process %r; attempting kill()zprocess %r survived kill())r�rprq�childrenr��popr�r�r�Z	terminate�OSError�errnoZESRCHr`r|rar�r�ZECHILDr�Z
wait_procsrrQ�kill)	r�r�r�r��errr�r�Zgone�alivergrgrhr3�sd





cCs�tstd��d}tj�d}x(|D] }|j�s6|dkr@||7}q"Pq"W|sVtd|��d}d}|jd�}t|d�}t|�dkr�t|d�}t|�dkr�t|d�}|||fS)	z"Return a tuple such as (2, 6, 36).z	not POSIXrTrr{zcan't parse %rrrYr)	r�NotImplementedErrorrl�uname�isdigitrr�splitr��len)r�r��c�minor�microZnums�majorrgrgrhrBs&


cCsdtstd��tj�}t|d�r*|jp&d}n(tjd|d�}|rNt|j	d��}nd}|d|d|fS)Nznot WINDOWS�service_pack_majorrz\s\d$rrY)
r
r�rjZgetwindowsversion�hasattrr��re�searchr��group)ZwvZsp�rrgrgrhrA3s
c@s@eZdZdZeddddd�fdd�Zdd	�Zd
d�Zdd
�ZdS)�retryzA retry decorator.Ng����MbP?cCst|tjd�S)N)�file)�printrjra)r�rgrgrhr�Oszretry.<lambda>cCs2|r|rtd��||_||_||_||_||_dS)Nz/timeout and retries args are mutually exclusive)rr�	exceptionr��retries�interval�logfun)r�r�r�r�r�r�rgrgrhr�Jszretry.__init__ccs`|jr.tj�|j}xFtj�|kr*dVqWn.|jrPx&t|j�D]
}dVq@Wnx
dVqRWdS)N)r�r�r��range)r�Zstop_atr�rgrgrh�__iter__Yszretry.__iter__cCs|jdk	rtj|j�dS)N)r�r�r�)r�rgrgrhr�es
zretry.sleepcs"tj����fdd��}�|_|S)Ncstd}x^�D]V}y
�||�S�jk
r^}z(|}�jdk	rD�j|��j�w
WYdd}~Xq
Xq
Wtrn|�n�dS)N)r�r�r�r)r�r��excr�)r�r�rgrhr�js



zretry.__call__.<locals>.wrapper)r�r��	decorator)r�r�r�rg)r�r�rh�__call__iszretry.__call__)	r�r�r�r�rer�rr�rrgrgrgrhr�Gs
r�g����MbP?)r�r�r�r�cCstj|�trtjd�dS)z�Wait for pid to show up in the process list then return.
    Used in the test suite to give time the sub process to initialize.
    g{�G�z�?N)rprqr
r�r�)r�rgrgrhrD�s
Tc	Cs4t|d��}|j�}WdQRX|s"|r0tj|�|S)z8Wait for a file to be written on disk with some content.�rbN)�open�readrlr�)Zfnamer�r�r�r�rgrgrhrE�s
cCs
|�}|S)zVKeep calling function for timeout secs and exit if eval()
    expression is True.
    rg)r��expr�retrgrgrhrC�scCsfy0tj|�}tj|j�r$tj|�n
tj|�Wn0tk
r`}z|jtjkrP�WYdd}~XnXdS)z>Convenience function for removing temporary test files or dirsN)	rl�stat�S_ISDIR�st_mode�rmdirr�r�r��ENOENT)rm�str�rgrgrhr>�s
cCsDytj|�Wn0tk
r>}z|jtjkr.�WYdd}~XnXdS)z-Convenience function for creating a directoryN)rl�mkdirr�r�ZEEXIST)�dirr�rgrgrh�
safe_mkdir�s
rccs.tj�}ztj|�dVWdtj|�XdS)z@Context manager which temporarily changes the current directory.N)rlr�r=)�dirname�curdirrgrgrhr=�s


cCs�|rvtd�std��t|t�r(tjd�}tjdddd��}|j|�WdQRXzt	j
d|jd	|g�Wdt|j�Xn.t
jt|�tr�tj|�}tj||jtjB�dS)
z1Creates an executable file in the given location.�gcczgcc is not installedz�
                #include <unistd.h>
                int main() {
                    pause();
                    return 1;
                }
                z.cFr�)�suffixr�r�Nz-o)rrrr~�boolr�r�r�r�r�rbrcr�r>�shutil�copyfilerrrlr
�chmodr�S_IEXEC)ZoutpathZc_coder�rrgrgrhr?�s 

cCstj||d�S)N)r�r)r�r�)r�rrgrgrhr@�sc@s(eZdZdd�Zeejd�s$ejjZdS)�TestCasecCsd|jj|jj|jfS)Nz%s.%s.%s)r�r�r�Z_testMethodName)r�rgrgrh�__str__�szTestCase.__str__�assertRaisesRegexN)	r�r�r�rr��unittestrZassertRaisesRegexprrgrgrgrhr�srcCs$dtjkrdtjd<tjjj�dS)NZPSUTIL_TESTINGrU)rlr]rpZ_psplatformZcextZset_testingrgrgrgrh�_setup_testss

r cCs`dd�tjt�D�}dtjkr,dd�|D�}tj�}x&|D]}d|}|jtjj|��q:W|S)NcSs<g|]4}|jd�r|jd�r|jd�rtjj|�d�qS)z.pyZtest_Ztest_memory_leaksr)r�rtrlrm�splitext)rvrwrgrgrhrxszget_suite.<locals>.<listcomp>ZWHEELHOUSE_UPLOADER_USERNAMEcSsg|]}|jd�s|�qS)�osx�posix�linux)r"r#r$)r�)rvrwrgrgrhrxszpsutil.tests.%s)	rlr}�HEREr]r�	TestSuite�addTest�defaultTestLoader�loadTestsFromName)Ztestmods�suiteZtmrgrgrhr;
s

cCs8t�tjtd�jt��}|j�}tj|r.dnd�dS)N)�	verbosityrrY)	r r�TextTestRunnerr$r�r;�
wasSuccessfulrj�exit)�result�successrgrgrhr<scCsht�tjjtjj|��d}tj�}|jtjj	|��tj
td�j|�}|j
�}tj|r^dnd�dS)Nr)r+rY)r rlrmr!r�rr&r'r(r)r,r$r�r-rjr.)r�r*r/r0rgrgrhr:#scCsttd|d�S)zZDecorator which runs a test function and retries N times before
    actually failing.
    N)r�r�r�)r��AssertionError)r�rgrgrhr9/scs�fdd�}|S)z,Decorator to Ignore AccessDenied exceptions.cstj����fdd��}|S)Ncs>y
�||�Stjk
r8�dk	r*�s*�tjd��YnXdS)Nzraises AccessDenied)rpZAccessDeniedr�SkipTest)r�r�)r��only_ifrgrhr�9s
z9skip_on_access_denied.<locals>.decorator.<locals>.wrapper)r�r�)r�r�)r3)r�rhr8s	z(skip_on_access_denied.<locals>.decoratorrg)r3rrg)r3rhr76scs�fdd�}|S)z3Decorator to Ignore NotImplementedError exceptions.cstj����fdd��}|S)NcsFy
�||�Stk
r@�dk	r(�s(�d�j}tj|��YnXdS)Nz4%r was skipped because it raised NotImplementedError)r�r�rr2)r�r��msg)r�r3rgrhr�Is
z;skip_on_not_implemented.<locals>.decorator.<locals>.wrapper)r�r�)r�r�)r3)r�rhrHsz*skip_on_not_implemented.<locals>.decoratorrg)r3rrg)r3rhr8Fs
�	127.0.0.1cCsFtjtj���.}|jtjtjd�|j|df�|j�dSQRXdS)zReturn an unused TCP port.rYrN)r�r�r��
setsockopt�
SOL_SOCKET�SO_REUSEADDRr��getsockname)�hostr�rgrgrhrH]sccs@t|d�}z
|VWdytj|�Wntk
r8YnXXdS)zaA context manager which returns a non-existent file name
    and tries to delete it on exit.
    )rN)r@rl�unlinkr�)rrmrgrgrhrIes

cCs||dkr|ttfkrd}tj||�}y4|jtjtjd�|j|�|tjkrV|jd�|St	k
rv|j
��YnXdS)zBinds a generic socket.NrTrrYrX)rTr)rrr�r6r7r8r�rr�rer|)�family�type�addrr�rgrgrhrJus


cCsTtjtj|�}y"|j|�|tjkr.|jd�Wntk
rN|j��YnX|S)zBind a UNIX socket.rX)r�ryr�rr�rer|)r�r=r�rgrgrhrK�s

cCs�tjtj|t����}|j|�|jd�|j�}tj|t�}y@|j|�|j�}x(|j�\}}||krn||fS|j	�qRWWnt
k
r�|j	��YnXWdQRXdS)z^Build a pair of TCP sockets connected to each other.
    Return a (server, client) tuple.
    rXN)r�r�r�rr�r�r9�connectr�r|r�)r<r>Zllr�Zcaddr�argrgrhrL�s 


cCs�d}}y@t|tjd�}|jd�tjtjtj�}|jd�|j|�Wn6tk
r~|dk	rh|j�|dk	rx|j��YnX||fS)z�Build a pair of UNIX sockets connected to each other through
    the same UNIX file name.
    Return a (server, client) tuple.
    N)r=r)rKr�rZsetblockingryr?rer|)r�ZserverZclientrgrgrhrM�s

ccs�g}d}}z�|jttjtj��|jttjtj��t�rd|jttjtj��|jttjtj��tr�t	r�t
�j�}t
�j�}t|�\}}t
|tjd�}x|||fD]}|j|�q�W|VWdx|D]}|j�q�W|dk	r�t|�|dk	r�t|�XdS)z1Open as many socket families / types as possible.N)r=)�appendrJr�rrrrrr�HAS_CONNECTIONS_UNIXrIr�rMrKr|r>)ZsocksZfname1Zfname2�s1�s2Zs3r�rgrgrhrN�s,



cCs�ddl}trtr|tjkrTdd�|jd�D�}x|D]}q4WtsHt|�}|j|�n8|tjkrvtsjt|�}|j	|�n|t
jkr�n
td|��dS)z[Check a net address validity. Supported families are IPv4,
    IPv6 and MAC addresses.
    rNcSsg|]}t|��qSrg)r�)rvrwrgrgrhrx�sz%check_net_address.<locals>.<listcomp>r{zunknown family %r)
�	ipaddress�enumrr�rr�rZIPv4AddressrZIPv6AddressrpZAF_LINKrr)r>r<rEZoctsZnumrgrgrhrG�s 



c(Cs�t|�dk}t|dd	�d
k}|r |r�ttd�r�tr�ytj|j|j|j�}Wn:tj	t
fk
r�}z|jdtj
krv�WYdd}~XnXtj|��WdQRX|jttfk�r2|jtk�r>tj|j|j�}tj|��Vy|j|jddf�Wn6tj	k
�r$}z|jtjk�r�WYdd}~XnXWdQRXn|jtk�r>|jtk�rJxL|j|jfD]<}|jttfk�r�|�sv�qXt|j|j�n|jtk�rX�qXWdd�tt�D�}dS)z*Check validity of a connection namedtuple.r�fdrY�fromfdrNcSs g|]}|jd�rtt|��qS)ZCONN_)rtrurp)rvrwrgrgrhrx=sz+check_connection_ntuple.<locals>.<listcomp>r�r�)r�rur�r�r
rHrGr<r=�errorr�r�r�ZEBADFr�r�rrr�ZladdrZ
EADDRNOTAVAILryrZraddrrGZiprrp)r�Zhas_pidZhas_fdZdupsockr�r�r>ZvalidsrgrgrhrF�s@
 cCsLyddl}t|d�st�Wn"tk
r<ddl}|j|�SX|j|�SdS)z,Backport of importlib.reload of Python 3.3+.rN�reload)�	importlibr��ImportError�imprJ)�modulerKrMrgrgrhrOFs
cCs�tjjtjj|��d}tjddkr:ddl}|j||�Stjdd�dkrfddlm	}|||�j
�Sddl}|jj
||�}|jj|�}|jj|�|SdS)Nrrrr)�SourceFileLoader)rr)rlrmr!r�rjrorMZload_sourceZimportlib.machineryrO�load_module�importlib.util�util�spec_from_file_location�module_from_spec�loader�exec_module)rmr�rMrOrK�spec�modrgrgrhrPSscCstj|t�dS)zRaise a warning msg.N)�warningsrQ�UserWarning)r4rgrgrhrQhscCsVt|�}|j}t|�dks&|dtkr*dSt|dd�}t|t�sDdStdd�|D��S)z-Check if object is an instance of namedtuple.rYrF�_fieldsNcss|]}t|�tkVqdS)N)r=r�)rv�nrgrgrh�	<genexpr>vsz is_namedtuple.<locals>.<genexpr>)r=�	__bases__r��tuplerur~�all)rw�t�br�rgrgrhrSms
c#sfd�tj|�d�}�fdd�tj�j�D�}tj|�}tj||�zt	j
|�|VWdt|�XdS)z�Ctx manager which picks up a random shared CO lib used
        by this process, copies it in another location and loads it
        in memory via ctypes. Return the new absolutized path.
        z.so)r�rcs6g|].}tjj|j�d�krd|jj�kr|j�qS)rY�python)rlrmr!�lower)rvrw)�extrgrhrx�sz'copyload_shared_lib.<locals>.<listcomp>N)r�r�rprqr^�random�choicerr�ctypesZCDLLr>)�
dst_prefix�dst�libsr�rg)rerhrRzs


c	#s�ddlm}ddlm}d�tj|�d�}�fdd�tj�j�D�}tj	|�}t
j||�d}ztj|�}|VWd|dk	r�tj
jj}|jg|_||j�}|dkr�|�t|�XdS)	z�Ctx manager which picks up a random shared DLL lib used
        by this process, copies it in another location and loads it
        in memory via ctypes.
        Return the new absolutized, normcased path.
        r)�wintypes)�WinErrorz.dll)r�rcsPg|]H}tjj|j�dj��krdtjj|j�j�krd|jj�kr|j�qS)rYrcZwow64)rlrmr!rdr�)rvrw)rergrhrx�sz'copyload_shared_lib.<locals>.<listcomp>N)rhrlrmr�r�rprqr^rfrgrrZWinDLLZwindllZkernel32�FreeLibraryZHMODULEZargtypesZ_handler>)	rirlrmrjrkr��cfilernr	rg)rerhrR�s$





)rr)rr)rUrV)rWrri�)rZr[)N)F)TF)N)N)N)r5)rT�rTr)rp)�r�Z
__future__r�atexitr�rhr�r�rlrfr�r�rr�r
rbrjr�r�r�r�rrYrrrrrprrr	r
Zpsutil._commonrZpsutil._compatrr
rrroZ	unittest2rrrLrF�__all__�getenvr!�builtin_module_namesrZ	WIN_VISTArr]�getr"rrrrr$rrmr�rnr�rr�r �getfilesystemencodingrdZASCII_FS�abspathr�__file__rrr%r�rqr%r&rBr'r(r)Zmemory_full_infor[r1r*r+r,ZHAS_THREADSr-r_r.r/r0rsrr�devnullrrr#ru�objectryrzr�r�r�r��registerr�r�r�r�r�r4r6r5r2r�r3rBrAr�r�rD�EnvironmentErrorr1rErCr>r�contextmanagerr=r?r@rr r;r<r:r9r7r8rHrIrJrKrLrMrNrGrFrOrPrQrSrRrgrgrgrh�<module>	sN








 




0 #%
_:


	
	



L
tests/__pycache__/test_aix.cpython-36.opt-1.pyc000064400000006317150466730550015345 0ustar003

��JZm�@sxdZddlZddlmZddlmZddlmZddlmZddlZejed�Gdd	�d	ej	��Z
ed
krtee�dS)zAIX specific tests.�N)�AIX)�run_test_module_by_name)�sh)�unittestzAIX onlyc@s4eZdZdd�Zdd�Zdd�Zdd�Zd	d
�ZdS)�AIXSpecificTestCasecCs�td�}d}xdj�D]}|d|f7}qWtj||�}|j|d�d}t|jd��|}t|jd��|}t|jd	��|}t|jd
��|}	tj�}
d||}|j	|
j
|�|j|
j||d�|j|
j
||d�|j|
j|	|d�dS)
Nz/usr/bin/svmon -O unit=KBz	memory\s*z+size inuse free pin virtual available mmodez(?P<%s>\S+)\s+z(svmon command returned unexpected outputi�size�	availableZinuse�free�)�delta)r�split�re�search�assertIsNotNone�int�group�psutilZvirtual_memory�assertEqual�total�assertAlmostEqual�usedrr	)�self�out�
re_pattern�field�matchobjZKBrrrr	�
psutil_resultZMEMORY_TOLERANCE�r� /usr/lib64/python3.6/test_aix.py�test_virtual_memorys*z'AIXSpecificTestCase.test_virtual_memorycCsTtd�}tjd|�}|j|d�t|jd��}d}tj�}|jt|j	|�|�dS)Nz/usr/sbin/lsps -az=(?P<space>\S+)\s+(?P<vol>\S+)\s+(?P<vg>\S+)\s+(?P<size>\d+)MBz'lsps command returned unexpected outputrir
i)
rr
rrrrrZswap_memoryrr)rrrZtotal_mbZMBrrrr�test_swap_memory4sz$AIXSpecificTestCase.test_swap_memorycCs�td�}d}xdj�D]}|d|f7}qWtj||�}|j|d�d}tj�}|j|jt	|j
d��|d�|j|jt	|j
d	��|d�|j|jt	|j
d
��|d�|j|j
t	|j
d��|d�dS)Nz/usr/bin/mpstat -azALL\s*zfmin maj mpcs mpcr dev soft dec ph cs ics bound rq push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd syscz(?P<%s>\S+)\s+z)mpstat command returned unexpected outputi�Zcs)rZsyscZdevZsoft)rrr
rrrZ	cpu_statsrZctx_switchesrrZsyscallsZ
interruptsZsoft_interrupts)rrrrrZCPU_STATS_TOLERANCErrrr�test_cpu_statsIs2z"AIXSpecificTestCase.test_cpu_statscCs:td�}ttjd|�jd��}tjdd�}|j||�dS)Nz/usr/bin/mpstat -az
lcpu=(\d+)�T)Zlogical)rrr
rrr�	cpu_countr)rrZmpstat_lcpuZpsutil_lcpurrr�test_cpu_count_logicaljsz*AIXSpecificTestCase.test_cpu_count_logicalcCs4td�}t|j��}ttj�j��}|j||�dS)Nz/etc/ifconfig -l)r�setrrZnet_if_addrs�keysZassertSetEqual)rrZifconfig_namesZpsutil_namesrrr�test_net_if_addrs_namespsz+AIXSpecificTestCase.test_net_if_addrs_namesN)�__name__�
__module__�__qualname__rr r!r$r'rrrrrs
!r�__main__)
�__doc__r
rrZpsutil.testsrrrZskipIfZTestCaserr(�__file__rrrr�<module>s
ctests/__pycache__/test_sunos.cpython-36.pyc000064400000002646150466730550014775 0ustar003

��JZ�@sxdZddlZddlZddlmZddlmZddlmZddlmZejed�Gdd	�d	ej	��Z
ed
krtee�dS)zSun OS specific tests.�N)�SUNOS)�run_test_module_by_name)�sh)�unittestz
SUNOS onlyc@seZdZdd�Zdd�ZdS)�SunOSSpecificTestCasec
Cs�tdtjd�}|j�jd�dd�}|s4td��d}}xL|D]D}|j�}|d	d�\}}|tt|�d�7}|tt|�d�7}qBW||}tj�}	|j	|	j
|�|j	|	j|�|j	|	j|�dS)
Nz#env PATH=/usr/sbin:/sbin:%s swap -l�PATH�
�zno swap device(s) configuredr�i���)
r�os�environ�strip�split�
ValueError�int�psutilZswap_memory�assertEqual�total�used�free)
�self�out�linesrr�line�t�frZpsutil_swap�r�"/usr/lib64/python3.6/test_sunos.py�test_swap_memorys
z&SunOSSpecificTestCase.test_swap_memorycCs&td�}|jtj�t|jd���dS)Nz/usr/sbin/psrinfor)rrr�	cpu_count�lenr)rrrrr�test_cpu_count&sz$SunOSSpecificTestCase.test_cpu_countN)�__name__�
__module__�__qualname__rr"rrrrrsr�__main__)
�__doc__rrrZpsutil.testsrrrZskipIfZTestCaserr#�__file__rrrr�<module>s
tests/__pycache__/test_osx.cpython-36.opt-1.pyc000064400000025051150466730550015371 0ustar003

��JZ�%�@s<dZddlZddlZddlZddlZddlmZddlmZddlmZddlm	Z	ddlm
Z
ddlmZdd	lmZdd
lm
Z
ddlmZddlmZer�ejd
�ndZdd�Zdd�Zdd�Zejed�Gdd�dej��Zejed�Gdd�dej��Zejed�Gdd�dej��Zedk�r8e
e�dS)zOSX specific tests.�N)�OSX)�create_zombie_proc)�get_test_subprocess)�HAS_BATTERY)�MEMORY_TOLERANCE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�sh)�unittest�SC_PAGE_SIZEcCs6t|�}|j�d}yt|�Stk
r0|SXdS)zmExpects a sysctl command with an argument and parse the result
    returning only the value of interest.
    �N)r
�split�int�
ValueError)�cmdline�out�result�r� /usr/lib64/python3.6/test_osx.py�sysctlsrcCsHtd�}x$|jd�D]}||krPqWtd��ttjd|�jd��tS)z)Wrapper around 'vm_stat' cmdline utility.�vm_stat�
zline not foundz\d+r)r
rrr�re�search�group�PAGESIZE)Zfieldr�linerrrr(src	
Cs�ddi}|}d}x@|r&|dd
�j�s6|dd
�dkrP||d7}|d
d�}qWt|�}|j�}xD|j�D]\}}||krlPqlW|dkr�|d}|j�}ntd|��|dd
i}x0t|d
d��D]\}}d
|d
d>||<q�Wt|||�S)NZ	customary�B�K�M�G�T�P�E�Z�Y�rr
�.�kzcan't interpret %r�
)	rrr r!r"r#r$r%r&)�isdigit�float�strip�items�upperr�	enumerater)	�sZSYMBOLSZinit�numZletter�nameZsset�prefix�irrr�human2bytes4s&&
r6zOSX onlyc@s,eZdZedd��Zedd��Zdd�ZdS)�TestProcesscCst�j|_dS)N)r�pid)�clsrrr�
setUpClassQszTestProcess.setUpClasscCs
t�dS)N)r)r9rrr�
tearDownClassUszTestProcess.tearDownClasscCs�td|j�}|jdd�j�}|jd�d	}|jd�d
}tj|j�j�}|j|t	j
dt	j|���|j|t	j
dt	j|���dS)Nzps -o lstart -p %sZSTARTEDr'� �r
z%H:%M:%Sz%Y������)r
r8�replacer-r�psutil�Process�create_time�assertEqual�timeZstrftimeZ	localtime)�self�outputZstart_psZhhmmssZyearZstart_psutilrrr�test_process_create_timeYsz$TestProcess.test_process_create_timeN)�__name__�
__module__�__qualname__�classmethodr:r;rHrrrrr7Nsr7c@s�eZdZedd��Zedd��Zdd�Zdd�Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zdd�Zdd �Zd!S)"�TestZombieProcessAPIscCst�}tj|�|_dS)N)rrArB�p)r9Zzpidrrrr:jsz TestZombieProcessAPIs.setUpClasscCstdd�dS)NT)�	recursive)r)r9rrrr;osz#TestZombieProcessAPIs.tearDownClasscCsJ|j|jj�tj�|jj�|jj�|jj�|jj�|jj	�dS)N)
rDrNZstatusrAZ
STATUS_ZOMBIEZppidZuidsZgidsZterminalrC)rFrrr�test_pidtask_infoss



z'TestZombieProcessAPIs.test_pidtask_infocCs|jtj|jj�dS)N)�assertRaisesrA�
ZombieProcessrNZexe)rFrrr�test_exe{szTestZombieProcessAPIs.test_execCs|jtj|jj�dS)N)rQrArRrNr)rFrrr�test_cmdline~sz"TestZombieProcessAPIs.test_cmdlinecCs|jtj|jj�dS)N)rQrArRrN�environ)rFrrr�test_environ�sz"TestZombieProcessAPIs.test_environcCs|jtj|jj�dS)N)rQrArRrN�cwd)rFrrr�test_cwd�szTestZombieProcessAPIs.test_cwdcCs|jtj|jj�dS)N)rQrArRrNZmemory_full_info)rFrrr�test_memory_full_info�sz+TestZombieProcessAPIs.test_memory_full_infocCs|jtj|jj�dS)N)rQrArRrNZ	cpu_times)rFrrr�test_cpu_times�sz$TestZombieProcessAPIs.test_cpu_timescCs|jtj|jj�dS)N)rQrArRrNZnum_ctx_switches)rFrrr�test_num_ctx_switches�sz+TestZombieProcessAPIs.test_num_ctx_switchescCs|jtj|jj�dS)N)rQrArRrNZnum_threads)rFrrr�test_num_threads�sz&TestZombieProcessAPIs.test_num_threadscCs|jtj|jj�dS)N)rQrArRrNZ
open_files)rFrrr�test_open_files�sz%TestZombieProcessAPIs.test_open_filescCs|jtj|jj�dS)N)rQrArRrNZconnections)rFrrr�test_connections�sz&TestZombieProcessAPIs.test_connectionscCs|jtj|jj�dS)N)rQrArRrNZnum_fds)rFrrr�test_num_fds�sz"TestZombieProcessAPIs.test_num_fdscCs|jtjtjf|jj�dS)N)rQrArRZAccessDeniedrNZthreads)rFrrr�test_threads�sz"TestZombieProcessAPIs.test_threadscCs|jtj|jj�dS)N)rQrArRrNZmemory_maps)rFrrr�test_memory_maps�sz&TestZombieProcessAPIs.test_memory_mapsN)rIrJrKrLr:r;rPrSrTrVrXrYrZr[r\r]r^r_r`rarrrrrMgs rMc@s�eZdZdd�Zdd�Zdd�Zdd�Zd	d
�Ze�dd��Z	e�d
d��Z
e�dd��Ze�dd��Ze�dd��Z
e�dd��Ze�dd��Zdd�Zejed�dd��ZdS)�TestSystemAPIscCs�dd�}x�tjdd�D]�}tj|j�}||j�\}}}}|j|j|�|j|j|�t|j|�d	krx|j	d|j|�t|j
|�dkr|j	d|j
|�qWdS)NcSs�td|�j�}|jd�}|jd�|jd�}|j�dd�\}}}}|dkrRd}t|�d}t|�d}t|�d}||||fS)Nz
df -k "%s"rr�Znoner'i)r
r-r�popr)�pathr�linesr�dev�total�used�freerrr�df�s


z%TestSystemAPIs.test_disks.<locals>.dfF)�allr*izpsutil=%s, df=%si(i�i(i�)rAZdisk_partitionsZ
disk_usageZ
mountpointrDZdevicerh�absrjZfailri)rFrk�partZusagergrhrirjrrr�
test_disks�s
zTestSystemAPIs.test_diskscCs td�}|j|tjdd��dS)Nzsysctl hw.logicalcpuT)�logical)rrDrA�	cpu_count)rFr2rrr�test_cpu_count_logical�sz%TestSystemAPIs.test_cpu_count_logicalcCs td�}|j|tjdd��dS)Nzsysctl hw.physicalcpuF)rp)rrDrArq)rFr2rrr�test_cpu_count_physical�sz&TestSystemAPIs.test_cpu_count_physicalcCsZtj�}|j|jddtd��|j|jddtd��|j|jddtd��dS)Ni�zsysctl hw.cpufrequencyzsysctl hw.cpufrequency_minzsysctl hw.cpufrequency_max)rAZcpu_freqrDZcurrentr�min�max)rFZfreqrrr�
test_cpu_freq�szTestSystemAPIs.test_cpu_freqcCstd�}|j|tj�j�dS)Nzsysctl hw.memsize)rrDrA�virtual_memoryrh)rFZsysctl_hwphymemrrr�test_vmem_total�szTestSystemAPIs.test_vmem_totalcCs&td�}tj�j}|j||td�dS)Nrj)�delta)rrArwrj�assertAlmostEqualr)rF�
vmstat_val�
psutil_valrrr�test_vmem_free�s
zTestSystemAPIs.test_vmem_freecCs.td�td�}tj�j}|j||td�dS)N�inactiverj)ry)rrArwZ	availablerzr)rFr{r|rrr�test_vmem_available�s
z"TestSystemAPIs.test_vmem_availablecCs&td�}tj�j}|j||td�dS)N�active)ry)rrArwr�rzr)rFr{r|rrr�test_vmem_active�s
zTestSystemAPIs.test_vmem_activecCs&td�}tj�j}|j||td�dS)Nr~)ry)rrArwr~rzr)rFr{r|rrr�test_vmem_inactive�s
z!TestSystemAPIs.test_vmem_inactivecCs&td�}tj�j}|j||td�dS)N�wired)ry)rrArwr�rzr)rFr{r|rrr�test_vmem_wired�s
zTestSystemAPIs.test_vmem_wiredcCs"td�}tj�j}|j||�dS)NZPageins)rrA�swap_memoryZsinrD)rFr{r|rrr�test_swapmem_sin�s
zTestSystemAPIs.test_swapmem_sincCs"td�}tj�j}|j||�dS)NZPageout)rrAr�ZsoutrD)rFr{r|rrr�test_swapmem_souts
z TestSystemAPIs.test_swapmem_soutcCsxxrtj�j�D]b\}}ytd|�}Wntk
r:YqX|j|jd|k|d�|j|jtt	j
d|�d��qWdS)Nzifconfig %sZRUNNING)�msgz	mtu (\d+)r)rAZnet_if_statsr.r
�RuntimeErrorrDZisupZmturr�findall)rFr3Zstatsrrrr�test_net_if_statssz TestSystemAPIs.test_net_if_statsz
no batterycCs`td�}tjd|�jd�}tjd|�jd�}|dk}tj�}|j|j|�|j|jt	|��dS)Nz
pmset -g battz(\d+)%r
zNow drawing from '([^']+)'zAC Power)
r
rrrrAZsensors_batteryrD�
power_plugged�percentr)rFrr�Zdrawing_fromr�Z
psutil_resultrrr�test_sensors_battery"sz#TestSystemAPIs.test_sensors_batteryN)rIrJrKrorrrsrvrxrr}rr�r�r�r�r�r�r�skipIfrr�rrrrrb�s
rb�__main__)�__doc__�osrrErArZpsutil.testsrrrrrrr	r
r�sysconfrrrr6r�ZTestCaser7rMrbrI�__file__rrrr�<module>s6

<
	
tests/__pycache__/test_connections.cpython-36.pyc000064400000035032150466730550016143 0ustar003

��JZ�P�@s8dZddlZddlZddlZddlmZddlmZddlmZddlmZddlm	Z	ddl
Z
ddl
mZdd	l
mZdd
l
m
Z
ddl
mZddl
mZdd
l
mZddl
mZddl
mZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%dd lm&Z&dd!lm'Z'dd"lm(Z(dd#lm)Z)dd$lm*Z*e
j+�Z,Gd%d&�d&e-�Z.Gd'd(�d(e.e'j/�Z0Gd)d*�d*e.e'j/�Z1Gd+d,�d,e.e'j/�Z2Gd-d.�d.e'j/�Z3e4d/k�r4e!e5�dS)0z;Tests for net_connections() and Process.connections() APIs.�N)�closing)�AF_INET)�AF_INET6)�
SOCK_DGRAM)�SOCK_STREAM)�FREEBSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�
supports_ipv6)�PY3)�AF_UNIX)�bind_socket)�bind_unix_socket)�check_connection_ntuple)�create_sockets)�
get_free_port)�HAS_CONNECTIONS_UNIX)�pyrun)�
reap_children)�run_test_module_by_name)�safe_rmpath)�skip_on_access_denied)�tcp_socketpair)�TESTFN)�TRAVIS)�unittest)�unix_socket_path)�unix_socketpair)�
wait_for_filec@s8eZdZdd�Zdd�Zdd�Zd
dd	�Zddd�ZdS)�BasecCs"tstjdd�}|st|��dS)N�all)�kind)r	�thisproc�connections�AssertionError)�self�cons�r,�(/usr/lib64/python3.6/test_connections.py�setUp6sz
Base.setUpcCs0tt�t�ts,tjdd�}|s,t|��dS)Nr%)r&)rrrr	r'r(r))r*r+r,r,r-�tearDown<s
z
Base.tearDowncCsrtjdd�}tdd�|D��}tr.||j�S|jt|�d�|djdkrf|j||j�j|j��|dSdS)Nr%)r&cSsg|]}|j|f�qSr,)�fd)�.0�cr,r,r-�
<listcomp>Gsz+Base.get_conn_from_sock.<locals>.<listcomp>�r���)r'r(�dictr	�fileno�assertEqual�lenr0)r*�sockr+Zsmapr,r,r-�get_conn_from_sockEszBase.get_conn_from_sockNcCs�|dkr|j|�}t|�|jdkr6|j|j|j��|j|j|j�|j|j|jtj	tj
��|j�}|r�tr�t
|t�r�|j�}|jtkr�|dd�}|jtkr�tr�n|j|j|�|jtkr�tr�tjdd�}|jtj�|�|S)z�Given a socket, makes sure it matches the one obtained
        via psutil. It assumes this process created one connection
        only (the one supposed to be checked).
        Nr4�r%)r&r5)r;rr0r8r7�family�typeZ
getsockopt�socketZ
SOL_SOCKETZSO_TYPEZgetsocknamer�
isinstance�bytes�decoderrr
�laddrrr'r(�compare_procsys_connections�os�getpid)r*r:�connrCr+r,r,r-�check_socketRs(


zBase.check_socketr%csdytj|d�}Wn tjk
r0tr*dS�YnX�fdd�|D�}|j�|j�|j||�dS)z�Given a process PID and its list of connections compare
        those against system-wide connections retrieved via
        psutil.net_connections.
        )r&Ncs"g|]}|j�kr|dd��qS)Nr4r5)�pid)r1r2)rIr,r-r3�sz4Base.compare_procsys_connections.<locals>.<listcomp>)�psutil�net_connectionsZAccessDeniedr�sortr8)r*rIZ	proc_consr&Zsys_consr,)rIr-rDvsz Base.compare_procsys_connections)N)r%)�__name__�
__module__�__qualname__r.r/r;rHrDr,r,r,r-r$4s
	
$r$c@s|eZdZdZdd�Zeje�d�dd��Zdd�Z	eje�d�d	d
��Z
ejed�dd
��Zejed�dd��Z
dS)�TestUnconnectedSocketsz;Tests sockets which are open but not connected to anything.c
CsRdt�f}tttt|d���,}|j|�}|js4t�|j|j	t
j�WdQRXdS)Nz	127.0.0.1)�addr)rrrrrrH�raddrr)r8�statusrJ�CONN_LISTEN)r*rQr:rGr,r,r-�test_tcp_v4�s


z"TestUnconnectedSockets.test_tcp_v4zIPv6 not supportedc
CsRdt�f}tttt|d���,}|j|�}|js4t�|j|j	t
j�WdQRXdS)Nz::1)rQ)rrrrrrHrRr)r8rSrJrT)r*rQr:rGr,r,r-�test_tcp_v6�s


z"TestUnconnectedSockets.test_tcp_v6c
CsRdt�f}tttt|d���,}|j|�}|js4t�|j|j	t
j�WdQRXdS)Nz	127.0.0.1)rQ)rrrrrrHrRr)r8rSrJ�	CONN_NONE)r*rQr:rGr,r,r-�test_udp_v4�s


z"TestUnconnectedSockets.test_udp_v4c
CsRdt�f}tttt|d���,}|j|�}|js4t�|j|j	t
j�WdQRXdS)Nz::1)rQ)rrrrrrHrRr)r8rSrJrW)r*rQr:rGr,r,r-�test_udp_v6�s


z"TestUnconnectedSockets.test_udp_v6z
POSIX onlycCsXt��H}tt|td���,}|j|�}|js0t�|j|jt	j
�WdQRXWdQRXdS)N)r>)r!rrrrHrRr)r8rSrJrW)r*�namer:rGr,r,r-�
test_unix_tcp�s

z$TestUnconnectedSockets.test_unix_tcpcCsXt��H}tt|td���,}|j|�}|js0t�|j|jt	j
�WdQRXWdQRXdS)N)r>)r!rrrrHrRr)r8rSrJrW)r*rZr:rGr,r,r-�
test_unix_udp�s

z$TestUnconnectedSockets.test_unix_udpN)rMrNrO�__doc__rUr �skipIfrrVrXrYrr[r\r,r,r,r-rP�srPc@sTeZdZdZejed�dd��Zejed�dd��Z	e
ed�d	d
��Zdd�Z
d
S)�TestConnectedSocketPairszJTest socket pairs which are are actually connected to
    each other.
    zunreliable on SUONSc
Cs�dt�f}tjdd�st�tt|d�\}}zHtjdd�}|jt|�d�|j|djt	j
�|j|djt	j
�Wd|j�|j�XdS)Nz	127.0.0.1�tcp4)r&)rQr<rr4)rr'r(r)rrr8r9rSrJZCONN_ESTABLISHED�close)r*rQ�server�clientr+r,r,r-�test_tcp�s
z!TestConnectedSocketPairs.test_tcpz
POSIX onlycCslt���Z}t|�\}}�z2tjdd�}|djo8|djs@t�|djoR|djsZt�trldd�|D�}|jt	|�d�t
s�ts�tr�|j|djd�|j|djd�|j||djp�|dj�n~t
�rxv|dj|dj|dj|djfD]}|j|d�q�Wn<|j|dj�p$|dj|�|j|dj�pB|dj|�Wd|j�|j�XWdQRXdS)	N�unix)r&rr4cSsg|]}|jdkr|�qS)z/var/run/log)rR)r1r2r,r,r-r3�sz6TestConnectedSocketPairs.test_unix.<locals>.<listcomp>r<�)r!r"r'r(rCrRr)r	r8r9rrr
r
ra)r*rZrbrcr+rQr,r,r-�	test_unix�s*
"z"TestConnectedSocketPairs.test_unix)Zonly_ifcs�fdd�}tjd�}tjd�}ddlm}tjjt�}||�jt	t
�d|d�}||�jt	t
�d|d�}||�jt	t�d	|d�}||�jt	t�d	|d�}	t|�}
t
t|��}t|�}t
t|��}
t�r�t|�}t
t|��}t|	�}t
t|��}nd}d}d}d}�x�tj�D�]�}|j�}�jt|�d
�x�|D]�}|j|
jk�r\|||t
t|ftjd�n�|j|jk�r�|||t
t|
ftjd�nZ|jt|dd�k�r�|||tt|ftjd�n,|jt|dd�k�r0|||tt|ftjd��q0W�qW�jt|jdd�dS)Nc
s�d}t|��j|j|��j|j|��j|j|��j|j|��j|j|�x8|D]0}	|j|	d�}
|	|krz|
s�t�qX|
sXt|
��qXWt	r��j
|j|g�dS)
Nr%�inet�inet4�inet6�tcpr`�tcp6�udp�udp4�udp6)r&)
r%rhrirjrkr`rlrmrnro)rr8r=r>rCrRrSr(r)rrDrI)�procrGr=r>rCrRrSZkindsZ	all_kindsr&r+)r*r,r-�
check_conns

z8TestConnectedSocketPairs.test_combos.<locals>.check_conna
            import socket, time
            s = socket.socket($family, socket.SOCK_STREAM)
            s.bind(('$addr', 0))
            s.listen(1)
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        z�
            import socket, time
            s = socket.socket($family, socket.SOCK_DGRAM)
            s.bind(('$addr', 0))
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        r)�Templatez	127.0.0.1)r=rQZtestfnz::1r4r%rhrirkr`rmrnrIrjrlroz???)r&)r%rhrirkr`)r%rhrirmrn)r%rhrjrkrl)r%rhrjrmro)�textwrap�dedent�stringrrrE�path�basenamerZ
substitute�intrrr�evalr#rr'Zchildrenr(r8r9rIrrJrTrrW�getattr�assertRaises�
ValueError)r*rqZtcp_templateZudp_templaterrZtestfileZ
tcp4_templateZ
udp4_templateZ
tcp6_templateZ
udp6_templateZ	tcp4_procZ	tcp4_addrZ	udp4_procZ	udp4_addrZ	tcp6_procZ	tcp6_addrZ	udp6_procZ	udp6_addr�pr+rGr,)r*r-�test_combossb
z$TestConnectedSocketPairs.test_comboscCs�t����}tjdd�}|jt|�t|��tjdd�}|jt|�t�rJdnd�x,|D]$}|j|jtt	f�|j|j
t�qVWtjdd�}|jt|�d�|j|djt�|j|dj
t�t��rtjdd�}|jt|�d�|j|djt	�|j|dj
t�tjd	d�}|jt|�t��r(dnd�x.|D]&}|j|jtt	f�|j|j
t��q4Wtjd
d�}|jt|�d�|j|djt�|j|dj
t�t��r�tjdd�}|jt|�d�|j|djt	�|j|dj
t�tjdd�}|jt|�t��rd
nd�x2|D]*}|j|jtt	f�|j|j
ttf��qWt��r�tjdd�}|jt|�d�x.|D]&}|j|jt	�|j|j
ttf��qlWt
�r�tjdd�}|jt|�d�x.|D]&}|j|jt�|j|j
ttf��q�WWdQRXdS)Nr%)r&rkr<r4r`rrlrmrnrorh�rjre�)rr'r(r8r9r�assertInr=rrr>rrrr)r*�socksr+rGr,r,r-�test_multi_sockets_filteringes`





z5TestConnectedSocketPairs.test_multi_sockets_filteringN)rMrNrOr]r r^r
rdrrgrrr~r�r,r,r,r-r_�s
!br_c@sJeZdZdZe�dd��Ze�dd��Ze�eje	o6e
d�dd���Zd	S)
�TestSystemWideConnectionszTests for net_connections().c
s��fdd�}t���ddlm}xZ|j�D]N\}}|dkrBtrBq*|\}}tj|�}�jt|�tt	|���||||�q*W�j
ttjdd�WdQRXdS)NcsVttdt��}xB|D]:}�j|j||d�|j|krF�j|j||d�t|�qWdS)Nr)�msg)rzr?�objectr�r=r>r)r+�families�types_rrG)r*r,r-�check�s

z0TestSystemWideConnections.test_it.<locals>.checkr)�	conn_tmaprez???)r&)r�psutil._commonr��itemsrrJrKr8r9�setr{r|)r*r�r�r&�groupsr�r�r+r,)r*r-�test_it�s
z!TestSystemWideConnections.test_itcCs@t��0}dd�tjdd�D�}|jt|�t|��WdQRXdS)NcSsg|]}|jtj�kr|�qSr,)rIrErF)r1�xr,r,r-r3�sz>TestSystemWideConnections.test_multi_socks.<locals>.<listcomp>r%)r&)rrJrKr8r9)r*r�r+r,r,r-�test_multi_socks�sz*TestSystemWideConnections.test_multi_sockszunreliable on OSX + TRAVISc

st��}t|�}WdQRXg�d}xRt|�D]F}tjjt�t|�}tj	d|�}t
|�}�j|j�|j
t|�q,Wx$t|�D]}tt|�}t|�q�W�fdd�tjdd�D�}xJ�D]B�|jt�fdd�|D��|�tj��}	|jt|	jd��|�q�WdS)N�
a                import time, os
                from psutil.tests import create_sockets
                with create_sockets():
                    with open('%s', 'w') as f:
                        f.write(str(os.getpid()))
                    time.sleep(60)
                csg|]}|j�kr|�qSr,)rI)r1r�)�pidsr,r-r3�szFTestSystemWideConnections.test_multi_sockets_procs.<locals>.<listcomp>r%)r&csg|]}|j�kr|�qSr,)rI)r1r�)rIr,r-r3�s)rr9�rangerErv�realpathr�strrsrtr�appendrIZ
addCleanuprr#rJrKr8�Processr()
r*r�Zexpected�times�iZfname�srcZsprocZsysconsr}r,)rIr�r-�test_multi_sockets_procs�s(



z2TestSystemWideConnections.test_multi_sockets_procsN)rMrNrOr]rr�r�r r^rrr�r,r,r,r-r��s
r�c@seZdZdd�ZdS)�TestMisccCs�g}g}xhtt�D]\}|jd�rtt|�}t|�}|j�sBt|��|jt|�|j||�|j|�|j|�qWt	r�tj
tjtr�tj
dS)NZCONN_)�dirrJ�
startswithrzr��isupperr)ZassertNotInr�r
Z	CONN_IDLEZ
CONN_BOUNDrZCONN_DELETE_TCB)r*ZintsZstrsrZZnumZstr_r,r,r-�test_connection_constants�s 


z"TestMisc.test_connection_constantsN)rMrNrOr�r,r,r,r-r��sr��__main__)6r]rEr?rs�
contextlibrrrrrrJrrr	r
rrr
rr�rZpsutil._compatrZpsutil.testsrrrrrrrrrrrrrrrr r!r"r#r�r'r�r$ZTestCaserPr_r�r�rM�__file__r,r,r,r-�<module>s^\7`P
tests/__pycache__/test_process.cpython-36.opt-1.pyc000064400000116363150466730550016245 0ustar003

��JZ9��@s�dZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddl
Z
ddlZddlmZddlmZddlmZddlmZddlmZddlmZdd	lmZdd
lmZddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddlm$Z$ddlm%Z%ddlm&Z&ddlm'Z'ddlm(Z(ddlm)Z)ddlm*Z*ddlm+Z+ddlm,Z,ddlm-Z-dd lm.Z.dd!lm/Z/dd"lm0Z0dd#lm1Z1dd$lm2Z2dd%lm3Z3dd&lm4Z4dd'lm5Z5dd(lm6Z6dd)lm7Z7dd*lm8Z8dd+lm9Z9dd,lm:Z:dd-lm;Z;dd.lm<Z<dd/lm=Z=Gd0d1�d1e;j>�Z?e�r�ej@�dk�r�Gd2d3�d3e?�ZAGd4d5�d5e;j>�ZBeCd6k�r�e2eD�dS)7zTests for psutil.Process class.�N)�AIX)�BSD)�LINUX)�NETBSD)�OPENBSD)�OSX)�POSIX)�SUNOS)�WINDOWS)�long)�PY3)�APPVEYOR)�
call_until)�copyload_shared_lib)�
create_exe)�create_proc_children_pair)�create_zombie_proc)�enum)�get_test_subprocess)�
get_winver)�HAS_CPU_AFFINITY)�HAS_ENVIRON)�
HAS_IONICE)�HAS_MEMORY_MAPS)�HAS_PROC_CPU_NUM)�HAS_PROC_IO_COUNTERS)�
HAS_RLIMIT)�HAS_THREADS)�mock)�PYPY)�
PYTHON_EXE)�
reap_children)�retry_before_failing)�run_test_module_by_name)�safe_rmpath)�sh)�skip_on_access_denied)�skip_on_not_implemented)�TESTFILE_PREFIX)�TESTFN)�
ThreadTask)�TRAVIS)�unittest)�wait_for_pid)�	WIN_VISTAc@sreZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dd�Z
dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zejed�dd��Zdd �Zejed!�ejed"�d#d$���Zejed�eed%�d&d'���Zejed�ejeo�e�e kd�d(d)���Z!ejed�eje�oe�e kd�d*d+���Z"eje#d�d,d-��Z$eje#d�d.d/��Z%eje#d�d0d1��Z&eje#d�d2d3��Z'eje#d�d4d5��Z(d6d7�Z)ejed8�d9d:��Z*eje+d�d;d<��Z,e-�e.e/d%�eje+d�d=d>����Z0d?d@�Z1dAdB�Z2eje3d�dCdD��Z4eje3d�dEdF��Z5dGdH�Z6dIdJ�Z7dKdL�Z8dMdN�Z9dOdP�Z:eje;dQ�eje<dR�dSdT���Z=ejed!�dUdV��Z>ejed!�dWdX��Z?dYdZ�Z@d[d\�ZAd]d^�ZBd_d`�ZCdadb�ZDejeEd�dcdd��ZFejeEd�dedf��ZGejeEd�dgdh��ZHejeIdi�ejeJdj�dkdl���ZKejeIdi�ejeJdj�dmdn���ZLejed!�dodp��ZMeed%�ejeN�pzeOdq�drds���ZPdtdu�ZQdvdw�ZRdxdy�ZSdzd{�ZTd|d}�ZUd~d�ZVd�d��ZWd�d��ZXd�d��ZYd�d��ZZd�d��Z[d�d��Z\ejed!�d�d���Z]ejed!�d�d���Z^ejed!�d�d���Z_d�d��Z`ejead�d�d���Zbejead�ejed!�d�d����Zcd�S)��TestProcesszTests for psutil.Process class.cCstt�dS)N)r$r))�self�r1�$/usr/lib64/python3.6/test_process.py�setUpNszTestProcess.setUpcCs
t�dS)N)r!)r0r1r1r2�tearDownQszTestProcess.tearDownc	CsXtj�}|j|jtj��t�}|jtj|j�j|j�|jt��d|_WdQRXdS)N�!)	�psutil�Process�assertEqual�pid�os�getpidr�assertRaises�AttributeError)r0�p�sprocr1r1r2�test_pidTszTestProcess.test_pidcCsNt�}|j}tj|�}|j�|j�}|jtj|��trJ|j	|t
j�dS)N)rr9r6r7�kill�wait�assertFalse�
pid_existsrr8�signal�SIGKILL)r0r?r@r>�sigr1r1r2�	test_kill\s
zTestProcess.test_killcCsNt�}|j}tj|�}|j�|j�}|jtj|��trJ|j	|t
j�dS)N)rr9r6r7�	terminaterBrCrDrr8rE�SIGTERM)r0r?r@r>rGr1r1r2�test_terminatefs
zTestProcess.test_terminatec CsLtr
tjntj}t�}tj|j�}|j|�|j	�}|j
tj|j��t�rH|j||�t�}tj|j�}|j|�t
jdttjd�d��(|jtj��|j|�WdQRXWdQRXt�}tj|j�}|j|�t
jdttjd�d��,|jtj��tj�j|�WdQRXWdQRXdtj�k�rHtjd�}|jt|jtj�dS)Nzpsutil.os.kill�)�side_effectr)rrErFrJrr6r7r9�send_signalrBrCrDr8r�patch�OSError�errnoZESRCHr<�
NoSuchProcessZEPERM�AccessDenied�pids�
ValueError)r0rGr?r>Zexit_sigr1r1r2�test_send_signalps2


"
zTestProcess.test_send_signalcCs^t�}tj|j�}|j�|j�}tr8|j|tj	�n|j|tj
�|j|j��t�}tj|j�}|j
�|j�}tr�|j|tj
�n|j|tj
�|j|j��d}ttd|g�}tj|j�}|j|j�d�|j|j��ttd|g�}tj|j�}|j|j�d�|j|j�d�t�}tj|j�}|j�|jtj|jd�|jt|jd�dS)Nz0import time, sys; time.sleep(0.01); sys.exit(5);z-c�g{�G�z�?�)rWN���)rr6r7r9rArBrr8rErFrJrC�
is_runningrIr �assertIn�namer<�TimeoutExpiredrU)r0r?r>�coder1r1r2�	test_wait�s<zTestProcess.test_waitcCs�t�\}}|jtj|jd�|jtj|jd�|j�|j�|j�}|j�}trp|j|tj	�|j|d�n|j|tj	�|j|tj	�dS)Ng{�G�z�?)
rr<r6r]rBrIrr8rErJ)r0�p1�p2Zret1Zret2r1r1r2�test_wait_non_children�s
z"TestProcess.test_wait_non_childrencCs�t�}tj|j�}|jtj|jd�|j�tj�d}x:y|jd�}Wn$tjk
rltj�|krh�Yq:XPq:Wt	r�|j
|tj�n|j
|tj
�|j|j��dS)Nr�)rr6r7r9r<r]rBrA�timerr8rErFrJrCrZ)r0r?r>Zstop_atr^r1r1r2�test_wait_timeout_0�s zTestProcess.test_wait_timeout_0c
Cs�tj�}|jdd�|jdd�xRtd�D]F}|jdd�}|j|t�|j|d�tsd|j|d�q*|j|d�q*W|j	t
��|jdd�WdQRXdS)Ng����MbP?)Zinterval�dggY@rXrY)r6r7�cpu_percent�range�assertIsInstance�float�assertGreaterEqualr�assertLessEqualr<rU)r0r>�xZpercentr1r1r2�test_cpu_percent�szTestProcess.test_cpu_percentc	Cs*tjddd��}tj�j�WdQRXdS)Nzpsutil.cpu_count)Zreturn_value)rrOr6r7rg)r0�mr1r1r2�test_cpu_percent_numcpus_none�sz)TestProcess.test_cpu_percent_numcpus_nonecCs8tj�j�}x&|jD]}tjdtjt||���qWdS)Nz%H:%M:%S)r6r7�	cpu_times�_fieldsrd�strftime�	localtime�getattr)r0�timesr\r1r1r2�test_cpu_times�szTestProcess.test_cpu_timescCs�tj�j�dd�\}}tj�dd�\}}t||g�t||g�dkrZ|jd||f�t||g�t||g�dkr�|jd||f�dS)Nrcg�������?zexpected: %s, found: %s)r6r7rqr:rv�max�min�fail)r0�	user_timeZkernel_time�utimeZktimer1r1r2�test_cpu_times_2szTestProcess.test_cpu_times_2z
not supportedcCsPtj�}|j�}|j|d�tj�dkr4|j|d�|j|j�ttj���dS)NrrX)r6r7Zcpu_numrk�	cpu_countr8r[rh)r0r>Znumr1r1r2�test_cpu_numszTestProcess.test_cpu_numcCsdt�}tj�}tj|j�}|j�}t||�}|dkrJ|jd|||f�tjdtj	|j���dS)Nrcz'expected: %s, found: %s, difference: %sz%Y %m %d %H:%M:%S)
rrdr6r7r9�create_time�absrzrsrt)r0r?Znowr>r��
differencer1r1r2�test_create_timeszTestProcess.test_create_timez
POSIX onlyznot reliable on TRAVIScCsLtj�j�}tjj�s tjj�r>tjj	t
d��}|j||�n
|j|�dS)N�tty)
r6r7�terminal�sys�stdin�isatty�stdoutr:�path�realpathr%r8�assertIsNone)r0r�r�r1r1r2�
test_terminal-s
zTestProcess.test_terminal)Zonly_ifcCs�tj�}|j�}ttd��}|j�WdQRX|j�}tr�tr�|j|j	|j	�|j
|j|j�tr�|j|j
|j
�|j
|j|j�n |j|j|j�|j|j|j�|j�}tjtd��.}tr�|jtddd��n|jdd�WdQRX|j�}|j|j|j�|j|j|j�|j|j	|j	�|j|j|j�t�r^|j|j|j�|j|j
|j
�xJtt|��D]:}t�r�|dk�r��ql|j||d�|j||d��qlWdS)N�rb)�prefixrmi@B�asciircr)r6r7Zio_counters�openr �readrr�
assertGreaterZ
read_countr8Zwrite_countrZ
read_charsZwrite_charsrkZ
read_bytesZwrite_bytes�tempfileZ
TemporaryFiler(r�write�bytesrh�len)r0r>Zio1�fZio2�ir1r1r2�test_io_counters7s>zTestProcess.test_io_countersc	Cs�t�r<ddlm}m}m}m}|j|d�|j|d�|j|d�|j|d�tj�}z�|jd�|j�\}}t	dk	r�|j
|t	j�|j|d�|j|d�|jd�|j�\}}|j|d�|j|d�|jdd�|j�\}}|j|d�|j|d�|jdd�|j�\}}|j|d�|j|d�Wd|j|�XnZtj�}|j�}|j
|t�z0d}||k�rld}|j|�|j|j�|�Wd|j|�XdS)Nr)�IOPRIO_CLASS_NONE�IOPRIO_CLASS_RT�IOPRIO_CLASS_BE�IOPRIO_CLASS_IDLErXrc���)
rr6r�r�r�r�r8r7�ionicerri�IntEnum�int)	r0r�r�r�r�r>Zioclass�value�originalr1r1r2�test_ionicecsJ



zTestProcess.test_ionicecCs�t�}tj|j�}tr�|jt|jdd�|jt|jdd�|jt|jd�|jt|jdd�|j	td|jtj
d�|j	td|jtjd�|j	td|jdd	�n"|jt|jd
�|jt|jdd�dS)Nrc�
rXr��fooz*can't specify value with IOPRIO_CLASS_NONEz*can't specify value with IOPRIO_CLASS_IDLEz$'ioclass' argument must be specified)r�r�rY)rr6r7r9rr<rUr��	TypeErrorZassertRaisesRegexr�r�)r0r?r>r1r1r2�test_ionice_errs�s$zTestProcess.test_ionice_errscCs�ddl}tjtj��}dd�tt�D�}x�|D]�}tt|�}|j|d�|t|�kr�|j|t||��t	rlq.|j|j
|�|j|��q.|j
|�}|jt|�d�|j|dd�|j|dd�q.WdS)NrcSsg|]}|jd�r|�qS)ZRLIMIT)�
startswith)�.0rmr1r1r2�
<listcomp>�sz/TestProcess.test_rlimit_get.<locals>.<listcomp>rcrXrYrY)
�resourcer6r7r:r;�dirrurkr8r�rlimitZ	getrlimitr�)r0r�r>�namesr\r��retr1r1r2�test_rlimit_get�s


zTestProcess.test_rlimit_getcCs�t�}tj|j�}|jtjd�|j|jtj�d�|jt��tj	jd�jd�WdQRX|jt��|jtjd�WdQRXdS)NrWr)rWrW)rWrW)rWrWrW)
rr6r7r9r��
RLIMIT_NOFILEr8r<rUZ_psplatform)r0r?r>r1r1r2�test_rlimit_set�szTestProcess.test_rlimit_setc Cs�tj�}|jtj�\}}z�|jtjd|f�ttd��}|jdd�WdQRX|jt��*}ttd��}|jdd�WdQRXWdQRX|j	t
r�|jjn|jdtj
�Wd|jtj||f�|j	|jtj�||f�XdS)Ni�wb�Xir)r6r7r��RLIMIT_FSIZEr�r)r�r<�IOErrorr8rZ	exceptionrQZEFBIG)r0r>�soft�hardr��excr1r1r2�test_rlimit�s"zTestProcess.test_rlimitcCs�tj�}|jtj�\}}zN|jtjd|f�|jtjtj|f�ttd��}|jdd�WdQRXWd|jtj||f�|j|jtj�||f�XdS)Nir�r�i)	r6r7r�r��
RLIM_INFINITYr�r)r�r8)r0r>r�r�r�r1r1r2�test_rlimit_infinity�sz TestProcess.test_rlimit_infinitycCs<tj�}|jtj�\}}|jtj|�|jtj||f�dS)N)r6r7r�r�r8r�)r0r>r�r�r1r1r2�test_rlimit_infinity_value�sz&TestProcess.test_rlimit_infinity_valuecCsrtj�}tr<y|j�}WqDtjk
r8tjd��YqDXn|j�}t��|j�}|j||d�WdQRXdS)Nz$on OpenBSD this requires root accessrX)	r6r7r�num_threadsrSr,�SkipTestr*r8)r0r>�step1�step2r1r1r2�test_num_threads�szTestProcess.test_num_threadszWINDOWS onlycCstj�}|j|j�d�dS)Nr)r6r7r�Znum_handles)r0r>r1r1r2�test_num_handlesszTestProcess.test_num_handlescCs�tj�}tr<y|j�}WqDtjk
r8tjd��YqDXn|j�}t��~|j�}|jt	|�t	|�d�t
r�|j|djtj
��|d}|j|j|d�|j|j|d�|j|j|d�WdQRXdS)Nz$on OpenBSD this requires root accessrXrrc)r6r7r�threadsrSr,r�r*r8r�r�idr:r;r{�system_time)r0r>r�r�Zathreadr1r1r2�test_threadss zTestProcess.test_threadsc
Cs�t�}tj|j�}trDy|j�Wn tjk
rBtjd��YnX|j	|j
�jtdd�|j�D��dd�|j	|j
�j
tdd�|j�D��dd�dS)Nz$on OpenBSD this requires root accesscSsg|]
}|j�qSr1)r{)r�rmr1r1r2r�7sz.TestProcess.test_threads_2.<locals>.<listcomp>g�������?)ZdeltacSsg|]
}|j�qSr1)r�)r�rmr1r1r2r�:s)rr6r7r9rr�rSr,r�ZassertAlmostEqualrq�user�sum�system)r0r?r>r1r1r2�test_threads_2)szTestProcess.test_threads_2cCs�tj�}|j�dd�\}}|j�}|j|d�|j|d�dgd}|j�dd�\}}|j�}|j||�|j||�|j||�~tr�|j�}	|j|	j|	j	�|j|	j
|	j�|j�}	x |	jD]}
|jt
|	|
�d�q�WdS)Nrcri`�)r6r7Zmemory_info�memory_percentr�rkr
r8ZrssZwset�vmsZpagefilerrru)r0r>Zrss1Zvms1Zpercent1ZmemarrZrss2Zvms2Zpercent2�memr\r1r1r2�test_memory_info<s&
zTestProcess.test_memory_infocCs�tj�j}tj�j�}xB|jD]8}t||�}|j|d||fd�|j|||||fd�qWt	sft
sftrt|j|jd�t	r�|j|j
d�|j|jd�dS)Nr)�msg)r6Zvirtual_memory�totalr7Zmemory_full_inforrrurkrlrr
r�ussZpssZswap)r0r�r�r\r�r1r1r2�test_memory_full_infoZs

z!TestProcess.test_memory_full_infoc
Cstj�}|j�}dd�|D�}|jt|�tt|���|jdd�}x~|D]v}|jjd�sHtr�yWq�t	k
r�t
sx�n,td��}|j�}WdQRXd|j|kr��Yq�XqHdt
jj|j�krHqHWxN|D]F}x@|jD]6}t||�}	|d	kr�q�q�|dk�r�q�|j|	ttf�q�Wq�WdS)
NcSsg|]}|�qSr1r1)r�rmr1r1r2r�ksz0TestProcess.test_memory_maps.<locals>.<listcomp>F)Zgrouped�[z/proc/self/smapsz%s (deleted)Z64r��addr�perms)r�r�)r6r7�memory_mapsr8r��setr�r�r�AssertionErrorrr�r�r:�basenamerrrurir�r)
r0r>�maps�pathsZext_maps�ntr��dataZfnamer�r1r1r2�test_memory_mapsgs8





zTestProcess.test_memory_mapsc
sHt��8}dd���fdd�tj�j�D�}|j�|�|�WdQRXdS)NcSstjjtjj|��S)N)r:r�r��normcase)r>r1r1r2�normpath�sz8TestProcess.test_memory_maps_lists_lib.<locals>.normpathcsg|]}�|j��qSr1)r�)r�rm)r�r1r2r��sz:TestProcess.test_memory_maps_lists_lib.<locals>.<listcomp>)rr6r7r�r[)r0r�Zlibpathsr1)r�r2�test_memory_maps_lists_lib�s

z&TestProcess.test_memory_maps_lists_libcCsJtj�}|j�}|jdd�}|jt|jdd�ts:ts:trF|jdd�}dS)Nr�)Zmemtypez?!?r�)r6r7r�r<rUrrr
)r0r>r�r1r1r2�test_memory_percent�szTestProcess.test_memory_percentcCs&t�}tj|j�}|j�|j�dS)N)rr6r7r9rArB)r0r?r>r1r1r2�test_is_running�s
zTestProcess.test_is_runningcCs�t�}tj|j�j�}y|j|t�Wn�tk
r�trht	|�t	t�krht
jj}|j||�|t��nNdt
jdt
jdf}y |j|j|d�tj|d��Wntk
r�YnXYnXt|ddg�}|j|d�dS)Nz%s.%srrXrLz-czimport os; print('hey')Zhey)rr6r7r9�exer8r r�r
r�r:r�r�r��version_info�replacer%)r0r?r�r�Zver�outr1r1r2�test_exe�s zTestProcess.test_execCs�tddg}t|�}y(|jdjtj|j�j��dj|��Wn@tk
rzt	sVt
sVtrt|jtj|j�j�dt�n�YnXdS)Nz-czimport time; time.sleep(60)� r)r rr8�joinr6r7r9�cmdliner�rrr)r0r�r?r1r1r2�test_cmdline�s
zTestProcess.test_cmdlinecCs:tt�}tj|j�j�j�}tjj	tjj
tj��j�}dS)N)
rr r6r7r9r\�lowerr:r�r�r�r��
executable)r0r?r\Zpyexer1r1r2�	test_name�szTestProcess.test_namezbroken on SUNOSz
broken on AIXcs��fdd�}td�t��|j|��ddddddg}t|�}tj|j�}trZt|j�|j	|j
�|�|j	|j�tj
j���|j	tj
j|j��tj
j���dS)	Ncs&yt��Wntk
r YnXdS)N)r$rPr1)�
funky_pathr1r2�rm�sz.TestProcess.test_prog_w_funky_name.<locals>.rmz	foo bar )z-cz9import time; [time.sleep(0.01) for x in range(3000)];arg1Zarg2rLZarg3)r)r�
addCleanuprr6r7r9r+r-r8r�r\r:r�r�r�r�)r0r�r�r?r>r1)r�r2�test_prog_w_funky_name�s	

z"TestProcess.test_prog_w_funky_namecCsXtj�}|j�\}}}|j|tj��|j|tj��ttd�rT|jtj�|j��dS)N�	getresuid)	r6r7�uidsr8r:�getuid�geteuid�hasattrr�)r0r>�real�	effective�savedr1r1r2�	test_uidss
zTestProcess.test_uidscCsXtj�}|j�\}}}|j|tj��|j|tj��ttd�rT|jtj�|j��dS)Nr�)	r6r7�gidsr8r:�getgid�getegidr��	getresgid)r0r>r�r�rr1r1r2�	test_gidss
zTestProcess.test_gidscCs�tj�}|jt|jd�tr�z||j�}tjdkr@|j|t	j
�n|j|t�|j|tj
�|jtj�|j|j�tj�|jtj
�|j|j�tj
�Wd|jtj
�Xn�|j�}z�y�ttd�r�|jtjtjtj��|j��|jd�|j|j�d�ttd��r"|jtjtjtj��|j��t�sB|jd�|j|j�d�Wntjk
�r\YnXWdy|j|�Wntjk
�r�YnXXdS)N�strr�r��getpriorityrXr)r�r�)r6r7r<r��nicer
r�r�rirr�r�r8�NORMAL_PRIORITY_CLASSZHIGH_PRIORITY_CLASSr�r:r�PRIO_PROCESSr;rrS)r0r>ZinitZ
first_nicer1r1r2�	test_nice"sB




zTestProcess.test_nicecCstj�}|j|j�tj�dS)N)r6r7r8�statusZSTATUS_RUNNING)r0r>r1r1r2�test_statusKszTestProcess.test_statuscCsnt�}tj|j�}|j�}trZ|jd�\}}|j|tj	��dt
jkrj|j|t
jd�n|j|tj	��dS)N�\Z
USERDOMAIN)rr6r7r9�usernamer
�splitr8�getpassZgetuserr:�environ)r0r?r>rZdomainr1r1r2�
test_usernameOs
zTestProcess.test_usernamecCs*t�}tj|j�}|j|j�tj��dS)N)rr6r7r9r8�cwdr:�getcwd)r0r?r>r1r1r2�test_cwd[szTestProcess.test_cwdcCs.tddg}t|�}tj|j�}t|jd�dS)Nz-cz/import os, time; os.chdir('..'); time.sleep(60)z#ret == os.path.dirname(os.getcwd()))r rr6r7r9rr)r0�cmdr?r>r1r1r2�
test_cwd_2`s
zTestProcess.test_cwd_2cCs�tj�}|j�}|j|j|�ttd�r@|j|ttj|j	���|jt
|�t
t|���ttt
tj
dd����}xztsz|n|D]j}|j|g�|j|j�|g�ttd�r�|j|j�ttj|j	���t|d�r~|j|j�d|j��q~W|jg�t�r|j|j�|jj��n|j|j�|�ttd��rL|j|j�ttj|j	���|jt|jd�|j|�|jt|��|jt|��dS)N�sched_getaffinityT)�percpu�num_cpurrX)r6r7�cpu_affinityr�r�r:r8�listrr9r�r�rhrgr+rr�_procZ_get_eligible_cpusr<r��tuple)r0r>�initialZall_cpus�nr1r1r2�test_cpu_affinitygs4






zTestProcess.test_cpu_affinitycCszt�}tj|j�}ttjdd��dg}|jt|j|�|jt|jt	dd��|jt
|jddg�|jt|jdd	g�dS)
NT)rr�i'i�*r�1rXrY)rr6r7r9r�rqr<rUrrhr�)r0r?r>Zinvalid_cpur1r1r2�test_cpu_affinity_errs�sz"TestProcess.test_cpu_affinity_errscCs�tj�}|j�}|j|j|�g}xBtdt|�d�D],}x&tj||�D]}|rH|jt	|��qHWq6Wx&|D]}|j|�|j
|j�|�qlWdS)NrrX)r6r7rr�rhr��	itertools�combinations�appendrr8)r0r>r!Zcombos�lZsubsetZcombor1r1r2�"test_cpu_affinity_all_combinations�s

z.TestProcess.test_cpu_affinity_all_combinationsz
broken on BSDzunreliable on APPVEYORc	Cs$tj�}|j�}|jt|k�ttd��n}|jdd�|j�t|jdt	|��}x<|D]"}|j
tkrZtrz|j|j
d�PqZW|jdt|��WdQRXx|D]}q�Wdt}ttd|g�}tj|j�}xBtd�D]*}d	d
�|j�D�}t|kr�Ptjd�q�W|jt|�x|D]}�qWdS)Nr��xizlen(ret) != %izno file found; files=%sz2import time; f = open(r'%s', 'r'); time.sleep(60);z-crfcSsg|]
}|j�qSr1)r�)r�rmr1r1r2r��sz/TestProcess.test_open_files.<locals>.<listcomp>g{�G�z�?)r6r7�
open_filesrCr)r�r��flushrr�r�rr8Zpositionrz�reprrr r9rhrd�sleepr[)	r0r>�filesr��filer�r?rm�	filenamesr1r1r2�test_open_files�s4



zTestProcess.test_open_filescCs�ttd���}tj�}xB|j�D] }|j|jks<|j|j�krPqW|j	dt
|j���|j|j|j�tr||j|jd�n|j|j|j��|j�d}|j|d|j�|j|d|j�|j
|j|j��WdQRXdS)N�wzno file found; files=%srXrrY)r�r)r6r7r,r�r\�fd�filenorzr.r8r
�assertNotIn)r0Zfileobjr>r1Zntupler1r1r2�test_open_files_2�szTestProcess.test_open_files_2cCs�tj�}|j�}ttd�}|j|j�|j|j�|d�tj�}|j|j�|j|j�|d�|j�|j�|j|j�|�dS)Nr4rXrc)	r6r7Znum_fdsr�r)r��closer8�socket)r0r>�startr1Zsockr1r1r2�test_num_fds�s
zTestProcess.test_num_fdsz not reliable on OPENBSD & NETBSDcCsLtj�}t|j��}x(td�D]}t|j��}||krdSqW|jd�dS)Ni �z7num ctx switches still the same after 50.000 iterations)r6r7r�Znum_ctx_switchesrhrz)r0r>Zbeforerm�afterr1r1r2�test_num_ctx_switches�sz!TestProcess.test_num_ctx_switchescCs�ttd�r"|jtj�j�tj��tj�}t�}tj|j	�}|j|j�|�t
dd�tr^dSx2tj�D]&}|j	|j	krzqh|j
|j�||d�qhWdS)N�getppidT)�	recursive)r�)r�r:r8r6r7�ppidr?r;rr9r!r
�process_iter�assertNotEqual)r0�this_parentr?r>r1r1r2�	test_ppids

zTestProcess.test_ppidcCs0tj�}t�}tj|j�}|j|j�j|�dS)N)r:r;rr6r7r9r8�parent)r0rDr?r>r1r1r2�test_parentszTestProcess.test_parentc	CsFt�}tj|j�}tjdtjdd�d��|j|j��WdQRXdS)Nzpsutil.Processrr�)rM)	rr6r7r9rrOrRr�rF)r0r?r>r1r1r2�test_parent_disappeared s
z#TestProcess.test_parent_disappearedcCs�tj�}|j|j�g�|j|jdd�g�tdd�}|j�}|jdd�}xL||fD]@}|jt|�d�|j|dj|j�|j|dj�tj	��qTWdS)NT)r@r)Z
creationflagsrX)
r6r7r8�childrenrr�r9rAr:r;)r0r>r?Z	children1Z	children2rIr1r1r2�
test_children(s
zTestProcess.test_childrencCsdt�\}}tj�}|j|j�|g�|j|jdd�||g�|j�|j�|j|jdd�g�dS)NT)r@)rr6r7r8rIrIrB)r0r`rar>r1r1r2�test_children_recursive7s
z#TestProcess.test_children_recursivec
Cs�tjt�}x@tj�D]4}y||j�d7<Wqtjk
rFYqXqWt|j�dd�d�dd}tj	|�}y|j
dd�}Wntjk
r�YnX|jt
|�t
t|���dS)	NrXcSs|dS)NrXr1)rmr1r1r2�<lambda>Msz6TestProcess.test_children_duplicates.<locals>.<lambda>)�keyrT)r@rY)�collections�defaultdictr�r6rBrA�Error�sorted�itemsr7rIrSr8r�r�)r0�tabler>r9�cr1r1r2�test_children_duplicatesDs


z$TestProcess.test_children_duplicatescCsdt�}tj|j�}|j�x*td�D]}|j�tjkr8Ptj	d�q$W|j
�|j|j�tj�dS)Nrfg{�G�z�?)rr6r7r9�suspendrhr
ZSTATUS_STOPPEDrdr/�resumerC)r0r?r>rmr1r1r2�test_suspend_resumeVszTestProcess.test_suspend_resumecCs$|jttjd�|jttjd�dS)Nr$rXrY)r<r�r6r7rU)r0r1r1r2�test_invalid_pidaszTestProcess.test_invalid_pidc;Cs�tj�}|jddgd�}|jt|j��ddg�tjttj���}|jdgdd�}t|dt	�sp|j|dd�t
jddtjd	��"|j|jd
gdd�d
di�WdQRXt
jddtj
|jd�d	��|jtj
|jd
gd�WdQRXt
jddtj|jd�d	��"|j|jd
gdd�d
di�WdQRXt
jddtd	��F|j�}|jd
t	|j���|jt��|jd
gd�WdQRXWdQRX|jt��|jd�WdQRX|jt��|jdg�WdQRX|jt��|jddg�WdQRXdS)
Nr�r\)�attrsZconnectionsr�)rZZad_valuezpsutil.Process.niceT)ZcreaterMr	rXZbar)r6r7�as_dictr8rQ�keysryrT�
isinstancerrrOrSrRr9r<�
ZombieProcess�NotImplementedErrorr7r�rU)r0r>�dr1r1r2�test_as_dictes>""
"zTestProcess.test_as_dictcCs�tjd��@}tj�}|j��|j�|j�WdQRX|j|jd�WdQRXtjd��}|j�|j�WdQRX|j|jd�dS)Nz$psutil._psplatform.Process.cpu_timesrXrc)rrOr6r7�oneshotrqr8�
call_count)r0ror>r1r1r2�test_oneshot�s
zTestProcess.test_oneshotc&Cs�tjd���}tjd��r}tj�}|j��:|j�|j�|j��|j�|j�WdQRXWdQRX|j|jd�|j|jd�WdQRXWdQRXtjd��}|j�|j�WdQRX|j|jd�dS)Nz$psutil._psplatform.Process.cpu_timesz(psutil._psplatform.Process.oneshot_enterrXrc)rrOr6r7rbrqr8rc)r0�m1�m2r>ror1r1r2�test_oneshot_twice�s

"zTestProcess.test_oneshot_twicec
Cs�t�}tj|j�}|j�|j�tr8ttjd|j�|j	|j
��ddddddg}trjtrj|j
d��xTt|�D�]F}|jd	�sv||kr�qvy�t||�}|d
kr�tr�|d�}n
|tj�}np|dkr�|�}|d
�}nX|dkr�|tj�}|tjd�}n8|dk�r|�}|dg�}n|dk�r(|tj�}n|�}Wnztjk
�rV|jd|�Yqvtjk
�rlYqvtjk
�r�t�r�|dk�r�n�Yqvtk
�r�YqvX|jd||f�qvWdS)Nz
%s not in retr9rZrBr�rbZmemory_info_exr��_r	rXr�rcrWrrrNz/ZombieProcess for %r was not supposed to happenr�r�z4NoSuchProcess exception not raised for %r, retval=%s)rWrW)r�r�)rr6r7r9rIrBr
rrTrCrZrrr(r�r�rurr
r�rErJr^rzrRrSrr_)r0r?r>Zexcluded_namesr\�methr�r1r1r2�test_halfway_terminated_process�s^









z+TestProcess.test_halfway_terminated_processcCs�dd�}t�}|jtdd�tj|�}|j|j�tj�|j|j	��|j
�||j�}|dk	rl|j|g�t|d�r�||j
tj�||j
tjd�||j�t|d�r�y||jdg�Wn:tk
r�}ztr�tr�d	t|�kr�n�WYdd}~XnX||jd�t|d
��r0t�r$||jdd�n||jd�t|d��rL||j
tjd�||j�||j�||j�||j�|jtj|��t�r�t�r�|j|tj��|j|dd
�tj�D��it_|j|dd
�tj�D��dS)Nc_s,y
|||�Stjtjfk
r&YnXdS)N)r6r^rS)Zfun�args�kwargsr1r1r2�succeed_or_zombie_p_exc�s
z@TestProcess.test_zombie_process.<locals>.succeed_or_zombie_p_excT)r@r�rWrrznot eligibler�rccSsg|]
}|j�qSr1)r9)r�rmr1r1r2r�9sz3TestProcess.test_zombie_process.<locals>.<listcomp>cSsg|]
}|j�qSr1)r9)r�rmr1r1r2r�;s)rWrW)rWrW) rr�r!r6r7r8r
�
STATUS_ZOMBIE�
assertTruerZr[rVr�r�r�rFrrUr+rrr	r�rWrIrArDrr[rTrBZ_pmap)r0rmZzpidZzprocr��errr1r1r2�test_zombie_process�sP










zTestProcess.test_zombie_processc	Cs,tj�}tjdtjd�d��}WdQRXdS)Nzpsutil.Processr)rM)r6r7rrOr^)r0r>ror1r1r2�$test_zombie_process_is_running_w_exc=sz0TestProcess.test_zombie_process_is_running_w_excc
Cs>tj�}tjdtjd�d��}|j|j�tj�WdQRXdS)Nz!psutil._psplatform.Process.statusr)rM)r6r7rrOr^r8r
rn)r0r>ror1r1r2� test_zombie_process_status_w_excGs
z,TestProcess.test_zombie_process_status_w_exccCs*dtj�kr"|jtjtjd�dStjd�}x�tjD]�}|dkrBq4t||�}y
|�}Wntjk
rlYq4X|d
kr�|j|j	d�q4|dkr�t
r�|j|j�d�q�tr�|j|j�d�q4|dkr4q4Wt
|d	�r�y|jtj�Wntjk
r�YnX|j�t�s&|jdtj��|jtjd��dS)Nrr9r�rr�rootzNT AUTHORITY\SYSTEMr\r�)r�r)r6rTr<rRr7Z_as_dict_attrnamesrurSr8r�rrr
r�r�r�r[rr[rorD)r0r>r\rir�r1r1r2�
test_pid_0Qs<



zTestProcess.test_pid_0cCs@dd�}d|_tj�}||j��}|tjj��}|j||�dS)NcSsb|jdd�|jdd�|jdd�trL|jdd�|jdd�|jdd�tdd�|j�D��S)	NZPSUTIL_TESTINGZPLAT�HOMEZ__CF_USER_TEXT_ENCODINGZVERSIONER_PYTHON_PREFER_32_BITZVERSIONER_PYTHON_VERSIONcSs$g|]\}}|jd�|jd�f�qS)z
)�rstrip)r��k�vr1r1r2r��sz@TestProcess.test_environ.<locals>.clean_dict.<locals>.<listcomp>)�popr�dictrR)r`r1r1r2�
clean_dictzsz,TestProcess.test_environ.<locals>.clean_dict)ZmaxDiffr6r7rr:�copyr8)r0r|r>Zd1Zd2r1r1r2�test_environxszTestProcess.test_environcCs�tjd�}t}t||d�|jt|�t|gtjtjd�}t	j
|j�}t|j�|j
|j��|j|jj�d�|j|j�ddd��|j�|j|jd�dS)	Na�
            #include <unistd.h>
            #include <fcntl.h>
            char * const argv[] = {"cat", 0};
            char * const envp[] = {"A=1", "X", "C=3", 0};
            int main(void) {
                /* Close stderr on exec so parent can wait for the execve to
                 * finish. */
                if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0)
                    return 0;
                return execve("/bin/cat", argv, envp);
            }
            )Zc_code)r��stderr�r$�3)�A�Cr)�textwrap�dedentr)rr�r$r�
subprocess�PIPEr6r7r9r-rorZr8rr�r�communicate�
returncode)r0r^r�r?r>r1r1r2�test_weird_environ�s

zTestProcess.test_weird_environN)d�__name__�
__module__�__qualname__�__doc__r3r4r@rHrKrVr_rbrernrprwr}r,ZskipIfrrr�rr+r�rr'rr�rr
rr.r�r�rr�r�r�r�r�r�r�rr�r"r&rr�r�r�rr�r�r�r�r�r�r�r	rr�rrrrrrrrr#r%r*rr
r3r8r<rrr>rErGrHrJrKrUrXrYrardrgrjrqrrrsrurr~r�r1r1r1r2r/Ks�

 /	
		+ ."

)



)*

%


.
@I

'r/c@sReZdZdZeed�r&ej�Zej�Z	dd�Z
dd�Zdd�Zd	d
�Z
dd�Zd
S)�LimitedUserTestCasez�Repeat the previous tests by using a limited user.
        Executed only on UNIX and only if the user who run the test script
        is root.
        r�cs\tj|f|�|�xDdd�t|�D�D].}t||���fdd�}t||tj||��q&WdS)NcSsg|]}|jd�r|�qS)Ztest)r�)r�rmr1r1r2r��sz0LimitedUserTestCase.__init__.<locals>.<listcomp>cs&y
��Wntjk
r YnXdS)N)r6rS)r0)rir1r2�test_�s
z+LimitedUserTestCase.__init__.<locals>.test_)r/�__init__r�ru�setattr�types�
MethodType)r0rkrl�attrr�r1)rir2r��s

zLimitedUserTestCase.__init__cCs*tt�tj|�tjd�tjd�dS)Ni�)r$r)r/r3r:�setegid�seteuid)r0r1r1r2r3�s

zLimitedUserTestCase.setUpcCs&tj|j�tj|j�tj|�dS)N)r:r��PROCESS_UIDr��PROCESS_GIDr/r4)r0r1r1r2r4�szLimitedUserTestCase.tearDowncCs8ytj�jd�Wntjk
r(YnX|jd�dS)NrXzexception not raisedrY)r6r7r	rSrz)r0r1r1r2r�s
zLimitedUserTestCase.test_nicecCsdS)Nr1)r0r1r1r2rq�sz'LimitedUserTestCase.test_zombie_processN)r�r�r�r�r�r:r�r�rr�r�r3r4rrqr1r1r1r2r��s
r�c@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)�	TestPopenzTests for psutil.Popen class.cCs
t�dS)N)r!)r0r1r1r2r4�szTestPopen.tearDowncCsjtddg}tj|tjtjd��B}|j�|j�|j|jt	|��|j
tt|d�|j
�WdQRXdS)Nz-czimport time; time.sleep(60);)r�rr�)r r6�Popenr�r�r\rqr�ror�r<r=rurI)r0r�procr1r1r2�	test_misc�s

zTestPopen.test_miscc
CsBtjtdgtjtjtjd��}|j�WdQRX|j|jd�dS)Nz-V)r�rr�r)r6r�r r�r�r�r8r�)r0r�r1r1r2�test_ctx_manager�s
zTestPopen.test_ctx_managercCs�tddg}tj|tjtjd���}|j�|j�|jtj|j�|jtj|j	�|jtj|j
tj�t
r�tjdkr�|jtj|j
tj�|jtj|j
tj�WdQRXdS)Nz-czimport time; time.sleep(60);)r�rrcr�)rcr�)r r6r�r�r�rIrBr<rRrArNrErJr
r�r�ZCTRL_C_EVENTZCTRL_BREAK_EVENT)r0rr�r1r1r2�test_kill_terminates

zTestPopen.test_kill_terminateN)r�r�r�r�r4r�r�r�r1r1r1r2r��s
r��__main__)Er�rNrQrr&r:rEr:r�r�r�r�rdr�r6rrrrrrrr	r
Zpsutil._compatrrZpsutil.testsr
rrrrrrrrrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.ZTestCaser/r�r�r�r��__file__r1r1r1r2�<module>s�q53
tests/test_system.py000064400000104057150466730550010665 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tests for system APIS."""

import contextlib
import datetime
import errno
import os
import pprint
import shutil
import signal
import socket
import sys
import tempfile
import time

import psutil
from psutil import AIX
from psutil import BSD
from psutil import FREEBSD
from psutil import LINUX
from psutil import NETBSD
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._compat import long
from psutil.tests import APPVEYOR
from psutil.tests import ASCII_FS
from psutil.tests import check_net_address
from psutil.tests import DEVNULL
from psutil.tests import enum
from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import HAS_CPU_FREQ
from psutil.tests import HAS_SENSORS_BATTERY
from psutil.tests import HAS_SENSORS_FANS
from psutil.tests import HAS_SENSORS_TEMPERATURES
from psutil.tests import mock
from psutil.tests import reap_children
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_rmpath
from psutil.tests import TESTFN
from psutil.tests import TESTFN_UNICODE
from psutil.tests import TRAVIS
from psutil.tests import unittest


# ===================================================================
# --- System-related API tests
# ===================================================================


class TestSystemAPIs(unittest.TestCase):
    """Tests for system-related APIs."""

    def setUp(self):
        safe_rmpath(TESTFN)

    def tearDown(self):
        reap_children()

    def test_process_iter(self):
        self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
        sproc = get_test_subprocess()
        self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
        p = psutil.Process(sproc.pid)
        p.kill()
        p.wait()
        self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])

        with mock.patch('psutil.Process',
                        side_effect=psutil.NoSuchProcess(os.getpid())):
            self.assertEqual(list(psutil.process_iter()), [])
        with mock.patch('psutil.Process',
                        side_effect=psutil.AccessDenied(os.getpid())):
            with self.assertRaises(psutil.AccessDenied):
                list(psutil.process_iter())

    def test_prcess_iter_w_params(self):
        for p in psutil.process_iter(attrs=['pid']):
            self.assertEqual(list(p.info.keys()), ['pid'])
        with self.assertRaises(ValueError):
            list(psutil.process_iter(attrs=['foo']))
        with mock.patch("psutil._psplatform.Process.cpu_times",
                        side_effect=psutil.AccessDenied(0, "")) as m:
            for p in psutil.process_iter(attrs=["pid", "cpu_times"]):
                self.assertIsNone(p.info['cpu_times'])
                self.assertGreaterEqual(p.info['pid'], 0)
            assert m.called
        with mock.patch("psutil._psplatform.Process.cpu_times",
                        side_effect=psutil.AccessDenied(0, "")) as m:
            flag = object()
            for p in psutil.process_iter(
                    attrs=["pid", "cpu_times"], ad_value=flag):
                self.assertIs(p.info['cpu_times'], flag)
                self.assertGreaterEqual(p.info['pid'], 0)
            assert m.called

    def test_wait_procs(self):
        def callback(p):
            pids.append(p.pid)

        pids = []
        sproc1 = get_test_subprocess()
        sproc2 = get_test_subprocess()
        sproc3 = get_test_subprocess()
        procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)]
        self.assertRaises(ValueError, psutil.wait_procs, procs, timeout=-1)
        self.assertRaises(TypeError, psutil.wait_procs, procs, callback=1)
        t = time.time()
        gone, alive = psutil.wait_procs(procs, timeout=0.01, callback=callback)

        self.assertLess(time.time() - t, 0.5)
        self.assertEqual(gone, [])
        self.assertEqual(len(alive), 3)
        self.assertEqual(pids, [])
        for p in alive:
            self.assertFalse(hasattr(p, 'returncode'))

        @retry_before_failing(30)
        def test(procs, callback):
            gone, alive = psutil.wait_procs(procs, timeout=0.03,
                                            callback=callback)
            self.assertEqual(len(gone), 1)
            self.assertEqual(len(alive), 2)
            return gone, alive

        sproc3.terminate()
        gone, alive = test(procs, callback)
        self.assertIn(sproc3.pid, [x.pid for x in gone])
        if POSIX:
            self.assertEqual(gone.pop().returncode, -signal.SIGTERM)
        else:
            self.assertEqual(gone.pop().returncode, 1)
        self.assertEqual(pids, [sproc3.pid])
        for p in alive:
            self.assertFalse(hasattr(p, 'returncode'))

        @retry_before_failing(30)
        def test(procs, callback):
            gone, alive = psutil.wait_procs(procs, timeout=0.03,
                                            callback=callback)
            self.assertEqual(len(gone), 3)
            self.assertEqual(len(alive), 0)
            return gone, alive

        sproc1.terminate()
        sproc2.terminate()
        gone, alive = test(procs, callback)
        self.assertEqual(set(pids), set([sproc1.pid, sproc2.pid, sproc3.pid]))
        for p in gone:
            self.assertTrue(hasattr(p, 'returncode'))

    def test_wait_procs_no_timeout(self):
        sproc1 = get_test_subprocess()
        sproc2 = get_test_subprocess()
        sproc3 = get_test_subprocess()
        procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)]
        for p in procs:
            p.terminate()
        gone, alive = psutil.wait_procs(procs)

    def test_boot_time(self):
        bt = psutil.boot_time()
        self.assertIsInstance(bt, float)
        self.assertGreater(bt, 0)
        self.assertLess(bt, time.time())

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_PAGESIZE(self):
        # pagesize is used internally to perform different calculations
        # and it's determined by using SC_PAGE_SIZE; make sure
        # getpagesize() returns the same value.
        import resource
        self.assertEqual(os.sysconf("SC_PAGE_SIZE"), resource.getpagesize())

    def test_virtual_memory(self):
        mem = psutil.virtual_memory()
        assert mem.total > 0, mem
        assert mem.available > 0, mem
        assert 0 <= mem.percent <= 100, mem
        assert mem.used > 0, mem
        assert mem.free >= 0, mem
        for name in mem._fields:
            value = getattr(mem, name)
            if name != 'percent':
                self.assertIsInstance(value, (int, long))
            if name != 'total':
                if not value >= 0:
                    self.fail("%r < 0 (%s)" % (name, value))
                if value > mem.total:
                    self.fail("%r > total (total=%s, %s=%s)"
                              % (name, mem.total, name, value))

    def test_swap_memory(self):
        mem = psutil.swap_memory()
        self.assertEqual(
            mem._fields, ('total', 'used', 'free', 'percent', 'sin', 'sout'))

        assert mem.total >= 0, mem
        assert mem.used >= 0, mem
        if mem.total > 0:
            # likely a system with no swap partition
            assert mem.free > 0, mem
        else:
            assert mem.free == 0, mem
        assert 0 <= mem.percent <= 100, mem
        assert mem.sin >= 0, mem
        assert mem.sout >= 0, mem

    def test_pid_exists(self):
        sproc = get_test_subprocess()
        self.assertTrue(psutil.pid_exists(sproc.pid))
        p = psutil.Process(sproc.pid)
        p.kill()
        p.wait()
        self.assertFalse(psutil.pid_exists(sproc.pid))
        self.assertFalse(psutil.pid_exists(-1))
        self.assertEqual(psutil.pid_exists(0), 0 in psutil.pids())

    def test_pid_exists_2(self):
        reap_children()
        pids = psutil.pids()
        for pid in pids:
            try:
                assert psutil.pid_exists(pid)
            except AssertionError:
                # in case the process disappeared in meantime fail only
                # if it is no longer in psutil.pids()
                time.sleep(.1)
                if pid in psutil.pids():
                    self.fail(pid)
        pids = range(max(pids) + 5000, max(pids) + 6000)
        for pid in pids:
            self.assertFalse(psutil.pid_exists(pid), msg=pid)

    def test_pids(self):
        plist = [x.pid for x in psutil.process_iter()]
        pidlist = psutil.pids()
        self.assertEqual(plist.sort(), pidlist.sort())
        # make sure every pid is unique
        self.assertEqual(len(pidlist), len(set(pidlist)))

    def test_test(self):
        # test for psutil.test() function
        stdout = sys.stdout
        sys.stdout = DEVNULL
        try:
            psutil.test()
        finally:
            sys.stdout = stdout

    def test_cpu_count(self):
        logical = psutil.cpu_count()
        self.assertEqual(logical, len(psutil.cpu_times(percpu=True)))
        self.assertGreaterEqual(logical, 1)
        #
        if os.path.exists("/proc/cpuinfo"):
            with open("/proc/cpuinfo") as fd:
                cpuinfo_data = fd.read()
            if "physical id" not in cpuinfo_data:
                raise unittest.SkipTest("cpuinfo doesn't include physical id")
        physical = psutil.cpu_count(logical=False)
        self.assertGreaterEqual(physical, 1)
        self.assertGreaterEqual(logical, physical)

    def test_cpu_count_none(self):
        # https://github.com/giampaolo/psutil/issues/1085
        for val in (-1, 0, None):
            with mock.patch('psutil._psplatform.cpu_count_logical',
                            return_value=val) as m:
                self.assertIsNone(psutil.cpu_count())
                assert m.called
            with mock.patch('psutil._psplatform.cpu_count_physical',
                            return_value=val) as m:
                self.assertIsNone(psutil.cpu_count(logical=False))
                assert m.called

    def test_cpu_times(self):
        # Check type, value >= 0, str().
        total = 0
        times = psutil.cpu_times()
        sum(times)
        for cp_time in times:
            self.assertIsInstance(cp_time, float)
            self.assertGreaterEqual(cp_time, 0.0)
            total += cp_time
        self.assertEqual(total, sum(times))
        str(times)
        # CPU times are always supposed to increase over time
        # or at least remain the same and that's because time
        # cannot go backwards.
        # Surprisingly sometimes this might not be the case (at
        # least on Windows and Linux), see:
        # https://github.com/giampaolo/psutil/issues/392
        # https://github.com/giampaolo/psutil/issues/645
        # if not WINDOWS:
        #     last = psutil.cpu_times()
        #     for x in range(100):
        #         new = psutil.cpu_times()
        #         for field in new._fields:
        #             new_t = getattr(new, field)
        #             last_t = getattr(last, field)
        #             self.assertGreaterEqual(new_t, last_t,
        #                                     msg="%s %s" % (new_t, last_t))
        #         last = new

    def test_cpu_times_time_increases(self):
        # Make sure time increases between calls.
        t1 = sum(psutil.cpu_times())
        time.sleep(0.1)
        t2 = sum(psutil.cpu_times())
        difference = t2 - t1
        if not difference >= 0.05:
            self.fail("difference %s" % difference)

    def test_per_cpu_times(self):
        # Check type, value >= 0, str().
        for times in psutil.cpu_times(percpu=True):
            total = 0
            sum(times)
            for cp_time in times:
                self.assertIsInstance(cp_time, float)
                self.assertGreaterEqual(cp_time, 0.0)
                total += cp_time
            self.assertEqual(total, sum(times))
            str(times)
        self.assertEqual(len(psutil.cpu_times(percpu=True)[0]),
                         len(psutil.cpu_times(percpu=False)))

        # Note: in theory CPU times are always supposed to increase over
        # time or remain the same but never go backwards. In practice
        # sometimes this is not the case.
        # This issue seemd to be afflict Windows:
        # https://github.com/giampaolo/psutil/issues/392
        # ...but it turns out also Linux (rarely) behaves the same.
        # last = psutil.cpu_times(percpu=True)
        # for x in range(100):
        #     new = psutil.cpu_times(percpu=True)
        #     for index in range(len(new)):
        #         newcpu = new[index]
        #         lastcpu = last[index]
        #         for field in newcpu._fields:
        #             new_t = getattr(newcpu, field)
        #             last_t = getattr(lastcpu, field)
        #             self.assertGreaterEqual(
        #                 new_t, last_t, msg="%s %s" % (lastcpu, newcpu))
        #     last = new

    def test_per_cpu_times_2(self):
        # Simulate some work load then make sure time have increased
        # between calls.
        tot1 = psutil.cpu_times(percpu=True)
        stop_at = time.time() + 0.1
        while True:
            if time.time() >= stop_at:
                break
        tot2 = psutil.cpu_times(percpu=True)
        for t1, t2 in zip(tot1, tot2):
            t1, t2 = sum(t1), sum(t2)
            difference = t2 - t1
            if difference >= 0.05:
                return
        self.fail()

    def test_cpu_times_comparison(self):
        # Make sure the sum of all per cpu times is almost equal to
        # base "one cpu" times.
        base = psutil.cpu_times()
        per_cpu = psutil.cpu_times(percpu=True)
        summed_values = base._make([sum(num) for num in zip(*per_cpu)])
        for field in base._fields:
            self.assertAlmostEqual(
                getattr(base, field), getattr(summed_values, field), delta=1)

    def _test_cpu_percent(self, percent, last_ret, new_ret):
        try:
            self.assertIsInstance(percent, float)
            self.assertGreaterEqual(percent, 0.0)
            self.assertIsNot(percent, -0.0)
            self.assertLessEqual(percent, 100.0 * psutil.cpu_count())
        except AssertionError as err:
            raise AssertionError("\n%s\nlast=%s\nnew=%s" % (
                err, pprint.pformat(last_ret), pprint.pformat(new_ret)))

    def test_cpu_percent(self):
        last = psutil.cpu_percent(interval=0.001)
        for x in range(100):
            new = psutil.cpu_percent(interval=None)
            self._test_cpu_percent(new, last, new)
            last = new
        with self.assertRaises(ValueError):
            psutil.cpu_percent(interval=-1)

    def test_per_cpu_percent(self):
        last = psutil.cpu_percent(interval=0.001, percpu=True)
        self.assertEqual(len(last), psutil.cpu_count())
        for x in range(100):
            new = psutil.cpu_percent(interval=None, percpu=True)
            for percent in new:
                self._test_cpu_percent(percent, last, new)
            last = new
        with self.assertRaises(ValueError):
            psutil.cpu_percent(interval=-1, percpu=True)

    def test_cpu_times_percent(self):
        last = psutil.cpu_times_percent(interval=0.001)
        for x in range(100):
            new = psutil.cpu_times_percent(interval=None)
            for percent in new:
                self._test_cpu_percent(percent, last, new)
            self._test_cpu_percent(sum(new), last, new)
            last = new

    def test_per_cpu_times_percent(self):
        last = psutil.cpu_times_percent(interval=0.001, percpu=True)
        self.assertEqual(len(last), psutil.cpu_count())
        for x in range(100):
            new = psutil.cpu_times_percent(interval=None, percpu=True)
            for cpu in new:
                for percent in cpu:
                    self._test_cpu_percent(percent, last, new)
                self._test_cpu_percent(sum(cpu), last, new)
            last = new

    def test_per_cpu_times_percent_negative(self):
        # see: https://github.com/giampaolo/psutil/issues/645
        psutil.cpu_times_percent(percpu=True)
        zero_times = [x._make([0 for x in range(len(x._fields))])
                      for x in psutil.cpu_times(percpu=True)]
        with mock.patch('psutil.cpu_times', return_value=zero_times):
            for cpu in psutil.cpu_times_percent(percpu=True):
                for percent in cpu:
                    self._test_cpu_percent(percent, None, None)

    def test_disk_usage(self):
        usage = psutil.disk_usage(os.getcwd())
        self.assertEqual(usage._fields, ('total', 'used', 'free', 'percent'))

        assert usage.total > 0, usage
        assert usage.used > 0, usage
        assert usage.free > 0, usage
        assert usage.total > usage.used, usage
        assert usage.total > usage.free, usage
        assert 0 <= usage.percent <= 100, usage.percent
        if hasattr(shutil, 'disk_usage'):
            # py >= 3.3, see: http://bugs.python.org/issue12442
            shutil_usage = shutil.disk_usage(os.getcwd())
            tolerance = 5 * 1024 * 1024  # 5MB
            self.assertEqual(usage.total, shutil_usage.total)
            self.assertAlmostEqual(usage.free, shutil_usage.free,
                                   delta=tolerance)
            self.assertAlmostEqual(usage.used, shutil_usage.used,
                                   delta=tolerance)

        # if path does not exist OSError ENOENT is expected across
        # all platforms
        fname = tempfile.mktemp()
        with self.assertRaises(OSError) as exc:
            psutil.disk_usage(fname)
        self.assertEqual(exc.exception.errno, errno.ENOENT)

    def test_disk_usage_unicode(self):
        # See: https://github.com/giampaolo/psutil/issues/416
        if ASCII_FS:
            with self.assertRaises(UnicodeEncodeError):
                psutil.disk_usage(TESTFN_UNICODE)

    def test_disk_usage_bytes(self):
        psutil.disk_usage(b'.')

    def test_disk_partitions(self):
        # all = False
        ls = psutil.disk_partitions(all=False)
        # on travis we get:
        #     self.assertEqual(p.cpu_affinity(), [n])
        # AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7,... != [0]
        self.assertTrue(ls, msg=ls)
        for disk in ls:
            self.assertIsInstance(disk.device, str)
            self.assertIsInstance(disk.mountpoint, str)
            self.assertIsInstance(disk.fstype, str)
            self.assertIsInstance(disk.opts, str)
            if WINDOWS and 'cdrom' in disk.opts:
                continue
            if not POSIX:
                assert os.path.exists(disk.device), disk
            else:
                # we cannot make any assumption about this, see:
                # http://goo.gl/p9c43
                disk.device
            if SUNOS or TRAVIS:
                # on solaris apparently mount points can also be files
                assert os.path.exists(disk.mountpoint), disk
            else:
                assert os.path.isdir(disk.mountpoint), disk
            assert disk.fstype, disk

        # all = True
        ls = psutil.disk_partitions(all=True)
        self.assertTrue(ls, msg=ls)
        for disk in psutil.disk_partitions(all=True):
            if not WINDOWS:
                try:
                    os.stat(disk.mountpoint)
                except OSError as err:
                    if TRAVIS and OSX and err.errno == errno.EIO:
                        continue
                    # http://mail.python.org/pipermail/python-dev/
                    #     2012-June/120787.html
                    if err.errno not in (errno.EPERM, errno.EACCES):
                        raise
                else:
                    if SUNOS or TRAVIS:
                        # on solaris apparently mount points can also be files
                        assert os.path.exists(disk.mountpoint), disk
                    else:
                        assert os.path.isdir(disk.mountpoint), disk
            self.assertIsInstance(disk.fstype, str)
            self.assertIsInstance(disk.opts, str)

        def find_mount_point(path):
            path = os.path.abspath(path)
            while not os.path.ismount(path):
                path = os.path.dirname(path)
            return path.lower()

        mount = find_mount_point(__file__)
        mounts = [x.mountpoint.lower() for x in
                  psutil.disk_partitions(all=True)]
        self.assertIn(mount, mounts)
        psutil.disk_usage(mount)

    def test_net_io_counters(self):
        def check_ntuple(nt):
            self.assertEqual(nt[0], nt.bytes_sent)
            self.assertEqual(nt[1], nt.bytes_recv)
            self.assertEqual(nt[2], nt.packets_sent)
            self.assertEqual(nt[3], nt.packets_recv)
            self.assertEqual(nt[4], nt.errin)
            self.assertEqual(nt[5], nt.errout)
            self.assertEqual(nt[6], nt.dropin)
            self.assertEqual(nt[7], nt.dropout)
            assert nt.bytes_sent >= 0, nt
            assert nt.bytes_recv >= 0, nt
            assert nt.packets_sent >= 0, nt
            assert nt.packets_recv >= 0, nt
            assert nt.errin >= 0, nt
            assert nt.errout >= 0, nt
            assert nt.dropin >= 0, nt
            assert nt.dropout >= 0, nt

        ret = psutil.net_io_counters(pernic=False)
        check_ntuple(ret)
        ret = psutil.net_io_counters(pernic=True)
        self.assertNotEqual(ret, [])
        for key in ret:
            self.assertTrue(key)
            self.assertIsInstance(key, str)
            check_ntuple(ret[key])

    def test_net_io_counters_no_nics(self):
        # Emulate a case where no NICs are installed, see:
        # https://github.com/giampaolo/psutil/issues/1062
        with mock.patch('psutil._psplatform.net_io_counters',
                        return_value={}) as m:
            self.assertIsNone(psutil.net_io_counters(pernic=False))
            self.assertEqual(psutil.net_io_counters(pernic=True), {})
            assert m.called

    def test_net_if_addrs(self):
        nics = psutil.net_if_addrs()
        assert nics, nics

        nic_stats = psutil.net_if_stats()

        # Not reliable on all platforms (net_if_addrs() reports more
        # interfaces).
        # self.assertEqual(sorted(nics.keys()),
        #                  sorted(psutil.net_io_counters(pernic=True).keys()))

        families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK])
        for nic, addrs in nics.items():
            self.assertIsInstance(nic, str)
            self.assertEqual(len(set(addrs)), len(addrs))
            for addr in addrs:
                self.assertIsInstance(addr.family, int)
                self.assertIsInstance(addr.address, str)
                self.assertIsInstance(addr.netmask, (str, type(None)))
                self.assertIsInstance(addr.broadcast, (str, type(None)))
                self.assertIn(addr.family, families)
                if sys.version_info >= (3, 4):
                    self.assertIsInstance(addr.family, enum.IntEnum)
                if nic_stats[nic].isup:
                    # Do not test binding to addresses of interfaces
                    # that are down
                    if addr.family == socket.AF_INET:
                        s = socket.socket(addr.family)
                        with contextlib.closing(s):
                            s.bind((addr.address, 0))
                    elif addr.family == socket.AF_INET6:
                        info = socket.getaddrinfo(
                            addr.address, 0, socket.AF_INET6,
                            socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
                        af, socktype, proto, canonname, sa = info
                        s = socket.socket(af, socktype, proto)
                        with contextlib.closing(s):
                            s.bind(sa)
                for ip in (addr.address, addr.netmask, addr.broadcast,
                           addr.ptp):
                    if ip is not None:
                        # TODO: skip AF_INET6 for now because I get:
                        # AddressValueError: Only hex digits permitted in
                        # u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0'
                        if addr.family != socket.AF_INET6:
                            check_net_address(ip, addr.family)
                # broadcast and ptp addresses are mutually exclusive
                if addr.broadcast:
                    self.assertIsNone(addr.ptp)
                elif addr.ptp:
                    self.assertIsNone(addr.broadcast)

        if BSD or OSX or SUNOS:
            if hasattr(socket, "AF_LINK"):
                self.assertEqual(psutil.AF_LINK, socket.AF_LINK)
        elif LINUX:
            self.assertEqual(psutil.AF_LINK, socket.AF_PACKET)
        elif WINDOWS:
            self.assertEqual(psutil.AF_LINK, -1)

    def test_net_if_addrs_mac_null_bytes(self):
        # Simulate that the underlying C function returns an incomplete
        # MAC address. psutil is supposed to fill it with null bytes.
        # https://github.com/giampaolo/psutil/issues/786
        if POSIX:
            ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)]
        else:
            ret = [('em1', -1, '06-3d-29', None, None, None)]
        with mock.patch('psutil._psplatform.net_if_addrs',
                        return_value=ret) as m:
            addr = psutil.net_if_addrs()['em1'][0]
            assert m.called
            if POSIX:
                self.assertEqual(addr.address, '06:3d:29:00:00:00')
            else:
                self.assertEqual(addr.address, '06-3d-29-00-00-00')

    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")  # raises EPERM
    def test_net_if_stats(self):
        nics = psutil.net_if_stats()
        assert nics, nics
        all_duplexes = (psutil.NIC_DUPLEX_FULL,
                        psutil.NIC_DUPLEX_HALF,
                        psutil.NIC_DUPLEX_UNKNOWN)
        for name, stats in nics.items():
            self.assertIsInstance(name, str)
            isup, duplex, speed, mtu = stats
            self.assertIsInstance(isup, bool)
            self.assertIn(duplex, all_duplexes)
            self.assertIn(duplex, all_duplexes)
            self.assertGreaterEqual(speed, 0)
            self.assertGreaterEqual(mtu, 0)

    @unittest.skipIf(LINUX and not os.path.exists('/proc/diskstats'),
                     '/proc/diskstats not available on this linux version')
    @unittest.skipIf(APPVEYOR and psutil.disk_io_counters() is None,
                     "unreliable on APPVEYOR")  # no visible disks
    def test_disk_io_counters(self):
        def check_ntuple(nt):
            self.assertEqual(nt[0], nt.read_count)
            self.assertEqual(nt[1], nt.write_count)
            self.assertEqual(nt[2], nt.read_bytes)
            self.assertEqual(nt[3], nt.write_bytes)
            if not (OPENBSD or NETBSD):
                self.assertEqual(nt[4], nt.read_time)
                self.assertEqual(nt[5], nt.write_time)
                if LINUX:
                    self.assertEqual(nt[6], nt.read_merged_count)
                    self.assertEqual(nt[7], nt.write_merged_count)
                    self.assertEqual(nt[8], nt.busy_time)
                elif FREEBSD:
                    self.assertEqual(nt[6], nt.busy_time)
            for name in nt._fields:
                assert getattr(nt, name) >= 0, nt

        ret = psutil.disk_io_counters(perdisk=False)
        assert ret is not None, "no disks on this system?"
        check_ntuple(ret)
        ret = psutil.disk_io_counters(perdisk=True)
        # make sure there are no duplicates
        self.assertEqual(len(ret), len(set(ret)))
        for key in ret:
            assert key, key
            check_ntuple(ret[key])
            if LINUX and key[-1].isdigit():
                # if 'sda1' is listed 'sda' shouldn't, see:
                # https://github.com/giampaolo/psutil/issues/338
                while key[-1].isdigit():
                    key = key[:-1]
                self.assertNotIn(key, ret.keys())

    def test_disk_io_counters_no_disks(self):
        # Emulate a case where no disks are installed, see:
        # https://github.com/giampaolo/psutil/issues/1062
        with mock.patch('psutil._psplatform.disk_io_counters',
                        return_value={}) as m:
            self.assertIsNone(psutil.disk_io_counters(perdisk=False))
            self.assertEqual(psutil.disk_io_counters(perdisk=True), {})
            assert m.called

    # can't find users on APPVEYOR or TRAVIS
    @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(),
                     "unreliable on APPVEYOR or TRAVIS")
    def test_users(self):
        users = psutil.users()
        self.assertNotEqual(users, [])
        for user in users:
            assert user.name, user
            self.assertIsInstance(user.name, str)
            self.assertIsInstance(user.terminal, (str, type(None)))
            if user.host is not None:
                self.assertIsInstance(user.host, (str, type(None)))
            user.terminal
            user.host
            assert user.started > 0.0, user
            datetime.datetime.fromtimestamp(user.started)
            if WINDOWS or OPENBSD:
                self.assertIsNone(user.pid)
            else:
                psutil.Process(user.pid)

    def test_cpu_stats(self):
        # Tested more extensively in per-platform test modules.
        infos = psutil.cpu_stats()
        self.assertEqual(
            infos._fields,
            ('ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'))
        for name in infos._fields:
            value = getattr(infos, name)
            self.assertGreaterEqual(value, 0)
            # on AIX, ctx_switches is always 0
            if not AIX and name in ('ctx_switches', 'interrupts'):
                self.assertGreater(value, 0)

    @unittest.skipIf(not HAS_CPU_FREQ, "not suported")
    def test_cpu_freq(self):
        def check_ls(ls):
            for nt in ls:
                self.assertEqual(nt._fields, ('current', 'min', 'max'))
                self.assertLessEqual(nt.current, nt.max)
                for name in nt._fields:
                    value = getattr(nt, name)
                    self.assertIsInstance(value, (int, long, float))
                    self.assertGreaterEqual(value, 0)

        ls = psutil.cpu_freq(percpu=True)
        if TRAVIS and not ls:
            return

        assert ls, ls
        check_ls([psutil.cpu_freq(percpu=False)])

        if LINUX:
            self.assertEqual(len(ls), psutil.cpu_count())

    def test_os_constants(self):
        names = ["POSIX", "WINDOWS", "LINUX", "OSX", "FREEBSD", "OPENBSD",
                 "NETBSD", "BSD", "SUNOS"]
        for name in names:
            self.assertIsInstance(getattr(psutil, name), bool, msg=name)

        if os.name == 'posix':
            assert psutil.POSIX
            assert not psutil.WINDOWS
            names.remove("POSIX")
            if "linux" in sys.platform.lower():
                assert psutil.LINUX
                names.remove("LINUX")
            elif "bsd" in sys.platform.lower():
                assert psutil.BSD
                self.assertEqual([psutil.FREEBSD, psutil.OPENBSD,
                                  psutil.NETBSD].count(True), 1)
                names.remove("BSD")
                names.remove("FREEBSD")
                names.remove("OPENBSD")
                names.remove("NETBSD")
            elif "sunos" in sys.platform.lower() or \
                    "solaris" in sys.platform.lower():
                assert psutil.SUNOS
                names.remove("SUNOS")
            elif "darwin" in sys.platform.lower():
                assert psutil.OSX
                names.remove("OSX")
        else:
            assert psutil.WINDOWS
            assert not psutil.POSIX
            names.remove("WINDOWS")

        # assert all other constants are set to False
        for name in names:
            self.assertIs(getattr(psutil, name), False, msg=name)

    @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
    def test_sensors_temperatures(self):
        temps = psutil.sensors_temperatures()
        for name, entries in temps.items():
            self.assertIsInstance(name, str)
            for entry in entries:
                self.assertIsInstance(entry.label, str)
                if entry.current is not None:
                    self.assertGreaterEqual(entry.current, 0)
                if entry.high is not None:
                    self.assertGreaterEqual(entry.high, 0)
                if entry.critical is not None:
                    self.assertGreaterEqual(entry.critical, 0)

    @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
    def test_sensors_temperatures_fahreneit(self):
        d = {'coretemp': [('label', 50.0, 60.0, 70.0)]}
        with mock.patch("psutil._psplatform.sensors_temperatures",
                        return_value=d) as m:
            temps = psutil.sensors_temperatures(
                fahrenheit=True)['coretemp'][0]
            assert m.called
            self.assertEqual(temps.current, 122.0)
            self.assertEqual(temps.high, 140.0)
            self.assertEqual(temps.critical, 158.0)

    @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
    @unittest.skipIf(not HAS_BATTERY, "no battery")
    def test_sensors_battery(self):
        ret = psutil.sensors_battery()
        self.assertGreaterEqual(ret.percent, 0)
        self.assertLessEqual(ret.percent, 100)
        if ret.secsleft not in (psutil.POWER_TIME_UNKNOWN,
                                psutil.POWER_TIME_UNLIMITED):
            self.assertGreaterEqual(ret.secsleft, 0)
        else:
            if ret.secsleft == psutil.POWER_TIME_UNLIMITED:
                self.assertTrue(ret.power_plugged)
        self.assertIsInstance(ret.power_plugged, bool)

    @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
    def test_sensors_fans(self):
        fans = psutil.sensors_fans()
        for name, entries in fans.items():
            self.assertIsInstance(name, str)
            for entry in entries:
                self.assertIsInstance(entry.label, str)
                self.assertIsInstance(entry.current, (int, long))
                self.assertGreaterEqual(entry.current, 0)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_posix.py000064400000037767150466730550010520 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""POSIX specific tests."""

import datetime
import errno
import os
import re
import subprocess
import sys
import time

import psutil
from psutil import AIX
from psutil import BSD
from psutil import LINUX
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil._compat import callable
from psutil._compat import PY3
from psutil.tests import APPVEYOR
from psutil.tests import get_kernel_version
from psutil.tests import get_test_subprocess
from psutil.tests import mock
from psutil.tests import PYTHON_EXE
from psutil.tests import reap_children
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import sh
from psutil.tests import skip_on_access_denied
from psutil.tests import TRAVIS
from psutil.tests import unittest
from psutil.tests import wait_for_pid
from psutil.tests import which


def ps(cmd):
    """Expects a ps command with a -o argument and parse the result
    returning only the value of interest.
    """
    if not LINUX:
        cmd = cmd.replace(" --no-headers ", " ")
    if SUNOS:
        cmd = cmd.replace("-o start", "-o stime")
    if AIX:
        cmd = cmd.replace("-o rss", "-o rssize")
    output = sh(cmd)
    if not LINUX:
        output = output.split('\n')[1].strip()
    try:
        return int(output)
    except ValueError:
        return output

# ps "-o" field names differ wildly between platforms.
# "comm" means "only executable name" but is not available on BSD platforms.
# "args" means "command with all its arguments", and is also not available
# on BSD platforms.
# "command" is like "args" on most platforms, but like "comm" on AIX,
# and not available on SUNOS.
# so for the executable name we can use "comm" on Solaris and split "command"
# on other platforms.
# to get the cmdline (with args) we have to use "args" on AIX and
# Solaris, and can use "command" on all others.


def ps_name(pid):
    field = "command"
    if SUNOS:
        field = "comm"
    return ps("ps --no-headers -o %s -p %s" % (field, pid)).split(' ')[0]


def ps_args(pid):
    field = "command"
    if AIX or SUNOS:
        field = "args"
    return ps("ps --no-headers -o %s -p %s" % (field, pid))


@unittest.skipIf(not POSIX, "POSIX only")
class TestProcess(unittest.TestCase):
    """Compare psutil results against 'ps' command line utility (mainly)."""

    @classmethod
    def setUpClass(cls):
        cls.pid = get_test_subprocess([PYTHON_EXE, "-E", "-O"],
                                      stdin=subprocess.PIPE).pid
        wait_for_pid(cls.pid)

    @classmethod
    def tearDownClass(cls):
        reap_children()

    def test_ppid(self):
        ppid_ps = ps("ps --no-headers -o ppid -p %s" % self.pid)
        ppid_psutil = psutil.Process(self.pid).ppid()
        self.assertEqual(ppid_ps, ppid_psutil)

    def test_uid(self):
        uid_ps = ps("ps --no-headers -o uid -p %s" % self.pid)
        uid_psutil = psutil.Process(self.pid).uids().real
        self.assertEqual(uid_ps, uid_psutil)

    def test_gid(self):
        gid_ps = ps("ps --no-headers -o rgid -p %s" % self.pid)
        gid_psutil = psutil.Process(self.pid).gids().real
        self.assertEqual(gid_ps, gid_psutil)

    def test_username(self):
        username_ps = ps("ps --no-headers -o user -p %s" % self.pid)
        username_psutil = psutil.Process(self.pid).username()
        self.assertEqual(username_ps, username_psutil)

    def test_username_no_resolution(self):
        # Emulate a case where the system can't resolve the uid to
        # a username in which case psutil is supposed to return
        # the stringified uid.
        p = psutil.Process()
        with mock.patch("psutil.pwd.getpwuid", side_effect=KeyError) as fun:
            self.assertEqual(p.username(), str(p.uids().real))
            assert fun.called

    @skip_on_access_denied()
    @retry_before_failing()
    def test_rss_memory(self):
        # give python interpreter some time to properly initialize
        # so that the results are the same
        time.sleep(0.1)
        rss_ps = ps("ps --no-headers -o rss -p %s" % self.pid)
        rss_psutil = psutil.Process(self.pid).memory_info()[0] / 1024
        self.assertEqual(rss_ps, rss_psutil)

    @skip_on_access_denied()
    @retry_before_failing()
    def test_vsz_memory(self):
        # give python interpreter some time to properly initialize
        # so that the results are the same
        time.sleep(0.1)
        vsz_ps = ps("ps --no-headers -o vsz -p %s" % self.pid)
        vsz_psutil = psutil.Process(self.pid).memory_info()[1] / 1024
        self.assertEqual(vsz_ps, vsz_psutil)

    def test_name(self):
        name_ps = ps_name(self.pid)
        # remove path if there is any, from the command
        name_ps = os.path.basename(name_ps).lower()
        name_psutil = psutil.Process(self.pid).name().lower()
        # ...because of how we calculate PYTHON_EXE; on OSX this may
        # be "pythonX.Y".
        name_ps = re.sub(r"\d.\d", "", name_ps)
        name_psutil = re.sub(r"\d.\d", "", name_psutil)
        self.assertEqual(name_ps, name_psutil)

    def test_name_long(self):
        # On UNIX the kernel truncates the name to the first 15
        # characters. In such a case psutil tries to determine the
        # full name from the cmdline.
        name = "long-program-name"
        cmdline = ["long-program-name-extended", "foo", "bar"]
        with mock.patch("psutil._psplatform.Process.name",
                        return_value=name):
            with mock.patch("psutil._psplatform.Process.cmdline",
                            return_value=cmdline):
                p = psutil.Process()
                self.assertEqual(p.name(), "long-program-name-extended")

    def test_name_long_cmdline_ad_exc(self):
        # Same as above but emulates a case where cmdline() raises
        # AccessDenied in which case psutil is supposed to return
        # the truncated name instead of crashing.
        name = "long-program-name"
        with mock.patch("psutil._psplatform.Process.name",
                        return_value=name):
            with mock.patch("psutil._psplatform.Process.cmdline",
                            side_effect=psutil.AccessDenied(0, "")):
                p = psutil.Process()
                self.assertEqual(p.name(), "long-program-name")

    def test_name_long_cmdline_nsp_exc(self):
        # Same as above but emulates a case where cmdline() raises NSP
        # which is supposed to propagate.
        name = "long-program-name"
        with mock.patch("psutil._psplatform.Process.name",
                        return_value=name):
            with mock.patch("psutil._psplatform.Process.cmdline",
                            side_effect=psutil.NoSuchProcess(0, "")):
                p = psutil.Process()
                self.assertRaises(psutil.NoSuchProcess, p.name)

    @unittest.skipIf(OSX or BSD, 'ps -o start not available')
    def test_create_time(self):
        time_ps = ps("ps --no-headers -o start -p %s" % self.pid).split(' ')[0]
        time_psutil = psutil.Process(self.pid).create_time()
        time_psutil_tstamp = datetime.datetime.fromtimestamp(
            time_psutil).strftime("%H:%M:%S")
        # sometimes ps shows the time rounded up instead of down, so we check
        # for both possible values
        round_time_psutil = round(time_psutil)
        round_time_psutil_tstamp = datetime.datetime.fromtimestamp(
            round_time_psutil).strftime("%H:%M:%S")
        self.assertIn(time_ps, [time_psutil_tstamp, round_time_psutil_tstamp])

    def test_exe(self):
        ps_pathname = ps_name(self.pid)
        psutil_pathname = psutil.Process(self.pid).exe()
        try:
            self.assertEqual(ps_pathname, psutil_pathname)
        except AssertionError:
            # certain platforms such as BSD are more accurate returning:
            # "/usr/local/bin/python2.7"
            # ...instead of:
            # "/usr/local/bin/python"
            # We do not want to consider this difference in accuracy
            # an error.
            adjusted_ps_pathname = ps_pathname[:len(ps_pathname)]
            self.assertEqual(ps_pathname, adjusted_ps_pathname)

    def test_cmdline(self):
        ps_cmdline = ps_args(self.pid)
        psutil_cmdline = " ".join(psutil.Process(self.pid).cmdline())
        self.assertEqual(ps_cmdline, psutil_cmdline)

    # On SUNOS "ps" reads niceness /proc/pid/psinfo which returns an
    # incorrect value (20); the real deal is getpriority(2) which
    # returns 0; psutil relies on it, see:
    # https://github.com/giampaolo/psutil/issues/1082
    # AIX has the same issue
    @unittest.skipIf(SUNOS, "not reliable on SUNOS")
    @unittest.skipIf(AIX, "not reliable on AIX")
    def test_nice(self):
        ps_nice = ps("ps --no-headers -o nice -p %s" % self.pid)
        psutil_nice = psutil.Process().nice()
        self.assertEqual(ps_nice, psutil_nice)

    def test_num_fds(self):
        # Note: this fails from time to time; I'm keen on thinking
        # it doesn't mean something is broken
        def call(p, attr):
            args = ()
            attr = getattr(p, name, None)
            if attr is not None and callable(attr):
                if name == 'rlimit':
                    args = (psutil.RLIMIT_NOFILE,)
                attr(*args)
            else:
                attr

        p = psutil.Process(os.getpid())
        failures = []
        ignored_names = ['terminate', 'kill', 'suspend', 'resume', 'nice',
                         'send_signal', 'wait', 'children', 'as_dict',
                         'memory_info_ex']
        if LINUX and get_kernel_version() < (2, 6, 36):
            ignored_names.append('rlimit')
        if LINUX and get_kernel_version() < (2, 6, 23):
            ignored_names.append('num_ctx_switches')
        for name in dir(psutil.Process):
            if (name.startswith('_') or name in ignored_names):
                continue
            else:
                try:
                    num1 = p.num_fds()
                    for x in range(2):
                        call(p, name)
                    num2 = p.num_fds()
                except psutil.AccessDenied:
                    pass
                else:
                    if abs(num2 - num1) > 1:
                        fail = "failure while processing Process.%s method " \
                               "(before=%s, after=%s)" % (name, num1, num2)
                        failures.append(fail)
        if failures:
            self.fail('\n' + '\n'.join(failures))


@unittest.skipIf(not POSIX, "POSIX only")
class TestSystemAPIs(unittest.TestCase):
    """Test some system APIs."""

    @retry_before_failing()
    def test_pids(self):
        # Note: this test might fail if the OS is starting/killing
        # other processes in the meantime
        if SUNOS or AIX:
            cmd = ["ps", "-A", "-o", "pid"]
        else:
            cmd = ["ps", "ax", "-o", "pid"]
        p = get_test_subprocess(cmd, stdout=subprocess.PIPE)
        output = p.communicate()[0].strip()
        assert p.poll() == 0
        if PY3:
            output = str(output, sys.stdout.encoding)
        pids_ps = []
        for line in output.split('\n')[1:]:
            if line:
                pid = int(line.split()[0].strip())
                pids_ps.append(pid)
        # remove ps subprocess pid which is supposed to be dead in meantime
        pids_ps.remove(p.pid)
        pids_psutil = psutil.pids()
        pids_ps.sort()
        pids_psutil.sort()

        # on OSX and OPENBSD ps doesn't show pid 0
        if OSX or OPENBSD and 0 not in pids_ps:
            pids_ps.insert(0, 0)
        self.assertEqual(pids_ps, pids_psutil)

    # for some reason ifconfig -a does not report all interfaces
    # returned by psutil
    @unittest.skipIf(SUNOS, "unreliable on SUNOS")
    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    @unittest.skipIf(not which('ifconfig'), "no ifconfig cmd")
    def test_nic_names(self):
        output = sh("ifconfig -a")
        for nic in psutil.net_io_counters(pernic=True).keys():
            for line in output.split():
                if line.startswith(nic):
                    break
            else:
                self.fail(
                    "couldn't find %s nic in 'ifconfig -a' output\n%s" % (
                        nic, output))

    # can't find users on APPVEYOR or TRAVIS
    @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(),
                     "unreliable on APPVEYOR or TRAVIS")
    @retry_before_failing()
    def test_users(self):
        out = sh("who")
        lines = out.split('\n')
        users = [x.split()[0] for x in lines]
        terminals = [x.split()[1] for x in lines]
        self.assertEqual(len(users), len(psutil.users()))
        for u in psutil.users():
            self.assertIn(u.name, users)
            self.assertIn(u.terminal, terminals)

    def test_pid_exists_let_raise(self):
        # According to "man 2 kill" possible error values for kill
        # are (EINVAL, EPERM, ESRCH). Test that any other errno
        # results in an exception.
        with mock.patch("psutil._psposix.os.kill",
                        side_effect=OSError(errno.EBADF, "")) as m:
            self.assertRaises(OSError, psutil._psposix.pid_exists, os.getpid())
            assert m.called

    def test_os_waitpid_let_raise(self):
        # os.waitpid() is supposed to catch EINTR and ECHILD only.
        # Test that any other errno results in an exception.
        with mock.patch("psutil._psposix.os.waitpid",
                        side_effect=OSError(errno.EBADF, "")) as m:
            self.assertRaises(OSError, psutil._psposix.wait_pid, os.getpid())
            assert m.called

    def test_os_waitpid_eintr(self):
        # os.waitpid() is supposed to "retry" on EINTR.
        with mock.patch("psutil._psposix.os.waitpid",
                        side_effect=OSError(errno.EINTR, "")) as m:
            self.assertRaises(
                psutil._psposix.TimeoutExpired,
                psutil._psposix.wait_pid, os.getpid(), timeout=0.01)
            assert m.called

    def test_os_waitpid_bad_ret_status(self):
        # Simulate os.waitpid() returning a bad status.
        with mock.patch("psutil._psposix.os.waitpid",
                        return_value=(1, -1)) as m:
            self.assertRaises(ValueError,
                              psutil._psposix.wait_pid, os.getpid())
            assert m.called

    # AIX can return '-' in df output instead of numbers, e.g. for /proc
    @unittest.skipIf(AIX, "unreliable on AIX")
    def test_disk_usage(self):
        def df(device):
            out = sh("df -k %s" % device).strip()
            line = out.split('\n')[1]
            fields = line.split()
            total = int(fields[1]) * 1024
            used = int(fields[2]) * 1024
            free = int(fields[3]) * 1024
            percent = float(fields[4].replace('%', ''))
            return (total, used, free, percent)

        tolerance = 4 * 1024 * 1024  # 4MB
        for part in psutil.disk_partitions(all=False):
            usage = psutil.disk_usage(part.mountpoint)
            try:
                total, used, free, percent = df(part.device)
            except RuntimeError as err:
                # see:
                # https://travis-ci.org/giampaolo/psutil/jobs/138338464
                # https://travis-ci.org/giampaolo/psutil/jobs/138343361
                err = str(err).lower()
                if "no such file or directory" in err or \
                        "raw devices not supported" in err or \
                        "permission denied" in err:
                    continue
                else:
                    raise
            else:
                self.assertAlmostEqual(usage.total, total, delta=tolerance)
                self.assertAlmostEqual(usage.used, used, delta=tolerance)
                self.assertAlmostEqual(usage.free, free, delta=tolerance)
                self.assertAlmostEqual(usage.percent, percent, delta=1)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_bsd.py000064400000042543150466730550010112 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# TODO: (FreeBSD) add test for comparing connections with 'sockstat' cmd.


"""Tests specific to all BSD platforms."""


import datetime
import os
import re
import time

import psutil
from psutil import BSD
from psutil import FREEBSD
from psutil import NETBSD
from psutil import OPENBSD
from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import MEMORY_TOLERANCE
from psutil.tests import reap_children
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import sh
from psutil.tests import unittest
from psutil.tests import which


if BSD:
    PAGESIZE = os.sysconf("SC_PAGE_SIZE")
    if os.getuid() == 0:  # muse requires root privileges
        MUSE_AVAILABLE = which('muse')
    else:
        MUSE_AVAILABLE = False
else:
    MUSE_AVAILABLE = False


def sysctl(cmdline):
    """Expects a sysctl command with an argument and parse the result
    returning only the value of interest.
    """
    result = sh("sysctl " + cmdline)
    if FREEBSD:
        result = result[result.find(": ") + 2:]
    elif OPENBSD or NETBSD:
        result = result[result.find("=") + 1:]
    try:
        return int(result)
    except ValueError:
        return result


def muse(field):
    """Thin wrapper around 'muse' cmdline utility."""
    out = sh('muse')
    for line in out.split('\n'):
        if line.startswith(field):
            break
    else:
        raise ValueError("line not found")
    return int(line.split()[1])


# =====================================================================
# --- All BSD*
# =====================================================================


@unittest.skipIf(not BSD, "BSD only")
class BSDSpecificTestCase(unittest.TestCase):
    """Generic tests common to all BSD variants."""

    @classmethod
    def setUpClass(cls):
        cls.pid = get_test_subprocess().pid

    @classmethod
    def tearDownClass(cls):
        reap_children()

    @unittest.skipIf(NETBSD, "-o lstart doesn't work on NETBSD")
    def test_process_create_time(self):
        output = sh("ps -o lstart -p %s" % self.pid)
        start_ps = output.replace('STARTED', '').strip()
        start_psutil = psutil.Process(self.pid).create_time()
        start_psutil = time.strftime("%a %b %e %H:%M:%S %Y",
                                     time.localtime(start_psutil))
        self.assertEqual(start_ps, start_psutil)

    def test_disks(self):
        # test psutil.disk_usage() and psutil.disk_partitions()
        # against "df -a"
        def df(path):
            out = sh('df -k "%s"' % path).strip()
            lines = out.split('\n')
            lines.pop(0)
            line = lines.pop(0)
            dev, total, used, free = line.split()[:4]
            if dev == 'none':
                dev = ''
            total = int(total) * 1024
            used = int(used) * 1024
            free = int(free) * 1024
            return dev, total, used, free

        for part in psutil.disk_partitions(all=False):
            usage = psutil.disk_usage(part.mountpoint)
            dev, total, used, free = df(part.mountpoint)
            self.assertEqual(part.device, dev)
            self.assertEqual(usage.total, total)
            # 10 MB tollerance
            if abs(usage.free - free) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.free, free))
            if abs(usage.used - used) > 10 * 1024 * 1024:
                self.fail("psutil=%s, df=%s" % (usage.used, used))

    @unittest.skipIf(not which('sysctl'), "sysctl cmd not available")
    def test_cpu_count_logical(self):
        syst = sysctl("hw.ncpu")
        self.assertEqual(psutil.cpu_count(logical=True), syst)

    @unittest.skipIf(not which('sysctl'), "sysctl cmd not available")
    def test_virtual_memory_total(self):
        num = sysctl('hw.physmem')
        self.assertEqual(num, psutil.virtual_memory().total)

    def test_net_if_stats(self):
        for name, stats in psutil.net_if_stats().items():
            try:
                out = sh("ifconfig %s" % name)
            except RuntimeError:
                pass
            else:
                self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
                if "mtu" in out:
                    self.assertEqual(stats.mtu,
                                     int(re.findall(r'mtu (\d+)', out)[0]))


# =====================================================================
# --- FreeBSD
# =====================================================================


@unittest.skipIf(not FREEBSD, "FREEBSD only")
class FreeBSDSpecificTestCase(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        cls.pid = get_test_subprocess().pid

    @classmethod
    def tearDownClass(cls):
        reap_children()

    @retry_before_failing()
    def test_proc_memory_maps(self):
        out = sh('procstat -v %s' % self.pid)
        maps = psutil.Process(self.pid).memory_maps(grouped=False)
        lines = out.split('\n')[1:]
        while lines:
            line = lines.pop()
            fields = line.split()
            _, start, stop, perms, res = fields[:5]
            map = maps.pop()
            self.assertEqual("%s-%s" % (start, stop), map.addr)
            self.assertEqual(int(res), map.rss)
            if not map.path.startswith('['):
                self.assertEqual(fields[10], map.path)

    def test_proc_exe(self):
        out = sh('procstat -b %s' % self.pid)
        self.assertEqual(psutil.Process(self.pid).exe(),
                         out.split('\n')[1].split()[-1])

    def test_proc_cmdline(self):
        out = sh('procstat -c %s' % self.pid)
        self.assertEqual(' '.join(psutil.Process(self.pid).cmdline()),
                         ' '.join(out.split('\n')[1].split()[2:]))

    def test_proc_uids_gids(self):
        out = sh('procstat -s %s' % self.pid)
        euid, ruid, suid, egid, rgid, sgid = out.split('\n')[1].split()[2:8]
        p = psutil.Process(self.pid)
        uids = p.uids()
        gids = p.gids()
        self.assertEqual(uids.real, int(ruid))
        self.assertEqual(uids.effective, int(euid))
        self.assertEqual(uids.saved, int(suid))
        self.assertEqual(gids.real, int(rgid))
        self.assertEqual(gids.effective, int(egid))
        self.assertEqual(gids.saved, int(sgid))

    @retry_before_failing()
    def test_proc_ctx_switches(self):
        tested = []
        out = sh('procstat -r %s' % self.pid)
        p = psutil.Process(self.pid)
        for line in out.split('\n'):
            line = line.lower().strip()
            if ' voluntary context' in line:
                pstat_value = int(line.split()[-1])
                psutil_value = p.num_ctx_switches().voluntary
                self.assertEqual(pstat_value, psutil_value)
                tested.append(None)
            elif ' involuntary context' in line:
                pstat_value = int(line.split()[-1])
                psutil_value = p.num_ctx_switches().involuntary
                self.assertEqual(pstat_value, psutil_value)
                tested.append(None)
        if len(tested) != 2:
            raise RuntimeError("couldn't find lines match in procstat out")

    @retry_before_failing()
    def test_proc_cpu_times(self):
        tested = []
        out = sh('procstat -r %s' % self.pid)
        p = psutil.Process(self.pid)
        for line in out.split('\n'):
            line = line.lower().strip()
            if 'user time' in line:
                pstat_value = float('0.' + line.split()[-1].split('.')[-1])
                psutil_value = p.cpu_times().user
                self.assertEqual(pstat_value, psutil_value)
                tested.append(None)
            elif 'system time' in line:
                pstat_value = float('0.' + line.split()[-1].split('.')[-1])
                psutil_value = p.cpu_times().system
                self.assertEqual(pstat_value, psutil_value)
                tested.append(None)
        if len(tested) != 2:
            raise RuntimeError("couldn't find lines match in procstat out")

    # --- virtual_memory(); tests against sysctl

    @retry_before_failing()
    def test_vmem_active(self):
        syst = sysctl("vm.stats.vm.v_active_count") * PAGESIZE
        self.assertAlmostEqual(psutil.virtual_memory().active, syst,
                               delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_inactive(self):
        syst = sysctl("vm.stats.vm.v_inactive_count") * PAGESIZE
        self.assertAlmostEqual(psutil.virtual_memory().inactive, syst,
                               delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_wired(self):
        syst = sysctl("vm.stats.vm.v_wire_count") * PAGESIZE
        self.assertAlmostEqual(psutil.virtual_memory().wired, syst,
                               delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_cached(self):
        syst = sysctl("vm.stats.vm.v_cache_count") * PAGESIZE
        self.assertAlmostEqual(psutil.virtual_memory().cached, syst,
                               delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_free(self):
        syst = sysctl("vm.stats.vm.v_free_count") * PAGESIZE
        self.assertAlmostEqual(psutil.virtual_memory().free, syst,
                               delta=MEMORY_TOLERANCE)

    @retry_before_failing()
    def test_vmem_buffers(self):
        syst = sysctl("vfs.bufspace")
        self.assertAlmostEqual(psutil.virtual_memory().buffers, syst,
                               delta=MEMORY_TOLERANCE)

    # --- virtual_memory(); tests against muse

    @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
    def test_muse_vmem_total(self):
        num = muse('Total')
        self.assertEqual(psutil.virtual_memory().total, num)

    @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
    @retry_before_failing()
    def test_muse_vmem_active(self):
        num = muse('Active')
        self.assertAlmostEqual(psutil.virtual_memory().active, num,
                               delta=MEMORY_TOLERANCE)

    @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
    @retry_before_failing()
    def test_muse_vmem_inactive(self):
        num = muse('Inactive')
        self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
                               delta=MEMORY_TOLERANCE)

    @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
    @retry_before_failing()
    def test_muse_vmem_wired(self):
        num = muse('Wired')
        self.assertAlmostEqual(psutil.virtual_memory().wired, num,
                               delta=MEMORY_TOLERANCE)

    @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
    @retry_before_failing()
    def test_muse_vmem_cached(self):
        num = muse('Cache')
        self.assertAlmostEqual(psutil.virtual_memory().cached, num,
                               delta=MEMORY_TOLERANCE)

    @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
    @retry_before_failing()
    def test_muse_vmem_free(self):
        num = muse('Free')
        self.assertAlmostEqual(psutil.virtual_memory().free, num,
                               delta=MEMORY_TOLERANCE)

    @unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
    @retry_before_failing()
    def test_muse_vmem_buffers(self):
        num = muse('Buffer')
        self.assertAlmostEqual(psutil.virtual_memory().buffers, num,
                               delta=MEMORY_TOLERANCE)

    def test_cpu_stats_ctx_switches(self):
        self.assertAlmostEqual(psutil.cpu_stats().ctx_switches,
                               sysctl('vm.stats.sys.v_swtch'), delta=1000)

    def test_cpu_stats_interrupts(self):
        self.assertAlmostEqual(psutil.cpu_stats().interrupts,
                               sysctl('vm.stats.sys.v_intr'), delta=1000)

    def test_cpu_stats_soft_interrupts(self):
        self.assertAlmostEqual(psutil.cpu_stats().soft_interrupts,
                               sysctl('vm.stats.sys.v_soft'), delta=1000)

    def test_cpu_stats_syscalls(self):
        self.assertAlmostEqual(psutil.cpu_stats().syscalls,
                               sysctl('vm.stats.sys.v_syscall'), delta=1000)

    # def test_cpu_stats_traps(self):
    #    self.assertAlmostEqual(psutil.cpu_stats().traps,
    #                           sysctl('vm.stats.sys.v_trap'), delta=1000)

    # --- others

    def test_boot_time(self):
        s = sysctl('sysctl kern.boottime')
        s = s[s.find(" sec = ") + 7:]
        s = s[:s.find(',')]
        btime = int(s)
        self.assertEqual(btime, psutil.boot_time())

    # --- sensors_battery

    @unittest.skipIf(not HAS_BATTERY, "no battery")
    def test_sensors_battery(self):
        def secs2hours(secs):
            m, s = divmod(secs, 60)
            h, m = divmod(m, 60)
            return "%d:%02d" % (h, m)

        out = sh("acpiconf -i 0")
        fields = dict([(x.split('\t')[0], x.split('\t')[-1])
                       for x in out.split("\n")])
        metrics = psutil.sensors_battery()
        percent = int(fields['Remaining capacity:'].replace('%', ''))
        remaining_time = fields['Remaining time:']
        self.assertEqual(metrics.percent, percent)
        if remaining_time == 'unknown':
            self.assertEqual(metrics.secsleft, psutil.POWER_TIME_UNLIMITED)
        else:
            self.assertEqual(secs2hours(metrics.secsleft), remaining_time)

    @unittest.skipIf(not HAS_BATTERY, "no battery")
    def test_sensors_battery_against_sysctl(self):
        self.assertEqual(psutil.sensors_battery().percent,
                         sysctl("hw.acpi.battery.life"))
        self.assertEqual(psutil.sensors_battery().power_plugged,
                         sysctl("hw.acpi.acline") == 1)
        secsleft = psutil.sensors_battery().secsleft
        if secsleft < 0:
            self.assertEqual(sysctl("hw.acpi.battery.time"), -1)
        else:
            self.assertEqual(secsleft, sysctl("hw.acpi.battery.time") * 60)

    @unittest.skipIf(HAS_BATTERY, "has battery")
    def test_sensors_battery_no_battery(self):
        # If no battery is present one of these calls is supposed
        # to fail, see:
        # https://github.com/giampaolo/psutil/issues/1074
        with self.assertRaises(RuntimeError):
            sysctl("hw.acpi.battery.life")
            sysctl("hw.acpi.battery.time")
            sysctl("hw.acpi.acline")
        self.assertIsNone(psutil.sensors_battery())


# =====================================================================
# --- OpenBSD
# =====================================================================


@unittest.skipIf(not OPENBSD, "OPENBSD only")
class OpenBSDSpecificTestCase(unittest.TestCase):

    def test_boot_time(self):
        s = sysctl('kern.boottime')
        sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y")
        psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time())
        self.assertEqual(sys_bt, psutil_bt)


# =====================================================================
# --- NetBSD
# =====================================================================


@unittest.skipIf(not NETBSD, "NETBSD only")
class NetBSDSpecificTestCase(unittest.TestCase):

    @staticmethod
    def parse_meminfo(look_for):
        with open('/proc/meminfo', 'rb') as f:
            for line in f:
                if line.startswith(look_for):
                    return int(line.split()[1]) * 1024
        raise ValueError("can't find %s" % look_for)

    def test_vmem_total(self):
        self.assertEqual(
            psutil.virtual_memory().total, self.parse_meminfo("MemTotal:"))

    def test_vmem_free(self):
        self.assertAlmostEqual(
            psutil.virtual_memory().free, self.parse_meminfo("MemFree:"),
            delta=MEMORY_TOLERANCE)

    def test_vmem_buffers(self):
        self.assertAlmostEqual(
            psutil.virtual_memory().buffers, self.parse_meminfo("Buffers:"),
            delta=MEMORY_TOLERANCE)

    def test_vmem_shared(self):
        self.assertAlmostEqual(
            psutil.virtual_memory().shared, self.parse_meminfo("MemShared:"),
            delta=MEMORY_TOLERANCE)

    def test_swapmem_total(self):
        self.assertAlmostEqual(
            psutil.swap_memory().total, self.parse_meminfo("SwapTotal:"),
            delta=MEMORY_TOLERANCE)

    def test_swapmem_free(self):
        self.assertAlmostEqual(
            psutil.swap_memory().free, self.parse_meminfo("SwapFree:"),
            delta=MEMORY_TOLERANCE)

    def test_swapmem_used(self):
        smem = psutil.swap_memory()
        self.assertEqual(smem.used, smem.total - smem.free)

    def test_cpu_stats_interrupts(self):
        with open('/proc/stat', 'rb') as f:
            for line in f:
                if line.startswith(b'intr'):
                    interrupts = int(line.split()[1])
                    break
            else:
                raise ValueError("couldn't find line")
        self.assertAlmostEqual(
            psutil.cpu_stats().interrupts, interrupts, delta=1000)

    def test_cpu_stats_ctx_switches(self):
        with open('/proc/stat', 'rb') as f:
            for line in f:
                if line.startswith(b'ctxt'):
                    ctx_switches = int(line.split()[1])
                    break
            else:
                raise ValueError("couldn't find line")
        self.assertAlmostEqual(
            psutil.cpu_stats().ctx_switches, ctx_switches, delta=1000)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_connections.py000064400000050256150466730550011664 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tests for net_connections() and Process.connections() APIs."""

import os
import socket
import textwrap
from contextlib import closing
from socket import AF_INET
from socket import AF_INET6
from socket import SOCK_DGRAM
from socket import SOCK_STREAM

import psutil
from psutil import FREEBSD
from psutil import LINUX
from psutil import NETBSD
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._common import supports_ipv6
from psutil._compat import PY3
from psutil.tests import AF_UNIX
from psutil.tests import bind_socket
from psutil.tests import bind_unix_socket
from psutil.tests import check_connection_ntuple
from psutil.tests import create_sockets
from psutil.tests import get_free_port
from psutil.tests import HAS_CONNECTIONS_UNIX
from psutil.tests import pyrun
from psutil.tests import reap_children
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_rmpath
from psutil.tests import skip_on_access_denied
from psutil.tests import tcp_socketpair
from psutil.tests import TESTFN
from psutil.tests import TRAVIS
from psutil.tests import unittest
from psutil.tests import unix_socket_path
from psutil.tests import unix_socketpair
from psutil.tests import wait_for_file


thisproc = psutil.Process()


class Base(object):

    def setUp(self):
        if not NETBSD:
            # NetBSD opens a UNIX socket to /var/log/run.
            cons = thisproc.connections(kind='all')
            assert not cons, cons

    def tearDown(self):
        safe_rmpath(TESTFN)
        reap_children()
        if not NETBSD:
            # Make sure we closed all resources.
            # NetBSD opens a UNIX socket to /var/log/run.
            cons = thisproc.connections(kind='all')
            assert not cons, cons

    def get_conn_from_sock(self, sock):
        cons = thisproc.connections(kind='all')
        smap = dict([(c.fd, c) for c in cons])
        if NETBSD:
            # NetBSD opens a UNIX socket to /var/log/run
            # so there may be more connections.
            return smap[sock.fileno()]
        else:
            self.assertEqual(len(cons), 1)
            if cons[0].fd != -1:
                self.assertEqual(smap[sock.fileno()].fd, sock.fileno())
            return cons[0]

    def check_socket(self, sock, conn=None):
        """Given a socket, makes sure it matches the one obtained
        via psutil. It assumes this process created one connection
        only (the one supposed to be checked).
        """
        if conn is None:
            conn = self.get_conn_from_sock(sock)
        check_connection_ntuple(conn)

        # fd, family, type
        if conn.fd != -1:
            self.assertEqual(conn.fd, sock.fileno())
        self.assertEqual(conn.family, sock.family)
        # see: http://bugs.python.org/issue30204
        self.assertEqual(
            conn.type, sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE))

        # local address
        laddr = sock.getsockname()
        if not laddr and PY3 and isinstance(laddr, bytes):
            # See: http://bugs.python.org/issue30205
            laddr = laddr.decode()
        if sock.family == AF_INET6:
            laddr = laddr[:2]
        if sock.family == AF_UNIX and OPENBSD:
            # No addresses are set for UNIX sockets on OpenBSD.
            pass
        else:
            self.assertEqual(conn.laddr, laddr)

        # XXX Solaris can't retrieve system-wide UNIX sockets
        if sock.family == AF_UNIX and HAS_CONNECTIONS_UNIX:
            cons = thisproc.connections(kind='all')
            self.compare_procsys_connections(os.getpid(), cons)
        return conn

    def compare_procsys_connections(self, pid, proc_cons, kind='all'):
        """Given a process PID and its list of connections compare
        those against system-wide connections retrieved via
        psutil.net_connections.
        """
        try:
            sys_cons = psutil.net_connections(kind=kind)
        except psutil.AccessDenied:
            # On OSX, system-wide connections are retrieved by iterating
            # over all processes
            if OSX:
                return
            else:
                raise
        # Filter for this proc PID and exlucde PIDs from the tuple.
        sys_cons = [c[:-1] for c in sys_cons if c.pid == pid]
        sys_cons.sort()
        proc_cons.sort()
        self.assertEqual(proc_cons, sys_cons)


# =====================================================================
# --- Test unconnected sockets
# =====================================================================


class TestUnconnectedSockets(Base, unittest.TestCase):
    """Tests sockets which are open but not connected to anything."""

    def test_tcp_v4(self):
        addr = ("127.0.0.1", get_free_port())
        with closing(bind_socket(AF_INET, SOCK_STREAM, addr=addr)) as sock:
            conn = self.check_socket(sock)
            assert not conn.raddr
            self.assertEqual(conn.status, psutil.CONN_LISTEN)

    @unittest.skipIf(not supports_ipv6(), "IPv6 not supported")
    def test_tcp_v6(self):
        addr = ("::1", get_free_port())
        with closing(bind_socket(AF_INET6, SOCK_STREAM, addr=addr)) as sock:
            conn = self.check_socket(sock)
            assert not conn.raddr
            self.assertEqual(conn.status, psutil.CONN_LISTEN)

    def test_udp_v4(self):
        addr = ("127.0.0.1", get_free_port())
        with closing(bind_socket(AF_INET, SOCK_DGRAM, addr=addr)) as sock:
            conn = self.check_socket(sock)
            assert not conn.raddr
            self.assertEqual(conn.status, psutil.CONN_NONE)

    @unittest.skipIf(not supports_ipv6(), "IPv6 not supported")
    def test_udp_v6(self):
        addr = ("::1", get_free_port())
        with closing(bind_socket(AF_INET6, SOCK_DGRAM, addr=addr)) as sock:
            conn = self.check_socket(sock)
            assert not conn.raddr
            self.assertEqual(conn.status, psutil.CONN_NONE)

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_unix_tcp(self):
        with unix_socket_path() as name:
            with closing(bind_unix_socket(name, type=SOCK_STREAM)) as sock:
                conn = self.check_socket(sock)
                assert not conn.raddr
                self.assertEqual(conn.status, psutil.CONN_NONE)

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_unix_udp(self):
        with unix_socket_path() as name:
            with closing(bind_unix_socket(name, type=SOCK_STREAM)) as sock:
                conn = self.check_socket(sock)
                assert not conn.raddr
                self.assertEqual(conn.status, psutil.CONN_NONE)


# =====================================================================
# --- Test connected sockets
# =====================================================================


class TestConnectedSocketPairs(Base, unittest.TestCase):
    """Test socket pairs which are are actually connected to
    each other.
    """

    # On SunOS, even after we close() it, the server socket stays around
    # in TIME_WAIT state.
    @unittest.skipIf(SUNOS, "unreliable on SUONS")
    def test_tcp(self):
        addr = ("127.0.0.1", get_free_port())
        assert not thisproc.connections(kind='tcp4')
        server, client = tcp_socketpair(AF_INET, addr=addr)
        try:
            cons = thisproc.connections(kind='tcp4')
            self.assertEqual(len(cons), 2)
            self.assertEqual(cons[0].status, psutil.CONN_ESTABLISHED)
            self.assertEqual(cons[1].status, psutil.CONN_ESTABLISHED)
            # May not be fast enough to change state so it stays
            # commenteed.
            # client.close()
            # cons = thisproc.connections(kind='all')
            # self.assertEqual(len(cons), 1)
            # self.assertEqual(cons[0].status, psutil.CONN_CLOSE_WAIT)
        finally:
            server.close()
            client.close()

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_unix(self):
        with unix_socket_path() as name:
            server, client = unix_socketpair(name)
            try:
                cons = thisproc.connections(kind='unix')
                assert not (cons[0].laddr and cons[0].raddr)
                assert not (cons[1].laddr and cons[1].raddr)
                if NETBSD:
                    # On NetBSD creating a UNIX socket will cause
                    # a UNIX connection to  /var/run/log.
                    cons = [c for c in cons if c.raddr != '/var/run/log']
                self.assertEqual(len(cons), 2)
                if LINUX or FREEBSD or SUNOS:
                    # remote path is never set
                    self.assertEqual(cons[0].raddr, "")
                    self.assertEqual(cons[1].raddr, "")
                    # one local address should though
                    self.assertEqual(name, cons[0].laddr or cons[1].laddr)
                elif OPENBSD:
                    # No addresses whatsoever here.
                    for addr in (cons[0].laddr, cons[0].raddr,
                                 cons[1].laddr, cons[1].raddr):
                        self.assertEqual(addr, "")
                else:
                    # On other systems either the laddr or raddr
                    # of both peers are set.
                    self.assertEqual(cons[0].laddr or cons[1].laddr, name)
                    self.assertEqual(cons[0].raddr or cons[1].raddr, name)
            finally:
                server.close()
                client.close()

    @skip_on_access_denied(only_if=OSX)
    def test_combos(self):
        def check_conn(proc, conn, family, type, laddr, raddr, status, kinds):
            all_kinds = ("all", "inet", "inet4", "inet6", "tcp", "tcp4",
                         "tcp6", "udp", "udp4", "udp6")
            check_connection_ntuple(conn)
            self.assertEqual(conn.family, family)
            self.assertEqual(conn.type, type)
            self.assertEqual(conn.laddr, laddr)
            self.assertEqual(conn.raddr, raddr)
            self.assertEqual(conn.status, status)
            for kind in all_kinds:
                cons = proc.connections(kind=kind)
                if kind in kinds:
                    assert cons
                else:
                    assert not cons, cons
            # compare against system-wide connections
            # XXX Solaris can't retrieve system-wide UNIX
            # sockets.
            if HAS_CONNECTIONS_UNIX:
                self.compare_procsys_connections(proc.pid, [conn])

        tcp_template = textwrap.dedent("""
            import socket, time
            s = socket.socket($family, socket.SOCK_STREAM)
            s.bind(('$addr', 0))
            s.listen(1)
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        """)

        udp_template = textwrap.dedent("""
            import socket, time
            s = socket.socket($family, socket.SOCK_DGRAM)
            s.bind(('$addr', 0))
            with open('$testfn', 'w') as f:
                f.write(str(s.getsockname()[:2]))
            time.sleep(60)
        """)

        from string import Template
        testfile = os.path.basename(TESTFN)
        tcp4_template = Template(tcp_template).substitute(
            family=int(AF_INET), addr="127.0.0.1", testfn=testfile)
        udp4_template = Template(udp_template).substitute(
            family=int(AF_INET), addr="127.0.0.1", testfn=testfile)
        tcp6_template = Template(tcp_template).substitute(
            family=int(AF_INET6), addr="::1", testfn=testfile)
        udp6_template = Template(udp_template).substitute(
            family=int(AF_INET6), addr="::1", testfn=testfile)

        # launch various subprocess instantiating a socket of various
        # families and types to enrich psutil results
        tcp4_proc = pyrun(tcp4_template)
        tcp4_addr = eval(wait_for_file(testfile))
        udp4_proc = pyrun(udp4_template)
        udp4_addr = eval(wait_for_file(testfile))
        if supports_ipv6():
            tcp6_proc = pyrun(tcp6_template)
            tcp6_addr = eval(wait_for_file(testfile))
            udp6_proc = pyrun(udp6_template)
            udp6_addr = eval(wait_for_file(testfile))
        else:
            tcp6_proc = None
            udp6_proc = None
            tcp6_addr = None
            udp6_addr = None

        for p in thisproc.children():
            cons = p.connections()
            self.assertEqual(len(cons), 1)
            for conn in cons:
                # TCP v4
                if p.pid == tcp4_proc.pid:
                    check_conn(p, conn, AF_INET, SOCK_STREAM, tcp4_addr, (),
                               psutil.CONN_LISTEN,
                               ("all", "inet", "inet4", "tcp", "tcp4"))
                # UDP v4
                elif p.pid == udp4_proc.pid:
                    check_conn(p, conn, AF_INET, SOCK_DGRAM, udp4_addr, (),
                               psutil.CONN_NONE,
                               ("all", "inet", "inet4", "udp", "udp4"))
                # TCP v6
                elif p.pid == getattr(tcp6_proc, "pid", None):
                    check_conn(p, conn, AF_INET6, SOCK_STREAM, tcp6_addr, (),
                               psutil.CONN_LISTEN,
                               ("all", "inet", "inet6", "tcp", "tcp6"))
                # UDP v6
                elif p.pid == getattr(udp6_proc, "pid", None):
                    check_conn(p, conn, AF_INET6, SOCK_DGRAM, udp6_addr, (),
                               psutil.CONN_NONE,
                               ("all", "inet", "inet6", "udp", "udp6"))

        # err
        self.assertRaises(ValueError, p.connections, kind='???')

    def test_multi_sockets_filtering(self):
        with create_sockets() as socks:
            cons = thisproc.connections(kind='all')
            self.assertEqual(len(cons), len(socks))
            # tcp
            cons = thisproc.connections(kind='tcp')
            self.assertEqual(len(cons), 2 if supports_ipv6() else 1)
            for conn in cons:
                self.assertIn(conn.family, (AF_INET, AF_INET6))
                self.assertEqual(conn.type, SOCK_STREAM)
            # tcp4
            cons = thisproc.connections(kind='tcp4')
            self.assertEqual(len(cons), 1)
            self.assertEqual(cons[0].family, AF_INET)
            self.assertEqual(cons[0].type, SOCK_STREAM)
            # tcp6
            if supports_ipv6():
                cons = thisproc.connections(kind='tcp6')
                self.assertEqual(len(cons), 1)
                self.assertEqual(cons[0].family, AF_INET6)
                self.assertEqual(cons[0].type, SOCK_STREAM)
            # udp
            cons = thisproc.connections(kind='udp')
            self.assertEqual(len(cons), 2 if supports_ipv6() else 1)
            for conn in cons:
                self.assertIn(conn.family, (AF_INET, AF_INET6))
                self.assertEqual(conn.type, SOCK_DGRAM)
            # udp4
            cons = thisproc.connections(kind='udp4')
            self.assertEqual(len(cons), 1)
            self.assertEqual(cons[0].family, AF_INET)
            self.assertEqual(cons[0].type, SOCK_DGRAM)
            # udp6
            if supports_ipv6():
                cons = thisproc.connections(kind='udp6')
                self.assertEqual(len(cons), 1)
                self.assertEqual(cons[0].family, AF_INET6)
                self.assertEqual(cons[0].type, SOCK_DGRAM)
            # inet
            cons = thisproc.connections(kind='inet')
            self.assertEqual(len(cons), 4 if supports_ipv6() else 2)
            for conn in cons:
                self.assertIn(conn.family, (AF_INET, AF_INET6))
                self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
            # inet6
            if supports_ipv6():
                cons = thisproc.connections(kind='inet6')
                self.assertEqual(len(cons), 2)
                for conn in cons:
                    self.assertEqual(conn.family, AF_INET6)
                    self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
            # unix
            if HAS_CONNECTIONS_UNIX:
                cons = thisproc.connections(kind='unix')
                self.assertEqual(len(cons), 3)
                for conn in cons:
                    self.assertEqual(conn.family, AF_UNIX)
                    self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))


# =====================================================================
# --- Miscellaneous tests
# =====================================================================


class TestSystemWideConnections(Base, unittest.TestCase):
    """Tests for net_connections()."""

    @skip_on_access_denied()
    def test_it(self):
        def check(cons, families, types_):
            AF_UNIX = getattr(socket, 'AF_UNIX', object())
            for conn in cons:
                self.assertIn(conn.family, families, msg=conn)
                if conn.family != AF_UNIX:
                    self.assertIn(conn.type, types_, msg=conn)
                check_connection_ntuple(conn)

        with create_sockets():
            from psutil._common import conn_tmap
            for kind, groups in conn_tmap.items():
                # XXX: SunOS does not retrieve UNIX sockets.
                if kind == 'unix' and not HAS_CONNECTIONS_UNIX:
                    continue
                families, types_ = groups
                cons = psutil.net_connections(kind)
                self.assertEqual(len(cons), len(set(cons)))
                check(cons, families, types_)

            self.assertRaises(ValueError, psutil.net_connections, kind='???')

    @skip_on_access_denied()
    def test_multi_socks(self):
        with create_sockets() as socks:
            cons = [x for x in psutil.net_connections(kind='all')
                    if x.pid == os.getpid()]
            self.assertEqual(len(cons), len(socks))

    @skip_on_access_denied()
    # See: https://travis-ci.org/giampaolo/psutil/jobs/237566297
    @unittest.skipIf(OSX and TRAVIS, "unreliable on OSX + TRAVIS")
    def test_multi_sockets_procs(self):
        # Creates multiple sub processes, each creating different
        # sockets. For each process check that proc.connections()
        # and net_connections() return the same results.
        # This is done mainly to check whether net_connections()'s
        # pid is properly set, see:
        # https://github.com/giampaolo/psutil/issues/1013
        with create_sockets() as socks:
            expected = len(socks)
        pids = []
        times = 10
        for i in range(times):
            fname = os.path.realpath(TESTFN) + str(i)
            src = textwrap.dedent("""\
                import time, os
                from psutil.tests import create_sockets
                with create_sockets():
                    with open('%s', 'w') as f:
                        f.write(str(os.getpid()))
                    time.sleep(60)
                """ % fname)
            sproc = pyrun(src)
            pids.append(sproc.pid)
            self.addCleanup(safe_rmpath, fname)

        # sync
        for i in range(times):
            fname = TESTFN + str(i)
            wait_for_file(fname)

        syscons = [x for x in psutil.net_connections(kind='all') if x.pid
                   in pids]
        for pid in pids:
            self.assertEqual(len([x for x in syscons if x.pid == pid]),
                             expected)
            p = psutil.Process(pid)
            self.assertEqual(len(p.connections('all')), expected)


# =====================================================================
# --- Miscellaneous tests
# =====================================================================


class TestMisc(unittest.TestCase):

    def test_connection_constants(self):
        ints = []
        strs = []
        for name in dir(psutil):
            if name.startswith('CONN_'):
                num = getattr(psutil, name)
                str_ = str(num)
                assert str_.isupper(), str_
                self.assertNotIn(str, strs)
                self.assertNotIn(num, ints)
                ints.append(num)
                strs.append(str_)
        if SUNOS:
            psutil.CONN_IDLE
            psutil.CONN_BOUND
        if WINDOWS:
            psutil.CONN_DELETE_TCB


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_contracts.py000064400000057062150466730550011344 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Contracts tests. These tests mainly check API sanity in terms of
returned types and APIs availability.
Some of these are duplicates of tests test_system.py and test_process.py
"""

import errno
import os
import stat
import time
import traceback
import warnings
from contextlib import closing

from psutil import AIX
from psutil import BSD
from psutil import FREEBSD
from psutil import LINUX
from psutil import NETBSD
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._compat import callable
from psutil._compat import long
from psutil.tests import bind_unix_socket
from psutil.tests import check_connection_ntuple
from psutil.tests import get_kernel_version
from psutil.tests import HAS_CONNECTIONS_UNIX
from psutil.tests import HAS_RLIMIT
from psutil.tests import HAS_SENSORS_FANS
from psutil.tests import HAS_SENSORS_TEMPERATURES
from psutil.tests import is_namedtuple
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_rmpath
from psutil.tests import skip_on_access_denied
from psutil.tests import TESTFN
from psutil.tests import unittest
from psutil.tests import unix_socket_path
from psutil.tests import VALID_PROC_STATUSES
from psutil.tests import warn
import psutil


# ===================================================================
# --- APIs availability
# ===================================================================


class TestAvailability(unittest.TestCase):
    """Make sure code reflects what doc promises in terms of APIs
    availability.
    """

    def test_cpu_affinity(self):
        hasit = LINUX or WINDOWS or FREEBSD
        self.assertEqual(hasattr(psutil.Process, "cpu_affinity"), hasit)

    def test_win_service(self):
        self.assertEqual(hasattr(psutil, "win_service_iter"), WINDOWS)
        self.assertEqual(hasattr(psutil, "win_service_get"), WINDOWS)

    def test_PROCFS_PATH(self):
        self.assertEqual(hasattr(psutil, "PROCFS_PATH"),
                         LINUX or SUNOS or AIX)

    def test_win_priority(self):
        ae = self.assertEqual
        ae(hasattr(psutil, "ABOVE_NORMAL_PRIORITY_CLASS"), WINDOWS)
        ae(hasattr(psutil, "BELOW_NORMAL_PRIORITY_CLASS"), WINDOWS)
        ae(hasattr(psutil, "HIGH_PRIORITY_CLASS"), WINDOWS)
        ae(hasattr(psutil, "IDLE_PRIORITY_CLASS"), WINDOWS)
        ae(hasattr(psutil, "NORMAL_PRIORITY_CLASS"), WINDOWS)
        ae(hasattr(psutil, "REALTIME_PRIORITY_CLASS"), WINDOWS)

    def test_linux_ioprio(self):
        ae = self.assertEqual
        ae(hasattr(psutil, "IOPRIO_CLASS_NONE"), LINUX)
        ae(hasattr(psutil, "IOPRIO_CLASS_RT"), LINUX)
        ae(hasattr(psutil, "IOPRIO_CLASS_BE"), LINUX)
        ae(hasattr(psutil, "IOPRIO_CLASS_IDLE"), LINUX)

    def test_linux_rlimit(self):
        ae = self.assertEqual
        hasit = LINUX and get_kernel_version() >= (2, 6, 36)
        ae(hasattr(psutil.Process, "rlimit"), hasit)
        ae(hasattr(psutil, "RLIM_INFINITY"), hasit)
        ae(hasattr(psutil, "RLIMIT_AS"), hasit)
        ae(hasattr(psutil, "RLIMIT_CORE"), hasit)
        ae(hasattr(psutil, "RLIMIT_CPU"), hasit)
        ae(hasattr(psutil, "RLIMIT_DATA"), hasit)
        ae(hasattr(psutil, "RLIMIT_FSIZE"), hasit)
        ae(hasattr(psutil, "RLIMIT_LOCKS"), hasit)
        ae(hasattr(psutil, "RLIMIT_MEMLOCK"), hasit)
        ae(hasattr(psutil, "RLIMIT_NOFILE"), hasit)
        ae(hasattr(psutil, "RLIMIT_NPROC"), hasit)
        ae(hasattr(psutil, "RLIMIT_RSS"), hasit)
        ae(hasattr(psutil, "RLIMIT_STACK"), hasit)

        hasit = LINUX and get_kernel_version() >= (3, 0)
        ae(hasattr(psutil, "RLIMIT_MSGQUEUE"), hasit)
        ae(hasattr(psutil, "RLIMIT_NICE"), hasit)
        ae(hasattr(psutil, "RLIMIT_RTPRIO"), hasit)
        ae(hasattr(psutil, "RLIMIT_RTTIME"), hasit)
        ae(hasattr(psutil, "RLIMIT_SIGPENDING"), hasit)

    def test_cpu_freq(self):
        linux = (LINUX and
                 (os.path.exists("/sys/devices/system/cpu/cpufreq") or
                  os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq")))
        self.assertEqual(hasattr(psutil, "cpu_freq"), linux or OSX or WINDOWS)

    def test_sensors_temperatures(self):
        self.assertEqual(hasattr(psutil, "sensors_temperatures"), LINUX)

    def test_sensors_fans(self):
        self.assertEqual(hasattr(psutil, "sensors_fans"), LINUX)

    def test_battery(self):
        self.assertEqual(hasattr(psutil, "sensors_battery"),
                         LINUX or WINDOWS or FREEBSD or OSX)

    def test_proc_environ(self):
        self.assertEqual(hasattr(psutil.Process, "environ"),
                         LINUX or OSX or WINDOWS)

    def test_proc_uids(self):
        self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)

    def test_proc_gids(self):
        self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)

    def test_proc_terminal(self):
        self.assertEqual(hasattr(psutil.Process, "terminal"), POSIX)

    def test_proc_ionice(self):
        self.assertEqual(hasattr(psutil.Process, "ionice"), LINUX or WINDOWS)

    def test_proc_rlimit(self):
        self.assertEqual(hasattr(psutil.Process, "rlimit"), LINUX)

    def test_proc_io_counters(self):
        hasit = hasattr(psutil.Process, "io_counters")
        self.assertEqual(hasit, False if OSX or SUNOS else True)

    def test_proc_num_fds(self):
        self.assertEqual(hasattr(psutil.Process, "num_fds"), POSIX)

    def test_proc_num_handles(self):
        self.assertEqual(hasattr(psutil.Process, "num_handles"), WINDOWS)

    def test_proc_cpu_affinity(self):
        self.assertEqual(hasattr(psutil.Process, "cpu_affinity"),
                         LINUX or WINDOWS or FREEBSD)

    def test_proc_cpu_num(self):
        self.assertEqual(hasattr(psutil.Process, "cpu_num"),
                         LINUX or FREEBSD or SUNOS)

    def test_proc_memory_maps(self):
        hasit = hasattr(psutil.Process, "memory_maps")
        self.assertEqual(hasit, False if OPENBSD or NETBSD or AIX else True)


# ===================================================================
# --- Test deprecations
# ===================================================================


class TestDeprecations(unittest.TestCase):

    def test_memory_info_ex(self):
        with warnings.catch_warnings(record=True) as ws:
            psutil.Process().memory_info_ex()
        w = ws[0]
        self.assertIsInstance(w.category(), FutureWarning)
        self.assertIn("memory_info_ex() is deprecated", str(w.message))
        self.assertIn("use memory_info() instead", str(w.message))


# ===================================================================
# --- System API types
# ===================================================================


class TestSystem(unittest.TestCase):
    """Check the return types of system related APIs.
    Mainly we want to test we never return unicode on Python 2, see:
    https://github.com/giampaolo/psutil/issues/1039
    """

    @classmethod
    def setUpClass(cls):
        cls.proc = psutil.Process()

    def tearDown(self):
        safe_rmpath(TESTFN)

    def test_cpu_times(self):
        # Duplicate of test_system.py. Keep it anyway.
        ret = psutil.cpu_times()
        assert is_namedtuple(ret)
        for n in ret:
            self.assertIsInstance(n, float)
            self.assertGreaterEqual(n, 0)

    def test_io_counters(self):
        # Duplicate of test_system.py. Keep it anyway.
        for k in psutil.disk_io_counters(perdisk=True):
            self.assertIsInstance(k, str)

    def test_disk_partitions(self):
        # Duplicate of test_system.py. Keep it anyway.
        for disk in psutil.disk_partitions():
            self.assertIsInstance(disk.device, str)
            self.assertIsInstance(disk.mountpoint, str)
            self.assertIsInstance(disk.fstype, str)
            self.assertIsInstance(disk.opts, str)

    @unittest.skipIf(not POSIX, 'POSIX only')
    @unittest.skipIf(not HAS_CONNECTIONS_UNIX, "can't list UNIX sockets")
    @skip_on_access_denied(only_if=OSX)
    def test_net_connections(self):
        with unix_socket_path() as name:
            with closing(bind_unix_socket(name)):
                cons = psutil.net_connections(kind='unix')
                assert cons
                for conn in cons:
                    self.assertIsInstance(conn.laddr, str)

    def test_net_if_addrs(self):
        # Duplicate of test_system.py. Keep it anyway.
        for ifname, addrs in psutil.net_if_addrs().items():
            self.assertIsInstance(ifname, str)
            for addr in addrs:
                self.assertIsInstance(addr.address, str)
                self.assertIsInstance(addr.netmask, (str, type(None)))
                self.assertIsInstance(addr.broadcast, (str, type(None)))

    def test_net_if_stats(self):
        # Duplicate of test_system.py. Keep it anyway.
        for ifname, _ in psutil.net_if_stats().items():
            self.assertIsInstance(ifname, str)

    def test_net_io_counters(self):
        # Duplicate of test_system.py. Keep it anyway.
        for ifname, _ in psutil.net_io_counters(pernic=True).items():
            self.assertIsInstance(ifname, str)

    @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
    def test_sensors_fans(self):
        # Duplicate of test_system.py. Keep it anyway.
        for name, units in psutil.sensors_fans().items():
            self.assertIsInstance(name, str)
            for unit in units:
                self.assertIsInstance(unit.label, str)

    @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
    def test_sensors_temperatures(self):
        # Duplicate of test_system.py. Keep it anyway.
        for name, units in psutil.sensors_temperatures().items():
            self.assertIsInstance(name, str)
            for unit in units:
                self.assertIsInstance(unit.label, str)

    def test_users(self):
        # Duplicate of test_system.py. Keep it anyway.
        for user in psutil.users():
            self.assertIsInstance(user.name, str)
            self.assertIsInstance(user.terminal, (str, type(None)))
            self.assertIsInstance(user.host, (str, type(None)))
            self.assertIsInstance(user.pid, (int, type(None)))


# ===================================================================
# --- Featch all processes test
# ===================================================================


class TestFetchAllProcesses(unittest.TestCase):
    """Test which iterates over all running processes and performs
    some sanity checks against Process API's returned values.
    """

    def setUp(self):
        if POSIX:
            import pwd
            import grp
            users = pwd.getpwall()
            groups = grp.getgrall()
            self.all_uids = set([x.pw_uid for x in users])
            self.all_usernames = set([x.pw_name for x in users])
            self.all_gids = set([x.gr_gid for x in groups])

    def test_fetch_all(self):
        valid_procs = 0
        excluded_names = set([
            'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
            'as_dict', 'parent', 'children', 'memory_info_ex', 'oneshot',
        ])
        if LINUX and not HAS_RLIMIT:
            excluded_names.add('rlimit')
        attrs = []
        for name in dir(psutil.Process):
            if name.startswith("_"):
                continue
            if name in excluded_names:
                continue
            attrs.append(name)

        default = object()
        failures = []
        for p in psutil.process_iter():
            with p.oneshot():
                for name in attrs:
                    ret = default
                    try:
                        args = ()
                        kwargs = {}
                        attr = getattr(p, name, None)
                        if attr is not None and callable(attr):
                            if name == 'rlimit':
                                args = (psutil.RLIMIT_NOFILE,)
                            elif name == 'memory_maps':
                                kwargs = {'grouped': False}
                            ret = attr(*args, **kwargs)
                        else:
                            ret = attr
                        valid_procs += 1
                    except NotImplementedError:
                        msg = "%r was skipped because not implemented" % (
                            self.__class__.__name__ + '.test_' + name)
                        warn(msg)
                    except (psutil.NoSuchProcess, psutil.AccessDenied) as err:
                        self.assertEqual(err.pid, p.pid)
                        if err.name:
                            # make sure exception's name attr is set
                            # with the actual process name
                            self.assertEqual(err.name, p.name())
                        assert str(err)
                        assert err.msg
                    except Exception as err:
                        s = '\n' + '=' * 70 + '\n'
                        s += "FAIL: test_%s (proc=%s" % (name, p)
                        if ret != default:
                            s += ", ret=%s)" % repr(ret)
                        s += ')\n'
                        s += '-' * 70
                        s += "\n%s" % traceback.format_exc()
                        s = "\n".join((" " * 4) + i for i in s.splitlines())
                        s += '\n'
                        failures.append(s)
                        break
                    else:
                        if ret not in (0, 0.0, [], None, '', {}):
                            assert ret, ret
                        meth = getattr(self, name)
                        meth(ret, p)

        if failures:
            self.fail(''.join(failures))

        # we should always have a non-empty list, not including PID 0 etc.
        # special cases.
        assert valid_procs

    def cmdline(self, ret, proc):
        self.assertIsInstance(ret, list)
        for part in ret:
            self.assertIsInstance(part, str)

    def exe(self, ret, proc):
        self.assertIsInstance(ret, (str, type(None)))
        if not ret:
            self.assertEqual(ret, '')
        else:
            assert os.path.isabs(ret), ret
            # Note: os.stat() may return False even if the file is there
            # hence we skip the test, see:
            # http://stackoverflow.com/questions/3112546/os-path-exists-lies
            if POSIX and os.path.isfile(ret):
                if hasattr(os, 'access') and hasattr(os, "X_OK"):
                    # XXX may fail on OSX
                    assert os.access(ret, os.X_OK)

    def pid(self, ret, proc):
        self.assertIsInstance(ret, int)
        self.assertGreaterEqual(ret, 0)

    def ppid(self, ret, proc):
        self.assertIsInstance(ret, (int, long))
        self.assertGreaterEqual(ret, 0)

    def name(self, ret, proc):
        self.assertIsInstance(ret, str)
        # on AIX, "<exiting>" processes don't have names
        if not AIX:
            assert ret

    def create_time(self, ret, proc):
        self.assertIsInstance(ret, float)
        try:
            self.assertGreaterEqual(ret, 0)
        except AssertionError:
            # XXX
            if OPENBSD and proc.status() == psutil.STATUS_ZOMBIE:
                pass
            else:
                raise
        # this can't be taken for granted on all platforms
        # self.assertGreaterEqual(ret, psutil.boot_time())
        # make sure returned value can be pretty printed
        # with strftime
        time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))

    def uids(self, ret, proc):
        assert is_namedtuple(ret)
        for uid in ret:
            self.assertIsInstance(uid, int)
            self.assertGreaterEqual(uid, 0)
            self.assertIn(uid, self.all_uids)

    def gids(self, ret, proc):
        assert is_namedtuple(ret)
        # note: testing all gids as above seems not to be reliable for
        # gid == 30 (nodoby); not sure why.
        for gid in ret:
            self.assertIsInstance(gid, int)
            if not OSX and not NETBSD:
                self.assertGreaterEqual(gid, 0)
                self.assertIn(gid, self.all_gids)

    def username(self, ret, proc):
        self.assertIsInstance(ret, str)
        assert ret
        if POSIX:
            self.assertIn(ret, self.all_usernames)

    def status(self, ret, proc):
        self.assertIsInstance(ret, str)
        assert ret
        self.assertNotEqual(ret, '?')  # XXX
        self.assertIn(ret, VALID_PROC_STATUSES)

    def io_counters(self, ret, proc):
        assert is_namedtuple(ret)
        for field in ret:
            self.assertIsInstance(field, (int, long))
            if field != -1:
                self.assertGreaterEqual(field, 0)

    def ionice(self, ret, proc):
        if POSIX:
            assert is_namedtuple(ret)
            for field in ret:
                self.assertIsInstance(field, int)
        if LINUX:
            self.assertGreaterEqual(ret.ioclass, 0)
            self.assertGreaterEqual(ret.value, 0)
        else:
            self.assertGreaterEqual(ret, 0)
            self.assertIn(ret, (0, 1, 2))

    def num_threads(self, ret, proc):
        self.assertIsInstance(ret, int)
        self.assertGreaterEqual(ret, 1)

    def threads(self, ret, proc):
        self.assertIsInstance(ret, list)
        for t in ret:
            assert is_namedtuple(t)
            self.assertGreaterEqual(t.id, 0)
            self.assertGreaterEqual(t.user_time, 0)
            self.assertGreaterEqual(t.system_time, 0)
            for field in t:
                self.assertIsInstance(field, (int, float))

    def cpu_times(self, ret, proc):
        assert is_namedtuple(ret)
        for n in ret:
            self.assertIsInstance(n, float)
            self.assertGreaterEqual(n, 0)
        # TODO: check ntuple fields

    def cpu_percent(self, ret, proc):
        self.assertIsInstance(ret, float)
        assert 0.0 <= ret <= 100.0, ret

    def cpu_num(self, ret, proc):
        self.assertIsInstance(ret, int)
        if FREEBSD and ret == -1:
            return
        self.assertGreaterEqual(ret, 0)
        if psutil.cpu_count() == 1:
            self.assertEqual(ret, 0)
        self.assertIn(ret, list(range(psutil.cpu_count())))

    def memory_info(self, ret, proc):
        assert is_namedtuple(ret)
        for value in ret:
            self.assertIsInstance(value, (int, long))
            self.assertGreaterEqual(value, 0)
        if POSIX and not AIX and ret.vms != 0:
            # VMS is always supposed to be the highest
            for name in ret._fields:
                if name != 'vms':
                    value = getattr(ret, name)
                    self.assertGreater(ret.vms, value, msg=ret)
        elif WINDOWS:
            self.assertGreaterEqual(ret.peak_wset, ret.wset)
            self.assertGreaterEqual(ret.peak_paged_pool, ret.paged_pool)
            self.assertGreaterEqual(ret.peak_nonpaged_pool, ret.nonpaged_pool)
            self.assertGreaterEqual(ret.peak_pagefile, ret.pagefile)

    def memory_full_info(self, ret, proc):
        assert is_namedtuple(ret)
        total = psutil.virtual_memory().total
        for name in ret._fields:
            value = getattr(ret, name)
            self.assertIsInstance(value, (int, long))
            self.assertGreaterEqual(value, 0, msg=(name, value))
            self.assertLessEqual(value, total, msg=(name, value, total))

        if LINUX:
            self.assertGreaterEqual(ret.pss, ret.uss)

    def open_files(self, ret, proc):
        self.assertIsInstance(ret, list)
        for f in ret:
            self.assertIsInstance(f.fd, int)
            self.assertIsInstance(f.path, str)
            if WINDOWS:
                self.assertEqual(f.fd, -1)
            elif LINUX:
                self.assertIsInstance(f.position, int)
                self.assertIsInstance(f.mode, str)
                self.assertIsInstance(f.flags, int)
                self.assertGreaterEqual(f.position, 0)
                self.assertIn(f.mode, ('r', 'w', 'a', 'r+', 'a+'))
                self.assertGreater(f.flags, 0)
            elif BSD and not f.path:
                # XXX see: https://github.com/giampaolo/psutil/issues/595
                continue
            assert os.path.isabs(f.path), f
            assert os.path.isfile(f.path), f

    def num_fds(self, ret, proc):
        self.assertIsInstance(ret, int)
        self.assertGreaterEqual(ret, 0)

    def connections(self, ret, proc):
        self.assertEqual(len(ret), len(set(ret)))
        for conn in ret:
            check_connection_ntuple(conn)

    def cwd(self, ret, proc):
        if ret:     # 'ret' can be None or empty
            self.assertIsInstance(ret, str)
            assert os.path.isabs(ret), ret
            try:
                st = os.stat(ret)
            except OSError as err:
                if WINDOWS and err.errno in \
                        psutil._psplatform.ACCESS_DENIED_SET:
                    pass
                # directory has been removed in mean time
                elif err.errno != errno.ENOENT:
                    raise
            else:
                assert stat.S_ISDIR(st.st_mode)

    def memory_percent(self, ret, proc):
        self.assertIsInstance(ret, float)
        assert 0 <= ret <= 100, ret

    def is_running(self, ret, proc):
        self.assertIsInstance(ret, bool)

    def cpu_affinity(self, ret, proc):
        self.assertIsInstance(ret, list)
        assert ret != [], ret
        cpus = range(psutil.cpu_count())
        for n in ret:
            self.assertIsInstance(n, int)
            self.assertIn(n, cpus)

    def terminal(self, ret, proc):
        self.assertIsInstance(ret, (str, type(None)))
        if ret is not None:
            assert os.path.isabs(ret), ret
            assert os.path.exists(ret), ret

    def memory_maps(self, ret, proc):
        for nt in ret:
            self.assertIsInstance(nt.addr, str)
            self.assertIsInstance(nt.perms, str)
            self.assertIsInstance(nt.path, str)
            for fname in nt._fields:
                value = getattr(nt, fname)
                if fname == 'path':
                    if not value.startswith('['):
                        assert os.path.isabs(nt.path), nt.path
                        # commented as on Linux we might get
                        # '/foo/bar (deleted)'
                        # assert os.path.exists(nt.path), nt.path
                elif fname in ('addr', 'perms'):
                    assert value
                else:
                    self.assertIsInstance(value, (int, long))
                    self.assertGreaterEqual(value, 0)

    def num_handles(self, ret, proc):
        self.assertIsInstance(ret, int)
        self.assertGreaterEqual(ret, 0)

    def nice(self, ret, proc):
        self.assertIsInstance(ret, int)
        if POSIX:
            assert -20 <= ret <= 20, ret
        else:
            priorities = [getattr(psutil, x) for x in dir(psutil)
                          if x.endswith('_PRIORITY_CLASS')]
            self.assertIn(ret, priorities)

    def num_ctx_switches(self, ret, proc):
        assert is_namedtuple(ret)
        for value in ret:
            self.assertIsInstance(value, (int, long))
            self.assertGreaterEqual(value, 0)

    def rlimit(self, ret, proc):
        self.assertIsInstance(ret, tuple)
        self.assertEqual(len(ret), 2)
        self.assertGreaterEqual(ret[0], -1)
        self.assertGreaterEqual(ret[1], -1)

    def environ(self, ret, proc):
        self.assertIsInstance(ret, dict)
        for k, v in ret.items():
            self.assertIsInstance(k, str)
            self.assertIsInstance(v, str)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_process.py000064400000166071150466730550011023 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Tests for psutil.Process class."""

import collections
import errno
import getpass
import itertools
import os
import signal
import socket
import subprocess
import sys
import tempfile
import textwrap
import time
import types

import psutil

from psutil import AIX
from psutil import BSD
from psutil import LINUX
from psutil import NETBSD
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._compat import long
from psutil._compat import PY3
from psutil.tests import APPVEYOR
from psutil.tests import call_until
from psutil.tests import copyload_shared_lib
from psutil.tests import create_exe
from psutil.tests import create_proc_children_pair
from psutil.tests import create_zombie_proc
from psutil.tests import enum
from psutil.tests import get_test_subprocess
from psutil.tests import get_winver
from psutil.tests import HAS_CPU_AFFINITY
from psutil.tests import HAS_ENVIRON
from psutil.tests import HAS_IONICE
from psutil.tests import HAS_MEMORY_MAPS
from psutil.tests import HAS_PROC_CPU_NUM
from psutil.tests import HAS_PROC_IO_COUNTERS
from psutil.tests import HAS_RLIMIT
from psutil.tests import HAS_THREADS
from psutil.tests import mock
from psutil.tests import PYPY
from psutil.tests import PYTHON_EXE
from psutil.tests import reap_children
from psutil.tests import retry_before_failing
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_rmpath
from psutil.tests import sh
from psutil.tests import skip_on_access_denied
from psutil.tests import skip_on_not_implemented
from psutil.tests import TESTFILE_PREFIX
from psutil.tests import TESTFN
from psutil.tests import ThreadTask
from psutil.tests import TRAVIS
from psutil.tests import unittest
from psutil.tests import wait_for_pid
from psutil.tests import WIN_VISTA


# ===================================================================
# --- psutil.Process class tests
# ===================================================================

class TestProcess(unittest.TestCase):
    """Tests for psutil.Process class."""

    def setUp(self):
        safe_rmpath(TESTFN)

    def tearDown(self):
        reap_children()

    def test_pid(self):
        p = psutil.Process()
        self.assertEqual(p.pid, os.getpid())
        sproc = get_test_subprocess()
        self.assertEqual(psutil.Process(sproc.pid).pid, sproc.pid)
        with self.assertRaises(AttributeError):
            p.pid = 33

    def test_kill(self):
        sproc = get_test_subprocess()
        test_pid = sproc.pid
        p = psutil.Process(test_pid)
        p.kill()
        sig = p.wait()
        self.assertFalse(psutil.pid_exists(test_pid))
        if POSIX:
            self.assertEqual(sig, -signal.SIGKILL)

    def test_terminate(self):
        sproc = get_test_subprocess()
        test_pid = sproc.pid
        p = psutil.Process(test_pid)
        p.terminate()
        sig = p.wait()
        self.assertFalse(psutil.pid_exists(test_pid))
        if POSIX:
            self.assertEqual(sig, -signal.SIGTERM)

    def test_send_signal(self):
        sig = signal.SIGKILL if POSIX else signal.SIGTERM
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        p.send_signal(sig)
        exit_sig = p.wait()
        self.assertFalse(psutil.pid_exists(p.pid))
        if POSIX:
            self.assertEqual(exit_sig, -sig)
            #
            sproc = get_test_subprocess()
            p = psutil.Process(sproc.pid)
            p.send_signal(sig)
            with mock.patch('psutil.os.kill',
                            side_effect=OSError(errno.ESRCH, "")):
                with self.assertRaises(psutil.NoSuchProcess):
                    p.send_signal(sig)
            #
            sproc = get_test_subprocess()
            p = psutil.Process(sproc.pid)
            p.send_signal(sig)
            with mock.patch('psutil.os.kill',
                            side_effect=OSError(errno.EPERM, "")):
                with self.assertRaises(psutil.AccessDenied):
                    psutil.Process().send_signal(sig)
            # Sending a signal to process with PID 0 is not allowed as
            # it would affect every process in the process group of
            # the calling process (os.getpid()) instead of PID 0").
            if 0 in psutil.pids():
                p = psutil.Process(0)
                self.assertRaises(ValueError, p.send_signal, signal.SIGTERM)

    def test_wait(self):
        # check exit code signal
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        p.kill()
        code = p.wait()
        if POSIX:
            self.assertEqual(code, -signal.SIGKILL)
        else:
            self.assertEqual(code, signal.SIGTERM)
        self.assertFalse(p.is_running())

        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        p.terminate()
        code = p.wait()
        if POSIX:
            self.assertEqual(code, -signal.SIGTERM)
        else:
            self.assertEqual(code, signal.SIGTERM)
        self.assertFalse(p.is_running())

        # check sys.exit() code
        code = "import time, sys; time.sleep(0.01); sys.exit(5);"
        sproc = get_test_subprocess([PYTHON_EXE, "-c", code])
        p = psutil.Process(sproc.pid)
        self.assertEqual(p.wait(), 5)
        self.assertFalse(p.is_running())

        # Test wait() issued twice.
        # It is not supposed to raise NSP when the process is gone.
        # On UNIX this should return None, on Windows it should keep
        # returning the exit code.
        sproc = get_test_subprocess([PYTHON_EXE, "-c", code])
        p = psutil.Process(sproc.pid)
        self.assertEqual(p.wait(), 5)
        self.assertIn(p.wait(), (5, None))

        # test timeout
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        p.name()
        self.assertRaises(psutil.TimeoutExpired, p.wait, 0.01)

        # timeout < 0 not allowed
        self.assertRaises(ValueError, p.wait, -1)

    def test_wait_non_children(self):
        # Test wait() against a process which is not our direct
        # child.
        p1, p2 = create_proc_children_pair()
        self.assertRaises(psutil.TimeoutExpired, p1.wait, 0.01)
        self.assertRaises(psutil.TimeoutExpired, p2.wait, 0.01)
        # We also terminate the direct child otherwise the
        # grandchild will hang until the parent is gone.
        p1.terminate()
        p2.terminate()
        ret1 = p1.wait()
        ret2 = p2.wait()
        if POSIX:
            self.assertEqual(ret1, -signal.SIGTERM)
            # For processes which are not our children we're supposed
            # to get None.
            self.assertEqual(ret2, None)
        else:
            self.assertEqual(ret1, signal.SIGTERM)
            self.assertEqual(ret1, signal.SIGTERM)

    def test_wait_timeout_0(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        self.assertRaises(psutil.TimeoutExpired, p.wait, 0)
        p.kill()
        stop_at = time.time() + 2
        while True:
            try:
                code = p.wait(0)
            except psutil.TimeoutExpired:
                if time.time() >= stop_at:
                    raise
            else:
                break
        if POSIX:
            self.assertEqual(code, -signal.SIGKILL)
        else:
            self.assertEqual(code, signal.SIGTERM)
        self.assertFalse(p.is_running())

    def test_cpu_percent(self):
        p = psutil.Process()
        p.cpu_percent(interval=0.001)
        p.cpu_percent(interval=0.001)
        for x in range(100):
            percent = p.cpu_percent(interval=None)
            self.assertIsInstance(percent, float)
            self.assertGreaterEqual(percent, 0.0)
            if not POSIX:
                self.assertLessEqual(percent, 100.0)
            else:
                self.assertGreaterEqual(percent, 0.0)
        with self.assertRaises(ValueError):
            p.cpu_percent(interval=-1)

    def test_cpu_percent_numcpus_none(self):
        # See: https://github.com/giampaolo/psutil/issues/1087
        with mock.patch('psutil.cpu_count', return_value=None) as m:
            psutil.Process().cpu_percent()
            assert m.called

    def test_cpu_times(self):
        times = psutil.Process().cpu_times()
        assert (times.user > 0.0) or (times.system > 0.0), times
        assert (times.children_user >= 0.0), times
        assert (times.children_system >= 0.0), times
        # make sure returned values can be pretty printed with strftime
        for name in times._fields:
            time.strftime("%H:%M:%S", time.localtime(getattr(times, name)))

    def test_cpu_times_2(self):
        user_time, kernel_time = psutil.Process().cpu_times()[:2]
        utime, ktime = os.times()[:2]

        # Use os.times()[:2] as base values to compare our results
        # using a tolerance  of +/- 0.1 seconds.
        # It will fail if the difference between the values is > 0.1s.
        if (max([user_time, utime]) - min([user_time, utime])) > 0.1:
            self.fail("expected: %s, found: %s" % (utime, user_time))

        if (max([kernel_time, ktime]) - min([kernel_time, ktime])) > 0.1:
            self.fail("expected: %s, found: %s" % (ktime, kernel_time))

    @unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported")
    def test_cpu_num(self):
        p = psutil.Process()
        num = p.cpu_num()
        self.assertGreaterEqual(num, 0)
        if psutil.cpu_count() == 1:
            self.assertEqual(num, 0)
        self.assertIn(p.cpu_num(), range(psutil.cpu_count()))

    def test_create_time(self):
        sproc = get_test_subprocess()
        now = time.time()
        p = psutil.Process(sproc.pid)
        create_time = p.create_time()

        # Use time.time() as base value to compare our result using a
        # tolerance of +/- 1 second.
        # It will fail if the difference between the values is > 2s.
        difference = abs(create_time - now)
        if difference > 2:
            self.fail("expected: %s, found: %s, difference: %s"
                      % (now, create_time, difference))

        # make sure returned value can be pretty printed with strftime
        time.strftime("%Y %m %d %H:%M:%S", time.localtime(p.create_time()))

    @unittest.skipIf(not POSIX, 'POSIX only')
    @unittest.skipIf(TRAVIS, 'not reliable on TRAVIS')
    def test_terminal(self):
        terminal = psutil.Process().terminal()
        if sys.stdin.isatty() or sys.stdout.isatty():
            tty = os.path.realpath(sh('tty'))
            self.assertEqual(terminal, tty)
        else:
            self.assertIsNone(terminal)

    @unittest.skipIf(not HAS_PROC_IO_COUNTERS, 'not supported')
    @skip_on_not_implemented(only_if=LINUX)
    def test_io_counters(self):
        p = psutil.Process()

        # test reads
        io1 = p.io_counters()
        with open(PYTHON_EXE, 'rb') as f:
            f.read()
        io2 = p.io_counters()
        if not BSD and not AIX:
            self.assertGreater(io2.read_count, io1.read_count)
            self.assertEqual(io2.write_count, io1.write_count)
            if LINUX:
                self.assertGreater(io2.read_chars, io1.read_chars)
                self.assertEqual(io2.write_chars, io1.write_chars)
        else:
            self.assertGreaterEqual(io2.read_bytes, io1.read_bytes)
            self.assertGreaterEqual(io2.write_bytes, io1.write_bytes)

        # test writes
        io1 = p.io_counters()
        with tempfile.TemporaryFile(prefix=TESTFILE_PREFIX) as f:
            if PY3:
                f.write(bytes("x" * 1000000, 'ascii'))
            else:
                f.write("x" * 1000000)
        io2 = p.io_counters()
        self.assertGreaterEqual(io2.write_count, io1.write_count)
        self.assertGreaterEqual(io2.write_bytes, io1.write_bytes)
        self.assertGreaterEqual(io2.read_count, io1.read_count)
        self.assertGreaterEqual(io2.read_bytes, io1.read_bytes)
        if LINUX:
            self.assertGreater(io2.write_chars, io1.write_chars)
            self.assertGreaterEqual(io2.read_chars, io1.read_chars)

        # sanity check
        for i in range(len(io2)):
            if BSD and i >= 2:
                # On BSD read_bytes and write_bytes are always set to -1.
                continue
            self.assertGreaterEqual(io2[i], 0)
            self.assertGreaterEqual(io2[i], 0)

    @unittest.skipIf(not HAS_IONICE, "not supported")
    @unittest.skipIf(WINDOWS and get_winver() < WIN_VISTA, 'not supported')
    def test_ionice(self):
        if LINUX:
            from psutil import (IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT,
                                IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE)
            self.assertEqual(IOPRIO_CLASS_NONE, 0)
            self.assertEqual(IOPRIO_CLASS_RT, 1)
            self.assertEqual(IOPRIO_CLASS_BE, 2)
            self.assertEqual(IOPRIO_CLASS_IDLE, 3)
            p = psutil.Process()
            try:
                p.ionice(2)
                ioclass, value = p.ionice()
                if enum is not None:
                    self.assertIsInstance(ioclass, enum.IntEnum)
                self.assertEqual(ioclass, 2)
                self.assertEqual(value, 4)
                #
                p.ionice(3)
                ioclass, value = p.ionice()
                self.assertEqual(ioclass, 3)
                self.assertEqual(value, 0)
                #
                p.ionice(2, 0)
                ioclass, value = p.ionice()
                self.assertEqual(ioclass, 2)
                self.assertEqual(value, 0)
                p.ionice(2, 7)
                ioclass, value = p.ionice()
                self.assertEqual(ioclass, 2)
                self.assertEqual(value, 7)
            finally:
                p.ionice(IOPRIO_CLASS_NONE)
        else:
            p = psutil.Process()
            original = p.ionice()
            self.assertIsInstance(original, int)
            try:
                value = 0  # very low
                if original == value:
                    value = 1  # low
                p.ionice(value)
                self.assertEqual(p.ionice(), value)
            finally:
                p.ionice(original)

    @unittest.skipIf(not HAS_IONICE, "not supported")
    @unittest.skipIf(WINDOWS and get_winver() < WIN_VISTA, 'not supported')
    def test_ionice_errs(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        if LINUX:
            self.assertRaises(ValueError, p.ionice, 2, 10)
            self.assertRaises(ValueError, p.ionice, 2, -1)
            self.assertRaises(ValueError, p.ionice, 4)
            self.assertRaises(TypeError, p.ionice, 2, "foo")
            self.assertRaisesRegex(
                ValueError, "can't specify value with IOPRIO_CLASS_NONE",
                p.ionice, psutil.IOPRIO_CLASS_NONE, 1)
            self.assertRaisesRegex(
                ValueError, "can't specify value with IOPRIO_CLASS_IDLE",
                p.ionice, psutil.IOPRIO_CLASS_IDLE, 1)
            self.assertRaisesRegex(
                ValueError, "'ioclass' argument must be specified",
                p.ionice, value=1)
        else:
            self.assertRaises(ValueError, p.ionice, 3)
            self.assertRaises(TypeError, p.ionice, 2, 1)

    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit_get(self):
        import resource
        p = psutil.Process(os.getpid())
        names = [x for x in dir(psutil) if x.startswith('RLIMIT')]
        assert names, names
        for name in names:
            value = getattr(psutil, name)
            self.assertGreaterEqual(value, 0)
            if name in dir(resource):
                self.assertEqual(value, getattr(resource, name))
                # XXX - On PyPy RLIMIT_INFINITY returned by
                # resource.getrlimit() is reported as a very big long
                # number instead of -1. It looks like a bug with PyPy.
                if PYPY:
                    continue
                self.assertEqual(p.rlimit(value), resource.getrlimit(value))
            else:
                ret = p.rlimit(value)
                self.assertEqual(len(ret), 2)
                self.assertGreaterEqual(ret[0], -1)
                self.assertGreaterEqual(ret[1], -1)

    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit_set(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        p.rlimit(psutil.RLIMIT_NOFILE, (5, 5))
        self.assertEqual(p.rlimit(psutil.RLIMIT_NOFILE), (5, 5))
        # If pid is 0 prlimit() applies to the calling process and
        # we don't want that.
        with self.assertRaises(ValueError):
            psutil._psplatform.Process(0).rlimit(0)
        with self.assertRaises(ValueError):
            p.rlimit(psutil.RLIMIT_NOFILE, (5, 5, 5))

    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit(self):
        p = psutil.Process()
        soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
        try:
            p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
            with open(TESTFN, "wb") as f:
                f.write(b"X" * 1024)
            # write() or flush() doesn't always cause the exception
            # but close() will.
            with self.assertRaises(IOError) as exc:
                with open(TESTFN, "wb") as f:
                    f.write(b"X" * 1025)
            self.assertEqual(exc.exception.errno if PY3 else exc.exception[0],
                             errno.EFBIG)
        finally:
            p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
            self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))

    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit_infinity(self):
        # First set a limit, then re-set it by specifying INFINITY
        # and assume we overridden the previous limit.
        p = psutil.Process()
        soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
        try:
            p.rlimit(psutil.RLIMIT_FSIZE, (1024, hard))
            p.rlimit(psutil.RLIMIT_FSIZE, (psutil.RLIM_INFINITY, hard))
            with open(TESTFN, "wb") as f:
                f.write(b"X" * 2048)
        finally:
            p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))
            self.assertEqual(p.rlimit(psutil.RLIMIT_FSIZE), (soft, hard))

    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit_infinity_value(self):
        # RLIMIT_FSIZE should be RLIM_INFINITY, which will be a really
        # big number on a platform with large file support.  On these
        # platforms we need to test that the get/setrlimit functions
        # properly convert the number to a C long long and that the
        # conversion doesn't raise an error.
        p = psutil.Process()
        soft, hard = p.rlimit(psutil.RLIMIT_FSIZE)
        self.assertEqual(psutil.RLIM_INFINITY, hard)
        p.rlimit(psutil.RLIMIT_FSIZE, (soft, hard))

    def test_num_threads(self):
        # on certain platforms such as Linux we might test for exact
        # thread number, since we always have with 1 thread per process,
        # but this does not apply across all platforms (OSX, Windows)
        p = psutil.Process()
        if OPENBSD:
            try:
                step1 = p.num_threads()
            except psutil.AccessDenied:
                raise unittest.SkipTest("on OpenBSD this requires root access")
        else:
            step1 = p.num_threads()

        with ThreadTask():
            step2 = p.num_threads()
            self.assertEqual(step2, step1 + 1)

    @unittest.skipIf(not WINDOWS, 'WINDOWS only')
    def test_num_handles(self):
        # a better test is done later into test/_windows.py
        p = psutil.Process()
        self.assertGreater(p.num_handles(), 0)

    @unittest.skipIf(not HAS_THREADS, 'not supported')
    def test_threads(self):
        p = psutil.Process()
        if OPENBSD:
            try:
                step1 = p.threads()
            except psutil.AccessDenied:
                raise unittest.SkipTest("on OpenBSD this requires root access")
        else:
            step1 = p.threads()

        with ThreadTask():
            step2 = p.threads()
            self.assertEqual(len(step2), len(step1) + 1)
            # on Linux, first thread id is supposed to be this process
            if LINUX:
                self.assertEqual(step2[0].id, os.getpid())
            athread = step2[0]
            # test named tuple
            self.assertEqual(athread.id, athread[0])
            self.assertEqual(athread.user_time, athread[1])
            self.assertEqual(athread.system_time, athread[2])

    @retry_before_failing()
    @skip_on_access_denied(only_if=OSX)
    @unittest.skipIf(not HAS_THREADS, 'not supported')
    def test_threads_2(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        if OPENBSD:
            try:
                p.threads()
            except psutil.AccessDenied:
                raise unittest.SkipTest(
                    "on OpenBSD this requires root access")
        self.assertAlmostEqual(
            p.cpu_times().user,
            sum([x.user_time for x in p.threads()]), delta=0.1)
        self.assertAlmostEqual(
            p.cpu_times().system,
            sum([x.system_time for x in p.threads()]), delta=0.1)

    def test_memory_info(self):
        p = psutil.Process()

        # step 1 - get a base value to compare our results
        rss1, vms1 = p.memory_info()[:2]
        percent1 = p.memory_percent()
        self.assertGreater(rss1, 0)
        self.assertGreater(vms1, 0)

        # step 2 - allocate some memory
        memarr = [None] * 1500000

        rss2, vms2 = p.memory_info()[:2]
        percent2 = p.memory_percent()

        # step 3 - make sure that the memory usage bumped up
        self.assertGreater(rss2, rss1)
        self.assertGreaterEqual(vms2, vms1)  # vms might be equal
        self.assertGreater(percent2, percent1)
        del memarr

        if WINDOWS:
            mem = p.memory_info()
            self.assertEqual(mem.rss, mem.wset)
            self.assertEqual(mem.vms, mem.pagefile)

        mem = p.memory_info()
        for name in mem._fields:
            self.assertGreaterEqual(getattr(mem, name), 0)

    def test_memory_full_info(self):
        total = psutil.virtual_memory().total
        mem = psutil.Process().memory_full_info()
        for name in mem._fields:
            value = getattr(mem, name)
            self.assertGreaterEqual(value, 0, msg=(name, value))
            self.assertLessEqual(value, total, msg=(name, value, total))
        if LINUX or WINDOWS or OSX:
            self.assertGreaterEqual(mem.uss, 0)
        if LINUX:
            self.assertGreaterEqual(mem.pss, 0)
            self.assertGreaterEqual(mem.swap, 0)

    @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
    def test_memory_maps(self):
        p = psutil.Process()
        maps = p.memory_maps()
        paths = [x for x in maps]
        self.assertEqual(len(paths), len(set(paths)))
        ext_maps = p.memory_maps(grouped=False)

        for nt in maps:
            if not nt.path.startswith('['):
                assert os.path.isabs(nt.path), nt.path
                if POSIX:
                    try:
                        assert os.path.exists(nt.path) or \
                            os.path.islink(nt.path), nt.path
                    except AssertionError:
                        if not LINUX:
                            raise
                        else:
                            # https://github.com/giampaolo/psutil/issues/759
                            with open('/proc/self/smaps') as f:
                                data = f.read()
                            if "%s (deleted)" % nt.path not in data:
                                raise
                else:
                    # XXX - On Windows we have this strange behavior with
                    # 64 bit dlls: they are visible via explorer but cannot
                    # be accessed via os.stat() (wtf?).
                    if '64' not in os.path.basename(nt.path):
                        assert os.path.exists(nt.path), nt.path
        for nt in ext_maps:
            for fname in nt._fields:
                value = getattr(nt, fname)
                if fname == 'path':
                    continue
                elif fname in ('addr', 'perms'):
                    assert value, value
                else:
                    self.assertIsInstance(value, (int, long))
                    assert value >= 0, value

    @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
    def test_memory_maps_lists_lib(self):
        # Make sure a newly loaded shared lib is listed.
        with copyload_shared_lib() as path:
            def normpath(p):
                return os.path.realpath(os.path.normcase(p))
            libpaths = [normpath(x.path)
                        for x in psutil.Process().memory_maps()]
            self.assertIn(normpath(path), libpaths)

    def test_memory_percent(self):
        p = psutil.Process()
        ret = p.memory_percent()
        assert 0 <= ret <= 100, ret
        ret = p.memory_percent(memtype='vms')
        assert 0 <= ret <= 100, ret
        assert 0 <= ret <= 100, ret
        self.assertRaises(ValueError, p.memory_percent, memtype="?!?")
        if LINUX or OSX or WINDOWS:
            ret = p.memory_percent(memtype='uss')
            assert 0 <= ret <= 100, ret
            assert 0 <= ret <= 100, ret

    def test_is_running(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        assert p.is_running()
        assert p.is_running()
        p.kill()
        p.wait()
        assert not p.is_running()
        assert not p.is_running()

    def test_exe(self):
        sproc = get_test_subprocess()
        exe = psutil.Process(sproc.pid).exe()
        try:
            self.assertEqual(exe, PYTHON_EXE)
        except AssertionError:
            if WINDOWS and len(exe) == len(PYTHON_EXE):
                # on Windows we don't care about case sensitivity
                normcase = os.path.normcase
                self.assertEqual(normcase(exe), normcase(PYTHON_EXE))
            else:
                # certain platforms such as BSD are more accurate returning:
                # "/usr/local/bin/python2.7"
                # ...instead of:
                # "/usr/local/bin/python"
                # We do not want to consider this difference in accuracy
                # an error.
                ver = "%s.%s" % (sys.version_info[0], sys.version_info[1])
                try:
                    self.assertEqual(exe.replace(ver, ''),
                                     PYTHON_EXE.replace(ver, ''))
                except AssertionError:
                    # Tipically OSX. Really not sure what to do here.
                    pass

        out = sh([exe, "-c", "import os; print('hey')"])
        self.assertEqual(out, 'hey')

    def test_cmdline(self):
        cmdline = [PYTHON_EXE, "-c", "import time; time.sleep(60)"]
        sproc = get_test_subprocess(cmdline)
        try:
            self.assertEqual(' '.join(psutil.Process(sproc.pid).cmdline()),
                             ' '.join(cmdline))
        except AssertionError:
            # XXX - most of the times the underlying sysctl() call on Net
            # and Open BSD returns a truncated string.
            # Also /proc/pid/cmdline behaves the same so it looks
            # like this is a kernel bug.
            # XXX - AIX truncates long arguments in /proc/pid/cmdline
            if NETBSD or OPENBSD or AIX:
                self.assertEqual(
                    psutil.Process(sproc.pid).cmdline()[0], PYTHON_EXE)
            else:
                raise

    def test_name(self):
        sproc = get_test_subprocess(PYTHON_EXE)
        name = psutil.Process(sproc.pid).name().lower()
        pyexe = os.path.basename(os.path.realpath(sys.executable)).lower()
        assert pyexe.startswith(name), (pyexe, name)

    # XXX
    @unittest.skipIf(SUNOS, "broken on SUNOS")
    @unittest.skipIf(AIX, "broken on AIX")
    def test_prog_w_funky_name(self):
        # Test that name(), exe() and cmdline() correctly handle programs
        # with funky chars such as spaces and ")", see:
        # https://github.com/giampaolo/psutil/issues/628

        def rm():
            # Try to limit occasional failures on Appveyor:
            # https://ci.appveyor.com/project/giampaolo/psutil/build/1350/
            #     job/lbo3bkju55le850n
            try:
                safe_rmpath(funky_path)
            except OSError:
                pass

        funky_path = TESTFN + 'foo bar )'
        create_exe(funky_path)
        self.addCleanup(rm)
        cmdline = [funky_path, "-c",
                   "import time; [time.sleep(0.01) for x in range(3000)];"
                   "arg1", "arg2", "", "arg3", ""]
        sproc = get_test_subprocess(cmdline)
        p = psutil.Process(sproc.pid)
        # ...in order to try to prevent occasional failures on travis
        if TRAVIS:
            wait_for_pid(p.pid)
        self.assertEqual(p.cmdline(), cmdline)
        self.assertEqual(p.name(), os.path.basename(funky_path))
        self.assertEqual(os.path.normcase(p.exe()),
                         os.path.normcase(funky_path))

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_uids(self):
        p = psutil.Process()
        real, effective, saved = p.uids()
        # os.getuid() refers to "real" uid
        self.assertEqual(real, os.getuid())
        # os.geteuid() refers to "effective" uid
        self.assertEqual(effective, os.geteuid())
        # No such thing as os.getsuid() ("saved" uid), but starting
        # from python 2.7 we have os.getresuid() which returns all
        # of them.
        if hasattr(os, "getresuid"):
            self.assertEqual(os.getresuid(), p.uids())

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_gids(self):
        p = psutil.Process()
        real, effective, saved = p.gids()
        # os.getuid() refers to "real" uid
        self.assertEqual(real, os.getgid())
        # os.geteuid() refers to "effective" uid
        self.assertEqual(effective, os.getegid())
        # No such thing as os.getsgid() ("saved" gid), but starting
        # from python 2.7 we have os.getresgid() which returns all
        # of them.
        if hasattr(os, "getresuid"):
            self.assertEqual(os.getresgid(), p.gids())

    def test_nice(self):
        p = psutil.Process()
        self.assertRaises(TypeError, p.nice, "str")
        if WINDOWS:
            try:
                init = p.nice()
                if sys.version_info > (3, 4):
                    self.assertIsInstance(init, enum.IntEnum)
                else:
                    self.assertIsInstance(init, int)
                self.assertEqual(init, psutil.NORMAL_PRIORITY_CLASS)
                p.nice(psutil.HIGH_PRIORITY_CLASS)
                self.assertEqual(p.nice(), psutil.HIGH_PRIORITY_CLASS)
                p.nice(psutil.NORMAL_PRIORITY_CLASS)
                self.assertEqual(p.nice(), psutil.NORMAL_PRIORITY_CLASS)
            finally:
                p.nice(psutil.NORMAL_PRIORITY_CLASS)
        else:
            first_nice = p.nice()
            try:
                if hasattr(os, "getpriority"):
                    self.assertEqual(
                        os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice())
                p.nice(1)
                self.assertEqual(p.nice(), 1)
                if hasattr(os, "getpriority"):
                    self.assertEqual(
                        os.getpriority(os.PRIO_PROCESS, os.getpid()), p.nice())
                # XXX - going back to previous nice value raises
                # AccessDenied on OSX
                if not OSX:
                    p.nice(0)
                    self.assertEqual(p.nice(), 0)
            except psutil.AccessDenied:
                pass
            finally:
                try:
                    p.nice(first_nice)
                except psutil.AccessDenied:
                    pass

    def test_status(self):
        p = psutil.Process()
        self.assertEqual(p.status(), psutil.STATUS_RUNNING)

    def test_username(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        username = p.username()
        if WINDOWS:
            domain, username = username.split('\\')
            self.assertEqual(username, getpass.getuser())
            if 'USERDOMAIN' in os.environ:
                self.assertEqual(domain, os.environ['USERDOMAIN'])
        else:
            self.assertEqual(username, getpass.getuser())

    def test_cwd(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        self.assertEqual(p.cwd(), os.getcwd())

    def test_cwd_2(self):
        cmd = [PYTHON_EXE, "-c",
               "import os, time; os.chdir('..'); time.sleep(60)"]
        sproc = get_test_subprocess(cmd)
        p = psutil.Process(sproc.pid)
        call_until(p.cwd, "ret == os.path.dirname(os.getcwd())")

    @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
    def test_cpu_affinity(self):
        p = psutil.Process()
        initial = p.cpu_affinity()
        assert initial, initial
        self.addCleanup(p.cpu_affinity, initial)

        if hasattr(os, "sched_getaffinity"):
            self.assertEqual(initial, list(os.sched_getaffinity(p.pid)))
        self.assertEqual(len(initial), len(set(initial)))

        all_cpus = list(range(len(psutil.cpu_percent(percpu=True))))
        # Work around travis failure:
        # https://travis-ci.org/giampaolo/psutil/builds/284173194
        for n in all_cpus if not TRAVIS else initial:
            p.cpu_affinity([n])
            self.assertEqual(p.cpu_affinity(), [n])
            if hasattr(os, "sched_getaffinity"):
                self.assertEqual(p.cpu_affinity(),
                                 list(os.sched_getaffinity(p.pid)))
            # also test num_cpu()
            if hasattr(p, "num_cpu"):
                self.assertEqual(p.cpu_affinity()[0], p.num_cpu())

        # [] is an alias for "all eligible CPUs"; on Linux this may
        # not be equal to all available CPUs, see:
        # https://github.com/giampaolo/psutil/issues/956
        p.cpu_affinity([])
        if LINUX:
            self.assertEqual(p.cpu_affinity(), p._proc._get_eligible_cpus())
        else:
            self.assertEqual(p.cpu_affinity(), all_cpus)
        if hasattr(os, "sched_getaffinity"):
            self.assertEqual(p.cpu_affinity(),
                             list(os.sched_getaffinity(p.pid)))
        #
        self.assertRaises(TypeError, p.cpu_affinity, 1)
        p.cpu_affinity(initial)
        # it should work with all iterables, not only lists
        p.cpu_affinity(set(all_cpus))
        p.cpu_affinity(tuple(all_cpus))

    @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
    def test_cpu_affinity_errs(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        invalid_cpu = [len(psutil.cpu_times(percpu=True)) + 10]
        self.assertRaises(ValueError, p.cpu_affinity, invalid_cpu)
        self.assertRaises(ValueError, p.cpu_affinity, range(10000, 11000))
        self.assertRaises(TypeError, p.cpu_affinity, [0, "1"])
        self.assertRaises(ValueError, p.cpu_affinity, [0, -1])

    @unittest.skipIf(not HAS_CPU_AFFINITY, 'not supported')
    def test_cpu_affinity_all_combinations(self):
        p = psutil.Process()
        initial = p.cpu_affinity()
        assert initial, initial
        self.addCleanup(p.cpu_affinity, initial)

        # All possible CPU set combinations.
        combos = []
        for l in range(0, len(initial) + 1):
            for subset in itertools.combinations(initial, l):
                if subset:
                    combos.append(list(subset))

        for combo in combos:
            p.cpu_affinity(combo)
            self.assertEqual(p.cpu_affinity(), combo)

    # TODO: #595
    @unittest.skipIf(BSD, "broken on BSD")
    # can't find any process file on Appveyor
    @unittest.skipIf(APPVEYOR, "unreliable on APPVEYOR")
    def test_open_files(self):
        # current process
        p = psutil.Process()
        files = p.open_files()
        self.assertFalse(TESTFN in files)
        with open(TESTFN, 'wb') as f:
            f.write(b'x' * 1024)
            f.flush()
            # give the kernel some time to see the new file
            files = call_until(p.open_files, "len(ret) != %i" % len(files))
            for file in files:
                if file.path == TESTFN:
                    if LINUX:
                        self.assertEqual(file.position, 1024)
                    break
            else:
                self.fail("no file found; files=%s" % repr(files))
        for file in files:
            assert os.path.isfile(file.path), file

        # another process
        cmdline = "import time; f = open(r'%s', 'r'); time.sleep(60);" % TESTFN
        sproc = get_test_subprocess([PYTHON_EXE, "-c", cmdline])
        p = psutil.Process(sproc.pid)

        for x in range(100):
            filenames = [x.path for x in p.open_files()]
            if TESTFN in filenames:
                break
            time.sleep(.01)
        else:
            self.assertIn(TESTFN, filenames)
        for file in filenames:
            assert os.path.isfile(file), file

    # TODO: #595
    @unittest.skipIf(BSD, "broken on BSD")
    # can't find any process file on Appveyor
    @unittest.skipIf(APPVEYOR, "unreliable on APPVEYOR")
    def test_open_files_2(self):
        # test fd and path fields
        with open(TESTFN, 'w') as fileobj:
            p = psutil.Process()
            for file in p.open_files():
                if file.path == fileobj.name or file.fd == fileobj.fileno():
                    break
            else:
                self.fail("no file found; files=%s" % repr(p.open_files()))
            self.assertEqual(file.path, fileobj.name)
            if WINDOWS:
                self.assertEqual(file.fd, -1)
            else:
                self.assertEqual(file.fd, fileobj.fileno())
            # test positions
            ntuple = p.open_files()[0]
            self.assertEqual(ntuple[0], ntuple.path)
            self.assertEqual(ntuple[1], ntuple.fd)
            # test file is gone
            self.assertNotIn(fileobj.name, p.open_files())

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_num_fds(self):
        p = psutil.Process()
        start = p.num_fds()
        file = open(TESTFN, 'w')
        self.addCleanup(file.close)
        self.assertEqual(p.num_fds(), start + 1)
        sock = socket.socket()
        self.addCleanup(sock.close)
        self.assertEqual(p.num_fds(), start + 2)
        file.close()
        sock.close()
        self.assertEqual(p.num_fds(), start)

    @skip_on_not_implemented(only_if=LINUX)
    @unittest.skipIf(OPENBSD or NETBSD, "not reliable on OPENBSD & NETBSD")
    def test_num_ctx_switches(self):
        p = psutil.Process()
        before = sum(p.num_ctx_switches())
        for x in range(500000):
            after = sum(p.num_ctx_switches())
            if after > before:
                return
        self.fail("num ctx switches still the same after 50.000 iterations")

    def test_ppid(self):
        if hasattr(os, 'getppid'):
            self.assertEqual(psutil.Process().ppid(), os.getppid())
        this_parent = os.getpid()
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        self.assertEqual(p.ppid(), this_parent)
        # no other process is supposed to have us as parent
        reap_children(recursive=True)
        if APPVEYOR:
            # Occasional failures, see:
            # https://ci.appveyor.com/project/giampaolo/psutil/build/
            #     job/0hs623nenj7w4m33
            return
        for p in psutil.process_iter():
            if p.pid == sproc.pid:
                continue
            # XXX: sometimes this fails on Windows; not sure why.
            self.assertNotEqual(p.ppid(), this_parent, msg=p)

    def test_parent(self):
        this_parent = os.getpid()
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        self.assertEqual(p.parent().pid, this_parent)

    def test_parent_disappeared(self):
        # Emulate a case where the parent process disappeared.
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        with mock.patch("psutil.Process",
                        side_effect=psutil.NoSuchProcess(0, 'foo')):
            self.assertIsNone(p.parent())

    def test_children(self):
        p = psutil.Process()
        self.assertEqual(p.children(), [])
        self.assertEqual(p.children(recursive=True), [])
        # On Windows we set the flag to 0 in order to cancel out the
        # CREATE_NO_WINDOW flag (enabled by default) which creates
        # an extra "conhost.exe" child.
        sproc = get_test_subprocess(creationflags=0)
        children1 = p.children()
        children2 = p.children(recursive=True)
        for children in (children1, children2):
            self.assertEqual(len(children), 1)
            self.assertEqual(children[0].pid, sproc.pid)
            self.assertEqual(children[0].ppid(), os.getpid())

    def test_children_recursive(self):
        # Test children() against two sub processes, p1 and p2, where
        # p1 (our child) spawned p2 (our grandchild).
        p1, p2 = create_proc_children_pair()
        p = psutil.Process()
        self.assertEqual(p.children(), [p1])
        self.assertEqual(p.children(recursive=True), [p1, p2])
        # If the intermediate process is gone there's no way for
        # children() to recursively find it.
        p1.terminate()
        p1.wait()
        self.assertEqual(p.children(recursive=True), [])

    def test_children_duplicates(self):
        # find the process which has the highest number of children
        table = collections.defaultdict(int)
        for p in psutil.process_iter():
            try:
                table[p.ppid()] += 1
            except psutil.Error:
                pass
        # this is the one, now let's make sure there are no duplicates
        pid = sorted(table.items(), key=lambda x: x[1])[-1][0]
        p = psutil.Process(pid)
        try:
            c = p.children(recursive=True)
        except psutil.AccessDenied:  # windows
            pass
        else:
            self.assertEqual(len(c), len(set(c)))

    def test_suspend_resume(self):
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        p.suspend()
        for x in range(100):
            if p.status() == psutil.STATUS_STOPPED:
                break
            time.sleep(0.01)
        p.resume()
        self.assertNotEqual(p.status(), psutil.STATUS_STOPPED)

    def test_invalid_pid(self):
        self.assertRaises(TypeError, psutil.Process, "1")
        self.assertRaises(ValueError, psutil.Process, -1)

    def test_as_dict(self):
        p = psutil.Process()
        d = p.as_dict(attrs=['exe', 'name'])
        self.assertEqual(sorted(d.keys()), ['exe', 'name'])

        p = psutil.Process(min(psutil.pids()))
        d = p.as_dict(attrs=['connections'], ad_value='foo')
        if not isinstance(d['connections'], list):
            self.assertEqual(d['connections'], 'foo')

        # Test ad_value is set on AccessDenied.
        with mock.patch('psutil.Process.nice', create=True,
                        side_effect=psutil.AccessDenied):
            self.assertEqual(
                p.as_dict(attrs=["nice"], ad_value=1), {"nice": 1})

        # Test that NoSuchProcess bubbles up.
        with mock.patch('psutil.Process.nice', create=True,
                        side_effect=psutil.NoSuchProcess(p.pid, "name")):
            self.assertRaises(
                psutil.NoSuchProcess, p.as_dict, attrs=["nice"])

        # Test that ZombieProcess is swallowed.
        with mock.patch('psutil.Process.nice', create=True,
                        side_effect=psutil.ZombieProcess(p.pid, "name")):
            self.assertEqual(
                p.as_dict(attrs=["nice"], ad_value="foo"), {"nice": "foo"})

        # By default APIs raising NotImplementedError are
        # supposed to be skipped.
        with mock.patch('psutil.Process.nice', create=True,
                        side_effect=NotImplementedError):
            d = p.as_dict()
            self.assertNotIn('nice', list(d.keys()))
            # ...unless the user explicitly asked for some attr.
            with self.assertRaises(NotImplementedError):
                p.as_dict(attrs=["nice"])

        # errors
        with self.assertRaises(TypeError):
            p.as_dict('name')
        with self.assertRaises(ValueError):
            p.as_dict(['foo'])
        with self.assertRaises(ValueError):
            p.as_dict(['foo', 'bar'])

    def test_oneshot(self):
        with mock.patch("psutil._psplatform.Process.cpu_times") as m:
            p = psutil.Process()
            with p.oneshot():
                p.cpu_times()
                p.cpu_times()
            self.assertEqual(m.call_count, 1)

        with mock.patch("psutil._psplatform.Process.cpu_times") as m:
            p.cpu_times()
            p.cpu_times()
        self.assertEqual(m.call_count, 2)

    def test_oneshot_twice(self):
        # Test the case where the ctx manager is __enter__ed twice.
        # The second __enter__ is supposed to resut in a NOOP.
        with mock.patch("psutil._psplatform.Process.cpu_times") as m1:
            with mock.patch("psutil._psplatform.Process.oneshot_enter") as m2:
                p = psutil.Process()
                with p.oneshot():
                    p.cpu_times()
                    p.cpu_times()
                    with p.oneshot():
                        p.cpu_times()
                        p.cpu_times()
                self.assertEqual(m1.call_count, 1)
                self.assertEqual(m2.call_count, 1)

        with mock.patch("psutil._psplatform.Process.cpu_times") as m:
            p.cpu_times()
            p.cpu_times()
        self.assertEqual(m.call_count, 2)

    def test_halfway_terminated_process(self):
        # Test that NoSuchProcess exception gets raised in case the
        # process dies after we create the Process object.
        # Example:
        #  >>> proc = Process(1234)
        # >>> time.sleep(2)  # time-consuming task, process dies in meantime
        #  >>> proc.name()
        # Refers to Issue #15
        sproc = get_test_subprocess()
        p = psutil.Process(sproc.pid)
        p.terminate()
        p.wait()
        if WINDOWS:
            call_until(psutil.pids, "%s not in ret" % p.pid)
        self.assertFalse(p.is_running())
        # self.assertFalse(p.pid in psutil.pids(), msg="retcode = %s" %
        #   retcode)

        excluded_names = ['pid', 'is_running', 'wait', 'create_time',
                          'oneshot', 'memory_info_ex']
        if LINUX and not HAS_RLIMIT:
            excluded_names.append('rlimit')
        for name in dir(p):
            if (name.startswith('_') or
                    name in excluded_names):
                continue
            try:
                meth = getattr(p, name)
                # get/set methods
                if name == 'nice':
                    if POSIX:
                        ret = meth(1)
                    else:
                        ret = meth(psutil.NORMAL_PRIORITY_CLASS)
                elif name == 'ionice':
                    ret = meth()
                    ret = meth(2)
                elif name == 'rlimit':
                    ret = meth(psutil.RLIMIT_NOFILE)
                    ret = meth(psutil.RLIMIT_NOFILE, (5, 5))
                elif name == 'cpu_affinity':
                    ret = meth()
                    ret = meth([0])
                elif name == 'send_signal':
                    ret = meth(signal.SIGTERM)
                else:
                    ret = meth()
            except psutil.ZombieProcess:
                self.fail("ZombieProcess for %r was not supposed to happen" %
                          name)
            except psutil.NoSuchProcess:
                pass
            except psutil.AccessDenied:
                if OPENBSD and name in ('threads', 'num_threads'):
                    pass
                else:
                    raise
            except NotImplementedError:
                pass
            else:
                self.fail(
                    "NoSuchProcess exception not raised for %r, retval=%s" % (
                        name, ret))

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_zombie_process(self):
        def succeed_or_zombie_p_exc(fun, *args, **kwargs):
            try:
                return fun(*args, **kwargs)
            except (psutil.ZombieProcess, psutil.AccessDenied):
                pass

        zpid = create_zombie_proc()
        self.addCleanup(reap_children, recursive=True)
        # A zombie process should always be instantiable
        zproc = psutil.Process(zpid)
        # ...and at least its status always be querable
        self.assertEqual(zproc.status(), psutil.STATUS_ZOMBIE)
        # ...and it should be considered 'running'
        self.assertTrue(zproc.is_running())
        # ...and as_dict() shouldn't crash
        zproc.as_dict()
        # if cmdline succeeds it should be an empty list
        ret = succeed_or_zombie_p_exc(zproc.suspend)
        if ret is not None:
            self.assertEqual(ret, [])

        if hasattr(zproc, "rlimit"):
            succeed_or_zombie_p_exc(zproc.rlimit, psutil.RLIMIT_NOFILE)
            succeed_or_zombie_p_exc(zproc.rlimit, psutil.RLIMIT_NOFILE,
                                    (5, 5))
        # set methods
        succeed_or_zombie_p_exc(zproc.parent)
        if hasattr(zproc, 'cpu_affinity'):
            try:
                succeed_or_zombie_p_exc(zproc.cpu_affinity, [0])
            except ValueError as err:
                if TRAVIS and LINUX and "not eligible" in str(err):
                    # https://travis-ci.org/giampaolo/psutil/jobs/279890461
                    pass
                else:
                    raise

        succeed_or_zombie_p_exc(zproc.nice, 0)
        if hasattr(zproc, 'ionice'):
            if LINUX:
                succeed_or_zombie_p_exc(zproc.ionice, 2, 0)
            else:
                succeed_or_zombie_p_exc(zproc.ionice, 0)  # Windows
        if hasattr(zproc, 'rlimit'):
            succeed_or_zombie_p_exc(zproc.rlimit,
                                    psutil.RLIMIT_NOFILE, (5, 5))
        succeed_or_zombie_p_exc(zproc.suspend)
        succeed_or_zombie_p_exc(zproc.resume)
        succeed_or_zombie_p_exc(zproc.terminate)
        succeed_or_zombie_p_exc(zproc.kill)

        # ...its parent should 'see' it
        # edit: not true on BSD and OSX
        # descendants = [x.pid for x in psutil.Process().children(
        #                recursive=True)]
        # self.assertIn(zpid, descendants)
        # XXX should we also assume ppid be usable?  Note: this
        # would be an important use case as the only way to get
        # rid of a zombie is to kill its parent.
        # self.assertEqual(zpid.ppid(), os.getpid())
        # ...and all other APIs should be able to deal with it
        self.assertTrue(psutil.pid_exists(zpid))
        if not TRAVIS and OSX:
            # For some reason this started failing all of the sudden.
            # Maybe they upgraded OSX version?
            # https://travis-ci.org/giampaolo/psutil/jobs/310896404
            self.assertIn(zpid, psutil.pids())
            self.assertIn(zpid, [x.pid for x in psutil.process_iter()])
            psutil._pmap = {}
            self.assertIn(zpid, [x.pid for x in psutil.process_iter()])

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_zombie_process_is_running_w_exc(self):
        # Emulate a case where internally is_running() raises
        # ZombieProcess.
        p = psutil.Process()
        with mock.patch("psutil.Process",
                        side_effect=psutil.ZombieProcess(0)) as m:
            assert p.is_running()
            assert m.called

    @unittest.skipIf(not POSIX, 'POSIX only')
    def test_zombie_process_status_w_exc(self):
        # Emulate a case where internally status() raises
        # ZombieProcess.
        p = psutil.Process()
        with mock.patch("psutil._psplatform.Process.status",
                        side_effect=psutil.ZombieProcess(0)) as m:
            self.assertEqual(p.status(), psutil.STATUS_ZOMBIE)
            assert m.called

    def test_pid_0(self):
        # Process(0) is supposed to work on all platforms except Linux
        if 0 not in psutil.pids():
            self.assertRaises(psutil.NoSuchProcess, psutil.Process, 0)
            return

        # test all methods
        p = psutil.Process(0)
        for name in psutil._as_dict_attrnames:
            if name == 'pid':
                continue
            meth = getattr(p, name)
            try:
                ret = meth()
            except psutil.AccessDenied:
                pass
            else:
                if name in ("uids", "gids"):
                    self.assertEqual(ret.real, 0)
                elif name == "username":
                    if POSIX:
                        self.assertEqual(p.username(), 'root')
                    elif WINDOWS:
                        self.assertEqual(p.username(), 'NT AUTHORITY\\SYSTEM')
                elif name == "name":
                    assert name, name

        if hasattr(p, 'rlimit'):
            try:
                p.rlimit(psutil.RLIMIT_FSIZE)
            except psutil.AccessDenied:
                pass

        p.as_dict()

        if not OPENBSD:
            self.assertIn(0, psutil.pids())
            self.assertTrue(psutil.pid_exists(0))

    @unittest.skipIf(not HAS_ENVIRON, "not supported")
    def test_environ(self):
        def clean_dict(d):
            # Most of these are problematic on Travis.
            d.pop("PSUTIL_TESTING", None)
            d.pop("PLAT", None)
            d.pop("HOME", None)
            if OSX:
                d.pop("__CF_USER_TEXT_ENCODING", None)
                d.pop("VERSIONER_PYTHON_PREFER_32_BIT", None)
                d.pop("VERSIONER_PYTHON_VERSION", None)
            return dict(
                [(k.rstrip("\r\n"), v.rstrip("\r\n")) for k, v in d.items()])

        self.maxDiff = None
        p = psutil.Process()
        d1 = clean_dict(p.environ())
        d2 = clean_dict(os.environ.copy())
        self.assertEqual(d1, d2)

    @unittest.skipIf(not HAS_ENVIRON, "not supported")
    @unittest.skipIf(not POSIX, "POSIX only")
    def test_weird_environ(self):
        # environment variables can contain values without an equals sign
        code = textwrap.dedent("""
            #include <unistd.h>
            #include <fcntl.h>
            char * const argv[] = {"cat", 0};
            char * const envp[] = {"A=1", "X", "C=3", 0};
            int main(void) {
                /* Close stderr on exec so parent can wait for the execve to
                 * finish. */
                if (fcntl(2, F_SETFD, FD_CLOEXEC) != 0)
                    return 0;
                return execve("/bin/cat", argv, envp);
            }
            """)
        path = TESTFN
        create_exe(path, c_code=code)
        self.addCleanup(safe_rmpath, path)
        sproc = get_test_subprocess([path],
                                    stdin=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
        p = psutil.Process(sproc.pid)
        wait_for_pid(p.pid)
        self.assertTrue(p.is_running())
        # Wait for process to exec or exit.
        self.assertEqual(sproc.stderr.read(), b"")
        self.assertEqual(p.environ(), {"A": "1", "C": "3"})
        sproc.communicate()
        self.assertEqual(sproc.returncode, 0)


# ===================================================================
# --- Limited user tests
# ===================================================================


if POSIX and os.getuid() == 0:
    class LimitedUserTestCase(TestProcess):
        """Repeat the previous tests by using a limited user.
        Executed only on UNIX and only if the user who run the test script
        is root.
        """
        # the uid/gid the test suite runs under
        if hasattr(os, 'getuid'):
            PROCESS_UID = os.getuid()
            PROCESS_GID = os.getgid()

        def __init__(self, *args, **kwargs):
            TestProcess.__init__(self, *args, **kwargs)
            # re-define all existent test methods in order to
            # ignore AccessDenied exceptions
            for attr in [x for x in dir(self) if x.startswith('test')]:
                meth = getattr(self, attr)

                def test_(self):
                    try:
                        meth()
                    except psutil.AccessDenied:
                        pass
                setattr(self, attr, types.MethodType(test_, self))

        def setUp(self):
            safe_rmpath(TESTFN)
            TestProcess.setUp(self)
            os.setegid(1000)
            os.seteuid(1000)

        def tearDown(self):
            os.setegid(self.PROCESS_UID)
            os.seteuid(self.PROCESS_GID)
            TestProcess.tearDown(self)

        def test_nice(self):
            try:
                psutil.Process().nice(-1)
            except psutil.AccessDenied:
                pass
            else:
                self.fail("exception not raised")

        def test_zombie_process(self):
            # causes problems if test test suite is run as root
            pass


# ===================================================================
# --- psutil.Popen tests
# ===================================================================


class TestPopen(unittest.TestCase):
    """Tests for psutil.Popen class."""

    def tearDown(self):
        reap_children()

    def test_misc(self):
        # XXX this test causes a ResourceWarning on Python 3 because
        # psutil.__subproc instance doesn't get propertly freed.
        # Not sure what to do though.
        cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
        with psutil.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as proc:
            proc.name()
            proc.cpu_times()
            proc.stdin
            self.assertTrue(dir(proc))
            self.assertRaises(AttributeError, getattr, proc, 'foo')
            proc.terminate()

    def test_ctx_manager(self):
        with psutil.Popen([PYTHON_EXE, "-V"],
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          stdin=subprocess.PIPE) as proc:
            proc.communicate()
        assert proc.stdout.closed
        assert proc.stderr.closed
        assert proc.stdin.closed
        self.assertEqual(proc.returncode, 0)

    def test_kill_terminate(self):
        # subprocess.Popen()'s terminate(), kill() and send_signal() do
        # not raise exception after the process is gone. psutil.Popen
        # diverges from that.
        cmd = [PYTHON_EXE, "-c", "import time; time.sleep(60);"]
        with psutil.Popen(cmd, stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE) as proc:
            proc.terminate()
            proc.wait()
            self.assertRaises(psutil.NoSuchProcess, proc.terminate)
            self.assertRaises(psutil.NoSuchProcess, proc.kill)
            self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                              signal.SIGTERM)
            if WINDOWS and sys.version_info >= (2, 7):
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_C_EVENT)
                self.assertRaises(psutil.NoSuchProcess, proc.send_signal,
                                  signal.CTRL_BREAK_EVENT)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_memory_leaks.py000064400000043475150466730550012036 0ustar00
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Tests for detecting function memory leaks (typically the ones
implemented in C). It does so by calling a function many times and
checking whether process memory usage keeps increasing between
calls or over time.
Note that this may produce false positives (especially on Windows
for some reason).
"""

from __future__ import print_function
import errno
import functools
import gc
import os
import sys
import threading
import time

import psutil
import psutil._common
from psutil import LINUX
from psutil import OPENBSD
from psutil import OSX
from psutil import POSIX
from psutil import SUNOS
from psutil import WINDOWS
from psutil._compat import xrange
from psutil.tests import create_sockets
from psutil.tests import get_test_subprocess
from psutil.tests import HAS_CPU_AFFINITY
from psutil.tests import HAS_CPU_FREQ
from psutil.tests import HAS_ENVIRON
from psutil.tests import HAS_IONICE
from psutil.tests import HAS_MEMORY_MAPS
from psutil.tests import HAS_PROC_CPU_NUM
from psutil.tests import HAS_PROC_IO_COUNTERS
from psutil.tests import HAS_RLIMIT
from psutil.tests import HAS_SENSORS_BATTERY
from psutil.tests import HAS_SENSORS_FANS
from psutil.tests import HAS_SENSORS_TEMPERATURES
from psutil.tests import reap_children
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_rmpath
from psutil.tests import skip_on_access_denied
from psutil.tests import TESTFN
from psutil.tests import TRAVIS
from psutil.tests import unittest


LOOPS = 1000
MEMORY_TOLERANCE = 4096
RETRY_FOR = 3

SKIP_PYTHON_IMPL = True if TRAVIS else False
cext = psutil._psplatform.cext
thisproc = psutil.Process()
SKIP_PYTHON_IMPL = True if TRAVIS else False


# ===================================================================
# utils
# ===================================================================


def skip_if_linux():
    return unittest.skipIf(LINUX and SKIP_PYTHON_IMPL,
                           "worthless on LINUX (pure python)")


def bytes2human(n):
    """
    http://code.activestate.com/recipes/578019
    >>> bytes2human(10000)
    '9.8K'
    >>> bytes2human(100001221)
    '95.4M'
    """
    symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
    prefix = {}
    for i, s in enumerate(symbols):
        prefix[s] = 1 << (i + 1) * 10
    for s in reversed(symbols):
        if n >= prefix[s]:
            value = float(n) / prefix[s]
            return '%.2f%s' % (value, s)
    return "%sB" % n


class TestMemLeak(unittest.TestCase):
    """Base framework class which calls a function many times and
    produces a failure if process memory usage keeps increasing
    between calls or over time.
    """
    tolerance = MEMORY_TOLERANCE
    loops = LOOPS
    retry_for = RETRY_FOR

    def setUp(self):
        gc.collect()

    def execute(self, fun, *args, **kwargs):
        """Test a callable."""
        def call_many_times():
            for x in xrange(loops):
                self._call(fun, *args, **kwargs)
            del x
            gc.collect()

        tolerance = kwargs.pop('tolerance_', None) or self.tolerance
        loops = kwargs.pop('loops_', None) or self.loops
        retry_for = kwargs.pop('retry_for_', None) or self.retry_for

        # warm up
        for x in range(10):
            self._call(fun, *args, **kwargs)
        self.assertEqual(gc.garbage, [])
        self.assertEqual(threading.active_count(), 1)
        self.assertEqual(thisproc.children(), [])

        # Get 2 distinct memory samples, before and after having
        # called fun repeadetly.
        # step 1
        call_many_times()
        mem1 = self._get_mem()
        # step 2
        call_many_times()
        mem2 = self._get_mem()

        diff1 = mem2 - mem1
        if diff1 > tolerance:
            # This doesn't necessarily mean we have a leak yet.
            # At this point we assume that after having called the
            # function so many times the memory usage is stabilized
            # and if there are no leaks it should not increase
            # anymore.
            # Let's keep calling fun for 3 more seconds and fail if
            # we notice any difference.
            ncalls = 0
            stop_at = time.time() + retry_for
            while time.time() <= stop_at:
                self._call(fun, *args, **kwargs)
                ncalls += 1

            del stop_at
            gc.collect()
            mem3 = self._get_mem()
            diff2 = mem3 - mem2

            if mem3 > mem2:
                # failure
                extra_proc_mem = bytes2human(diff1 + diff2)
                print("exta proc mem: %s" % extra_proc_mem, file=sys.stderr)
                msg = "+%s after %s calls, +%s after another %s calls, "
                msg += "+%s extra proc mem"
                msg = msg % (
                    bytes2human(diff1), loops, bytes2human(diff2), ncalls,
                    extra_proc_mem)
                self.fail(msg)

    def execute_w_exc(self, exc, fun, *args, **kwargs):
        """Convenience function which tests a callable raising
        an exception.
        """
        def call():
            self.assertRaises(exc, fun, *args, **kwargs)

        self.execute(call)

    @staticmethod
    def _get_mem():
        # By using USS memory it seems it's less likely to bump
        # into false positives.
        if LINUX or WINDOWS or OSX:
            return thisproc.memory_full_info().uss
        else:
            return thisproc.memory_info().rss

    @staticmethod
    def _call(fun, *args, **kwargs):
        fun(*args, **kwargs)


# ===================================================================
# Process class
# ===================================================================


class TestProcessObjectLeaks(TestMemLeak):
    """Test leaks of Process class methods."""

    proc = thisproc

    def test_coverage(self):
        skip = set((
            "pid", "as_dict", "children", "cpu_affinity", "cpu_percent",
            "ionice", "is_running", "kill", "memory_info_ex", "memory_percent",
            "nice", "oneshot", "parent", "rlimit", "send_signal", "suspend",
            "terminate", "wait"))
        for name in dir(psutil.Process):
            if name.startswith('_'):
                continue
            if name in skip:
                continue
            self.assertTrue(hasattr(self, "test_" + name), msg=name)

    @skip_if_linux()
    def test_name(self):
        self.execute(self.proc.name)

    @skip_if_linux()
    def test_cmdline(self):
        self.execute(self.proc.cmdline)

    @skip_if_linux()
    def test_exe(self):
        self.execute(self.proc.exe)

    @skip_if_linux()
    def test_ppid(self):
        self.execute(self.proc.ppid)

    @unittest.skipIf(not POSIX, "POSIX only")
    @skip_if_linux()
    def test_uids(self):
        self.execute(self.proc.uids)

    @unittest.skipIf(not POSIX, "POSIX only")
    @skip_if_linux()
    def test_gids(self):
        self.execute(self.proc.gids)

    @skip_if_linux()
    def test_status(self):
        self.execute(self.proc.status)

    def test_nice_get(self):
        self.execute(self.proc.nice)

    def test_nice_set(self):
        niceness = thisproc.nice()
        self.execute(self.proc.nice, niceness)

    @unittest.skipIf(not HAS_IONICE, "not supported")
    def test_ionice_get(self):
        self.execute(self.proc.ionice)

    @unittest.skipIf(not HAS_IONICE, "not supported")
    def test_ionice_set(self):
        if WINDOWS:
            value = thisproc.ionice()
            self.execute(self.proc.ionice, value)
        else:
            self.execute(self.proc.ionice, psutil.IOPRIO_CLASS_NONE)
            fun = functools.partial(cext.proc_ioprio_set, os.getpid(), -1, 0)
            self.execute_w_exc(OSError, fun)

    @unittest.skipIf(not HAS_PROC_IO_COUNTERS, "not supported")
    @skip_if_linux()
    def test_io_counters(self):
        self.execute(self.proc.io_counters)

    @unittest.skipIf(POSIX, "worthless on POSIX")
    def test_username(self):
        self.execute(self.proc.username)

    @skip_if_linux()
    def test_create_time(self):
        self.execute(self.proc.create_time)

    @skip_if_linux()
    @skip_on_access_denied(only_if=OPENBSD)
    def test_num_threads(self):
        self.execute(self.proc.num_threads)

    @unittest.skipIf(not WINDOWS, "WINDOWS only")
    def test_num_handles(self):
        self.execute(self.proc.num_handles)

    @unittest.skipIf(not POSIX, "POSIX only")
    @skip_if_linux()
    def test_num_fds(self):
        self.execute(self.proc.num_fds)

    @skip_if_linux()
    def test_num_ctx_switches(self):
        self.execute(self.proc.num_ctx_switches)

    @skip_if_linux()
    @skip_on_access_denied(only_if=OPENBSD)
    def test_threads(self):
        self.execute(self.proc.threads)

    @skip_if_linux()
    def test_cpu_times(self):
        self.execute(self.proc.cpu_times)

    @skip_if_linux()
    @unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported")
    def test_cpu_num(self):
        self.execute(self.proc.cpu_num)

    @skip_if_linux()
    def test_memory_info(self):
        self.execute(self.proc.memory_info)

    @skip_if_linux()
    def test_memory_full_info(self):
        self.execute(self.proc.memory_full_info)

    @unittest.skipIf(not POSIX, "POSIX only")
    @skip_if_linux()
    def test_terminal(self):
        self.execute(self.proc.terminal)

    @unittest.skipIf(POSIX and SKIP_PYTHON_IMPL,
                     "worthless on POSIX (pure python)")
    def test_resume(self):
        self.execute(self.proc.resume)

    @skip_if_linux()
    def test_cwd(self):
        self.execute(self.proc.cwd)

    @unittest.skipIf(not HAS_CPU_AFFINITY, "not supported")
    def test_cpu_affinity_get(self):
        self.execute(self.proc.cpu_affinity)

    @unittest.skipIf(not HAS_CPU_AFFINITY, "not supported")
    def test_cpu_affinity_set(self):
        affinity = thisproc.cpu_affinity()
        self.execute(self.proc.cpu_affinity, affinity)
        if not TRAVIS:
            self.execute_w_exc(ValueError, self.proc.cpu_affinity, [-1])

    @skip_if_linux()
    def test_open_files(self):
        safe_rmpath(TESTFN)  # needed after UNIX socket test has run
        with open(TESTFN, 'w'):
            self.execute(self.proc.open_files)

    # OSX implementation is unbelievably slow
    @unittest.skipIf(OSX, "too slow on OSX")
    @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
    @skip_if_linux()
    def test_memory_maps(self):
        self.execute(self.proc.memory_maps)

    @unittest.skipIf(not LINUX, "LINUX only")
    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit_get(self):
        self.execute(self.proc.rlimit, psutil.RLIMIT_NOFILE)

    @unittest.skipIf(not LINUX, "LINUX only")
    @unittest.skipIf(not HAS_RLIMIT, "not supported")
    def test_rlimit_set(self):
        limit = thisproc.rlimit(psutil.RLIMIT_NOFILE)
        self.execute(self.proc.rlimit, psutil.RLIMIT_NOFILE, limit)
        self.execute_w_exc(OSError, self.proc.rlimit, -1)

    @skip_if_linux()
    # Windows implementation is based on a single system-wide
    # function (tested later).
    @unittest.skipIf(WINDOWS, "worthless on WINDOWS")
    def test_connections(self):
        # TODO: UNIX sockets are temporarily implemented by parsing
        # 'pfiles' cmd  output; we don't want that part of the code to
        # be executed.
        with create_sockets():
            kind = 'inet' if SUNOS else 'all'
            self.execute(self.proc.connections, kind)

    @unittest.skipIf(not HAS_ENVIRON, "not supported")
    def test_environ(self):
        self.execute(self.proc.environ)

    @unittest.skipIf(not WINDOWS, "WINDOWS only")
    def test_proc_info(self):
        self.execute(cext.proc_info, os.getpid())


class TestTerminatedProcessLeaks(TestProcessObjectLeaks):
    """Repeat the tests above looking for leaks occurring when dealing
    with terminated processes raising NoSuchProcess exception.
    The C functions are still invoked but will follow different code
    paths. We'll check those code paths.
    """

    @classmethod
    def setUpClass(cls):
        super(TestTerminatedProcessLeaks, cls).setUpClass()
        p = get_test_subprocess()
        cls.proc = psutil.Process(p.pid)
        cls.proc.kill()
        cls.proc.wait()

    @classmethod
    def tearDownClass(cls):
        super(TestTerminatedProcessLeaks, cls).tearDownClass()
        reap_children()

    def _call(self, fun, *args, **kwargs):
        try:
            fun(*args, **kwargs)
        except psutil.NoSuchProcess:
            pass

    if WINDOWS:

        def test_kill(self):
            self.execute(self.proc.kill)

        def test_terminate(self):
            self.execute(self.proc.terminate)

        def test_suspend(self):
            self.execute(self.proc.suspend)

        def test_resume(self):
            self.execute(self.proc.resume)

        def test_wait(self):
            self.execute(self.proc.wait)

        def test_proc_info(self):
            # test dual implementation
            def call():
                try:
                    return cext.proc_info(self.proc.pid)
                except OSError as err:
                    if err.errno != errno.ESRCH:
                        raise

            self.execute(call)


# ===================================================================
# system APIs
# ===================================================================


class TestModuleFunctionsLeaks(TestMemLeak):
    """Test leaks of psutil module functions."""

    def test_coverage(self):
        skip = set((
            "version_info", "__version__", "process_iter", "wait_procs",
            "cpu_percent", "cpu_times_percent", "cpu_count"))
        for name in psutil.__all__:
            if not name.islower():
                continue
            if name in skip:
                continue
            self.assertTrue(hasattr(self, "test_" + name), msg=name)

    # --- cpu

    @skip_if_linux()
    def test_cpu_count_logical(self):
        self.execute(psutil.cpu_count, logical=True)

    @skip_if_linux()
    def test_cpu_count_physical(self):
        self.execute(psutil.cpu_count, logical=False)

    @skip_if_linux()
    def test_cpu_times(self):
        self.execute(psutil.cpu_times)

    @skip_if_linux()
    def test_per_cpu_times(self):
        self.execute(psutil.cpu_times, percpu=True)

    def test_cpu_stats(self):
        self.execute(psutil.cpu_stats)

    @skip_if_linux()
    @unittest.skipIf(not HAS_CPU_FREQ, "not supported")
    def test_cpu_freq(self):
        self.execute(psutil.cpu_freq)

    # --- mem

    def test_virtual_memory(self):
        self.execute(psutil.virtual_memory)

    # TODO: remove this skip when this gets fixed
    @unittest.skipIf(SUNOS,
                     "worthless on SUNOS (uses a subprocess)")
    def test_swap_memory(self):
        self.execute(psutil.swap_memory)

    @unittest.skipIf(POSIX and SKIP_PYTHON_IMPL,
                     "worthless on POSIX (pure python)")
    def test_pid_exists(self):
        self.execute(psutil.pid_exists, os.getpid())

    # --- disk

    @unittest.skipIf(POSIX and SKIP_PYTHON_IMPL,
                     "worthless on POSIX (pure python)")
    def test_disk_usage(self):
        self.execute(psutil.disk_usage, '.')

    def test_disk_partitions(self):
        self.execute(psutil.disk_partitions)

    @unittest.skipIf(LINUX and not os.path.exists('/proc/diskstats'),
                     '/proc/diskstats not available on this Linux version')
    @skip_if_linux()
    def test_disk_io_counters(self):
        self.execute(psutil.disk_io_counters, nowrap=False)

    # --- proc

    @skip_if_linux()
    def test_pids(self):
        self.execute(psutil.pids)

    # --- net

    @skip_if_linux()
    def test_net_io_counters(self):
        self.execute(psutil.net_io_counters, nowrap=False)

    @unittest.skipIf(LINUX,
                     "worthless on Linux (pure python)")
    @unittest.skipIf(OSX and os.getuid() != 0, "need root access")
    def test_net_connections(self):
        with create_sockets():
            self.execute(psutil.net_connections)

    def test_net_if_addrs(self):
        # Note: verified that on Windows this was a false positive.
        self.execute(psutil.net_if_addrs,
                     tolerance_=80 * 1024 if WINDOWS else None)

    @unittest.skipIf(TRAVIS, "EPERM on travis")
    def test_net_if_stats(self):
        self.execute(psutil.net_if_stats)

    # --- sensors

    @skip_if_linux()
    @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
    def test_sensors_battery(self):
        self.execute(psutil.sensors_battery)

    @skip_if_linux()
    @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
    def test_sensors_temperatures(self):
        self.execute(psutil.sensors_temperatures)

    @skip_if_linux()
    @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
    def test_sensors_fans(self):
        self.execute(psutil.sensors_fans)

    # --- others

    @skip_if_linux()
    def test_boot_time(self):
        self.execute(psutil.boot_time)

    # XXX - on Windows this produces a false positive
    @unittest.skipIf(WINDOWS, "XXX produces a false positive on Windows")
    def test_users(self):
        self.execute(psutil.users)

    if WINDOWS:

        # --- win services

        def test_win_service_iter(self):
            self.execute(cext.winservice_enumerate)

        def test_win_service_get(self):
            pass

        def test_win_service_get_config(self):
            name = next(psutil.win_service_iter()).name()
            self.execute(cext.winservice_query_config, name)

        def test_win_service_get_status(self):
            name = next(psutil.win_service_iter()).name()
            self.execute(cext.winservice_query_status, name)

        def test_win_service_get_description(self):
            name = next(psutil.win_service_iter()).name()
            self.execute(cext.winservice_query_descr, name)


if __name__ == '__main__':
    run_test_module_by_name(__file__)
tests/test_misc.py000064400000111647150466730550010277 0ustar00# -*- coding: utf-8 -*-

# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
Miscellaneous tests.
"""

import ast
import collections
import contextlib
import errno
import json
import os
import pickle
import socket
import stat

from psutil import LINUX
from psutil import POSIX
from psutil import WINDOWS
from psutil._common import memoize
from psutil._common import memoize_when_activated
from psutil._common import supports_ipv6
from psutil._common import wrap_numbers
from psutil._compat import PY3
from psutil.tests import APPVEYOR
from psutil.tests import bind_socket
from psutil.tests import bind_unix_socket
from psutil.tests import call_until
from psutil.tests import chdir
from psutil.tests import create_proc_children_pair
from psutil.tests import create_sockets
from psutil.tests import create_zombie_proc
from psutil.tests import DEVNULL
from psutil.tests import get_free_port
from psutil.tests import get_test_subprocess
from psutil.tests import HAS_BATTERY
from psutil.tests import HAS_CONNECTIONS_UNIX
from psutil.tests import HAS_MEMORY_FULL_INFO
from psutil.tests import HAS_MEMORY_MAPS
from psutil.tests import HAS_SENSORS_BATTERY
from psutil.tests import HAS_SENSORS_FANS
from psutil.tests import HAS_SENSORS_TEMPERATURES
from psutil.tests import import_module_by_path
from psutil.tests import is_namedtuple
from psutil.tests import mock
from psutil.tests import PYTHON_EXE
from psutil.tests import reap_children
from psutil.tests import reload_module
from psutil.tests import retry
from psutil.tests import ROOT_DIR
from psutil.tests import run_test_module_by_name
from psutil.tests import safe_rmpath
from psutil.tests import SCRIPTS_DIR
from psutil.tests import sh
from psutil.tests import tcp_socketpair
from psutil.tests import TESTFN
from psutil.tests import TOX
from psutil.tests import TRAVIS
from psutil.tests import unittest
from psutil.tests import unix_socket_path
from psutil.tests import unix_socketpair
from psutil.tests import wait_for_file
from psutil.tests import wait_for_pid
import psutil
import psutil.tests


# ===================================================================
# --- Misc / generic tests.
# ===================================================================


class TestMisc(unittest.TestCase):

    def test_process__repr__(self, func=repr):
        p = psutil.Process()
        r = func(p)
        self.assertIn("psutil.Process", r)
        self.assertIn("pid=%s" % p.pid, r)
        self.assertIn("name=", r)
        self.assertIn(p.name(), r)
        with mock.patch.object(psutil.Process, "name",
                               side_effect=psutil.ZombieProcess(os.getpid())):
            p = psutil.Process()
            r = func(p)
            self.assertIn("pid=%s" % p.pid, r)
            self.assertIn("zombie", r)
            self.assertNotIn("name=", r)
        with mock.patch.object(psutil.Process, "name",
                               side_effect=psutil.NoSuchProcess(os.getpid())):
            p = psutil.Process()
            r = func(p)
            self.assertIn("pid=%s" % p.pid, r)
            self.assertIn("terminated", r)
            self.assertNotIn("name=", r)
        with mock.patch.object(psutil.Process, "name",
                               side_effect=psutil.AccessDenied(os.getpid())):
            p = psutil.Process()
            r = func(p)
            self.assertIn("pid=%s" % p.pid, r)
            self.assertNotIn("name=", r)

    def test_process__str__(self):
        self.test_process__repr__(func=str)

    def test_no_such_process__repr__(self, func=repr):
        self.assertEqual(
            repr(psutil.NoSuchProcess(321)),
            "psutil.NoSuchProcess process no longer exists (pid=321)")
        self.assertEqual(
            repr(psutil.NoSuchProcess(321, name='foo')),
            "psutil.NoSuchProcess process no longer exists (pid=321, "
            "name='foo')")
        self.assertEqual(
            repr(psutil.NoSuchProcess(321, msg='foo')),
            "psutil.NoSuchProcess foo")

    def test_zombie_process__repr__(self, func=repr):
        self.assertEqual(
            repr(psutil.ZombieProcess(321)),
            "psutil.ZombieProcess process still exists but it's a zombie "
            "(pid=321)")
        self.assertEqual(
            repr(psutil.ZombieProcess(321, name='foo')),
            "psutil.ZombieProcess process still exists but it's a zombie "
            "(pid=321, name='foo')")
        self.assertEqual(
            repr(psutil.ZombieProcess(321, name='foo', ppid=1)),
            "psutil.ZombieProcess process still exists but it's a zombie "
            "(pid=321, name='foo', ppid=1)")
        self.assertEqual(
            repr(psutil.ZombieProcess(321, msg='foo')),
            "psutil.ZombieProcess foo")

    def test_access_denied__repr__(self, func=repr):
        self.assertEqual(
            repr(psutil.AccessDenied(321)),
            "psutil.AccessDenied (pid=321)")
        self.assertEqual(
            repr(psutil.AccessDenied(321, name='foo')),
            "psutil.AccessDenied (pid=321, name='foo')")
        self.assertEqual(
            repr(psutil.AccessDenied(321, msg='foo')),
            "psutil.AccessDenied foo")

    def test_timeout_expired__repr__(self, func=repr):
        self.assertEqual(
            repr(psutil.TimeoutExpired(321)),
            "psutil.TimeoutExpired timeout after 321 seconds")
        self.assertEqual(
            repr(psutil.TimeoutExpired(321, pid=111)),
            "psutil.TimeoutExpired timeout after 321 seconds (pid=111)")
        self.assertEqual(
            repr(psutil.TimeoutExpired(321, pid=111, name='foo')),
            "psutil.TimeoutExpired timeout after 321 seconds "
            "(pid=111, name='foo')")

    def test_process__eq__(self):
        p1 = psutil.Process()
        p2 = psutil.Process()
        self.assertEqual(p1, p2)
        p2._ident = (0, 0)
        self.assertNotEqual(p1, p2)
        self.assertNotEqual(p1, 'foo')

    def test_process__hash__(self):
        s = set([psutil.Process(), psutil.Process()])
        self.assertEqual(len(s), 1)

    def test__all__(self):
        dir_psutil = dir(psutil)
        for name in dir_psutil:
            if name in ('callable', 'error', 'namedtuple', 'tests',
                        'long', 'test', 'NUM_CPUS', 'BOOT_TIME',
                        'TOTAL_PHYMEM'):
                continue
            if not name.startswith('_'):
                try:
                    __import__(name)
                except ImportError:
                    if name not in psutil.__all__:
                        fun = getattr(psutil, name)
                        if fun is None:
                            continue
                        if (fun.__doc__ is not None and
                                'deprecated' not in fun.__doc__.lower()):
                            self.fail('%r not in psutil.__all__' % name)

        # Import 'star' will break if __all__ is inconsistent, see:
        # https://github.com/giampaolo/psutil/issues/656
        # Can't do `from psutil import *` as it won't work on python 3
        # so we simply iterate over __all__.
        for name in psutil.__all__:
            self.assertIn(name, dir_psutil)

    def test_version(self):
        self.assertEqual('.'.join([str(x) for x in psutil.version_info]),
                         psutil.__version__)

    def test_process_as_dict_no_new_names(self):
        # See https://github.com/giampaolo/psutil/issues/813
        p = psutil.Process()
        p.foo = '1'
        self.assertNotIn('foo', p.as_dict())

    def test_memoize(self):
        @memoize
        def foo(*args, **kwargs):
            "foo docstring"
            calls.append(None)
            return (args, kwargs)

        calls = []
        # no args
        for x in range(2):
            ret = foo()
            expected = ((), {})
            self.assertEqual(ret, expected)
            self.assertEqual(len(calls), 1)
        # with args
        for x in range(2):
            ret = foo(1)
            expected = ((1, ), {})
            self.assertEqual(ret, expected)
            self.assertEqual(len(calls), 2)
        # with args + kwargs
        for x in range(2):
            ret = foo(1, bar=2)
            expected = ((1, ), {'bar': 2})
            self.assertEqual(ret, expected)
            self.assertEqual(len(calls), 3)
        # clear cache
        foo.cache_clear()
        ret = foo()
        expected = ((), {})
        self.assertEqual(ret, expected)
        self.assertEqual(len(calls), 4)
        # docstring
        self.assertEqual(foo.__doc__, "foo docstring")

    def test_memoize_when_activated(self):
        class Foo:

            @memoize_when_activated
            def foo(self):
                calls.append(None)

        f = Foo()
        calls = []
        f.foo()
        f.foo()
        self.assertEqual(len(calls), 2)

        # activate
        calls = []
        f.foo.cache_activate()
        f.foo()
        f.foo()
        self.assertEqual(len(calls), 1)

        # deactivate
        calls = []
        f.foo.cache_deactivate()
        f.foo()
        f.foo()
        self.assertEqual(len(calls), 2)

    def test_parse_environ_block(self):
        from psutil._common import parse_environ_block

        def k(s):
            return s.upper() if WINDOWS else s

        self.assertEqual(parse_environ_block("a=1\0"),
                         {k("a"): "1"})
        self.assertEqual(parse_environ_block("a=1\0b=2\0\0"),
                         {k("a"): "1", k("b"): "2"})
        self.assertEqual(parse_environ_block("a=1\0b=\0\0"),
                         {k("a"): "1", k("b"): ""})
        # ignore everything after \0\0
        self.assertEqual(parse_environ_block("a=1\0b=2\0\0c=3\0"),
                         {k("a"): "1", k("b"): "2"})
        # ignore everything that is not an assignment
        self.assertEqual(parse_environ_block("xxx\0a=1\0"), {k("a"): "1"})
        self.assertEqual(parse_environ_block("a=1\0=b=2\0"), {k("a"): "1"})
        # do not fail if the block is incomplete
        self.assertEqual(parse_environ_block("a=1\0b=2"), {k("a"): "1"})

    def test_supports_ipv6(self):
        self.addCleanup(supports_ipv6.cache_clear)
        if supports_ipv6():
            with mock.patch('psutil._common.socket') as s:
                s.has_ipv6 = False
                supports_ipv6.cache_clear()
                assert not supports_ipv6()

            supports_ipv6.cache_clear()
            with mock.patch('psutil._common.socket.socket',
                            side_effect=socket.error) as s:
                assert not supports_ipv6()
                assert s.called

            supports_ipv6.cache_clear()
            with mock.patch('psutil._common.socket.socket',
                            side_effect=socket.gaierror) as s:
                assert not supports_ipv6()
                supports_ipv6.cache_clear()
                assert s.called

            supports_ipv6.cache_clear()
            with mock.patch('psutil._common.socket.socket.bind',
                            side_effect=socket.gaierror) as s:
                assert not supports_ipv6()
                supports_ipv6.cache_clear()
                assert s.called
        else:
            with self.assertRaises(Exception):
                sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
                sock.bind(("::1", 0))

    def test_isfile_strict(self):
        from psutil._common import isfile_strict
        this_file = os.path.abspath(__file__)
        assert isfile_strict(this_file)
        assert not isfile_strict(os.path.dirname(this_file))
        with mock.patch('psutil._common.os.stat',
                        side_effect=OSError(errno.EPERM, "foo")):
            self.assertRaises(OSError, isfile_strict, this_file)
        with mock.patch('psutil._common.os.stat',
                        side_effect=OSError(errno.EACCES, "foo")):
            self.assertRaises(OSError, isfile_strict, this_file)
        with mock.patch('psutil._common.os.stat',
                        side_effect=OSError(errno.EINVAL, "foo")):
            assert not isfile_strict(this_file)
        with mock.patch('psutil._common.stat.S_ISREG', return_value=False):
            assert not isfile_strict(this_file)

    def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users())

    def test_setup_script(self):
        setup_py = os.path.join(ROOT_DIR, 'setup.py')
        if TRAVIS and not os.path.exists(setup_py):
            return self.skipTest("can't find setup.py")
        module = import_module_by_path(setup_py)
        self.assertRaises(SystemExit, module.setup)
        self.assertEqual(module.get_version(), psutil.__version__)

    def test_ad_on_process_creation(self):
        # We are supposed to be able to instantiate Process also in case
        # of zombie processes or access denied.
        with mock.patch.object(psutil.Process, 'create_time',
                               side_effect=psutil.AccessDenied) as meth:
            psutil.Process()
            assert meth.called
        with mock.patch.object(psutil.Process, 'create_time',
                               side_effect=psutil.ZombieProcess(1)) as meth:
            psutil.Process()
            assert meth.called
        with mock.patch.object(psutil.Process, 'create_time',
                               side_effect=ValueError) as meth:
            with self.assertRaises(ValueError):
                psutil.Process()
            assert meth.called

    def test_sanity_version_check(self):
        # see: https://github.com/giampaolo/psutil/issues/564
        with mock.patch(
                "psutil._psplatform.cext.version", return_value="0.0.0"):
            with self.assertRaises(ImportError) as cm:
                reload_module(psutil)
            self.assertIn("version conflict", str(cm.exception).lower())


# ===================================================================
# --- Tests for wrap_numbers() function.
# ===================================================================


nt = collections.namedtuple('foo', 'a b c')


class TestWrapNumbers(unittest.TestCase):

    def setUp(self):
        wrap_numbers.cache_clear()

    tearDown = setUp

    def test_first_call(self):
        input = {'disk1': nt(5, 5, 5)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)

    def test_input_hasnt_changed(self):
        input = {'disk1': nt(5, 5, 5)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)

    def test_increase_but_no_wrap(self):
        input = {'disk1': nt(5, 5, 5)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        input = {'disk1': nt(10, 15, 20)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        input = {'disk1': nt(20, 25, 30)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        input = {'disk1': nt(20, 25, 30)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)

    def test_wrap(self):
        # let's say 100 is the threshold
        input = {'disk1': nt(100, 100, 100)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        # first wrap restarts from 10
        input = {'disk1': nt(100, 100, 10)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(100, 100, 110)})
        # then it remains the same
        input = {'disk1': nt(100, 100, 10)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(100, 100, 110)})
        # then it goes up
        input = {'disk1': nt(100, 100, 90)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(100, 100, 190)})
        # then it wraps again
        input = {'disk1': nt(100, 100, 20)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(100, 100, 210)})
        # and remains the same
        input = {'disk1': nt(100, 100, 20)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(100, 100, 210)})
        # now wrap another num
        input = {'disk1': nt(50, 100, 20)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(150, 100, 210)})
        # and again
        input = {'disk1': nt(40, 100, 20)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(190, 100, 210)})
        # keep it the same
        input = {'disk1': nt(40, 100, 20)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(190, 100, 210)})

    def test_changing_keys(self):
        # Emulate a case where the second call to disk_io()
        # (or whatever) provides a new disk, then the new disk
        # disappears on the third call.
        input = {'disk1': nt(5, 5, 5)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        input = {'disk1': nt(5, 5, 5),
                 'disk2': nt(7, 7, 7)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        input = {'disk1': nt(8, 8, 8)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)

    def test_changing_keys_w_wrap(self):
        input = {'disk1': nt(50, 50, 50),
                 'disk2': nt(100, 100, 100)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        # disk 2 wraps
        input = {'disk1': nt(50, 50, 50),
                 'disk2': nt(100, 100, 10)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(50, 50, 50),
                          'disk2': nt(100, 100, 110)})
        # disk 2 disappears
        input = {'disk1': nt(50, 50, 50)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)

        # then it appears again; the old wrap is supposed to be
        # gone.
        input = {'disk1': nt(50, 50, 50),
                 'disk2': nt(100, 100, 100)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        # remains the same
        input = {'disk1': nt(50, 50, 50),
                 'disk2': nt(100, 100, 100)}
        self.assertEqual(wrap_numbers(input, 'disk_io'), input)
        # and then wraps again
        input = {'disk1': nt(50, 50, 50),
                 'disk2': nt(100, 100, 10)}
        self.assertEqual(wrap_numbers(input, 'disk_io'),
                         {'disk1': nt(50, 50, 50),
                          'disk2': nt(100, 100, 110)})

    def test_real_data(self):
        d = {'nvme0n1': (300, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048),
             'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8),
             'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28),
             'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348)}
        self.assertEqual(wrap_numbers(d, 'disk_io'), d)
        self.assertEqual(wrap_numbers(d, 'disk_io'), d)
        # decrease this   ↓
        d = {'nvme0n1': (100, 508, 640, 1571, 5970, 1987, 2049, 451751, 47048),
             'nvme0n1p1': (1171, 2, 5600256, 1024, 516, 0, 0, 0, 8),
             'nvme0n1p2': (54, 54, 2396160, 5165056, 4, 24, 30, 1207, 28),
             'nvme0n1p3': (2389, 4539, 5154, 150, 4828, 1844, 2019, 398, 348)}
        out = wrap_numbers(d, 'disk_io')
        self.assertEqual(out['nvme0n1'][0], 400)

    # --- cache tests

    def test_cache_first_call(self):
        input = {'disk1': nt(5, 5, 5)}
        wrap_numbers(input, 'disk_io')
        cache = wrap_numbers.cache_info()
        self.assertEqual(cache[0], {'disk_io': input})
        self.assertEqual(cache[1], {'disk_io': {}})
        self.assertEqual(cache[2], {'disk_io': {}})

    def test_cache_call_twice(self):
        input = {'disk1': nt(5, 5, 5)}
        wrap_numbers(input, 'disk_io')
        input = {'disk1': nt(10, 10, 10)}
        wrap_numbers(input, 'disk_io')
        cache = wrap_numbers.cache_info()
        self.assertEqual(cache[0], {'disk_io': input})
        self.assertEqual(
            cache[1],
            {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}})
        self.assertEqual(cache[2], {'disk_io': {}})

    def test_cache_wrap(self):
        # let's say 100 is the threshold
        input = {'disk1': nt(100, 100, 100)}
        wrap_numbers(input, 'disk_io')

        # first wrap restarts from 10
        input = {'disk1': nt(100, 100, 10)}
        wrap_numbers(input, 'disk_io')
        cache = wrap_numbers.cache_info()
        self.assertEqual(cache[0], {'disk_io': input})
        self.assertEqual(
            cache[1],
            {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 100}})
        self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}})

        def assert_():
            cache = wrap_numbers.cache_info()
            self.assertEqual(
                cache[1],
                {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0,
                             ('disk1', 2): 100}})
            self.assertEqual(cache[2],
                             {'disk_io': {'disk1': set([('disk1', 2)])}})

        # then it remains the same
        input = {'disk1': nt(100, 100, 10)}
        wrap_numbers(input, 'disk_io')
        cache = wrap_numbers.cache_info()
        self.assertEqual(cache[0], {'disk_io': input})
        assert_()

        # then it goes up
        input = {'disk1': nt(100, 100, 90)}
        wrap_numbers(input, 'disk_io')
        cache = wrap_numbers.cache_info()
        self.assertEqual(cache[0], {'disk_io': input})
        assert_()

        # then it wraps again
        input = {'disk1': nt(100, 100, 20)}
        wrap_numbers(input, 'disk_io')
        cache = wrap_numbers.cache_info()
        self.assertEqual(cache[0], {'disk_io': input})
        self.assertEqual(
            cache[1],
            {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 190}})
        self.assertEqual(cache[2], {'disk_io': {'disk1': set([('disk1', 2)])}})

    def test_cache_changing_keys(self):
        input = {'disk1': nt(5, 5, 5)}
        wrap_numbers(input, 'disk_io')
        input = {'disk1': nt(5, 5, 5),
                 'disk2': nt(7, 7, 7)}
        wrap_numbers(input, 'disk_io')
        cache = wrap_numbers.cache_info()
        self.assertEqual(cache[0], {'disk_io': input})
        self.assertEqual(
            cache[1],
            {'disk_io': {('disk1', 0): 0, ('disk1', 1): 0, ('disk1', 2): 0}})
        self.assertEqual(cache[2], {'disk_io': {}})

    def test_cache_clear(self):
        input = {'disk1': nt(5, 5, 5)}
        wrap_numbers(input, 'disk_io')
        wrap_numbers(input, 'disk_io')
        wrap_numbers.cache_clear('disk_io')
        self.assertEqual(wrap_numbers.cache_info(), ({}, {}, {}))
        wrap_numbers.cache_clear('disk_io')
        wrap_numbers.cache_clear('?!?')

    @unittest.skipIf(
        not psutil.disk_io_counters() or not psutil.net_io_counters(),
        "no disks or NICs available")
    def test_cache_clear_public_apis(self):
        psutil.disk_io_counters()
        psutil.net_io_counters()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.disk_io_counters', cache)
            self.assertIn('psutil.net_io_counters', cache)

        psutil.disk_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        for cache in caches:
            self.assertIn('psutil.net_io_counters', cache)
            self.assertNotIn('psutil.disk_io_counters', cache)

        psutil.net_io_counters.cache_clear()
        caches = wrap_numbers.cache_info()
        self.assertEqual(caches, ({}, {}, {}))


# ===================================================================
# --- Example script tests
# ===================================================================


@unittest.skipIf(TOX, "can't test on TOX")
# See: https://travis-ci.org/giampaolo/psutil/jobs/295224806
@unittest.skipIf(TRAVIS and not os.path.exists(SCRIPTS_DIR),
                 "can't locate scripts directory")
class TestScripts(unittest.TestCase):
    """Tests for scripts in the "scripts" directory."""

    @staticmethod
    def assert_stdout(exe, *args, **kwargs):
        exe = '%s' % os.path.join(SCRIPTS_DIR, exe)
        cmd = [PYTHON_EXE, exe]
        for arg in args:
            cmd.append(arg)
        try:
            out = sh(cmd, **kwargs).strip()
        except RuntimeError as err:
            if 'AccessDenied' in str(err):
                return str(err)
            else:
                raise
        assert out, out
        return out

    @staticmethod
    def assert_syntax(exe, args=None):
        exe = os.path.join(SCRIPTS_DIR, exe)
        if PY3:
            f = open(exe, 'rt', encoding='utf8')
        else:
            f = open(exe, 'rt')
        with f:
            src = f.read()
        ast.parse(src)

    def test_coverage(self):
        # make sure all example scripts have a test method defined
        meths = dir(self)
        for name in os.listdir(SCRIPTS_DIR):
            if name.endswith('.py'):
                if 'test_' + os.path.splitext(name)[0] not in meths:
                    # self.assert_stdout(name)
                    self.fail('no test defined for %r script'
                              % os.path.join(SCRIPTS_DIR, name))

    @unittest.skipIf(not POSIX, "POSIX only")
    def test_executable(self):
        for name in os.listdir(SCRIPTS_DIR):
            if name.endswith('.py'):
                path = os.path.join(SCRIPTS_DIR, name)
                if not stat.S_IXUSR & os.stat(path)[stat.ST_MODE]:
                    self.fail('%r is not executable' % path)

    def test_disk_usage(self):
        self.assert_stdout('disk_usage.py')

    def test_free(self):
        self.assert_stdout('free.py')

    def test_meminfo(self):
        self.assert_stdout('meminfo.py')

    def test_procinfo(self):
        self.assert_stdout('procinfo.py', str(os.getpid()))

    # can't find users on APPVEYOR or TRAVIS
    @unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(),
                     "unreliable on APPVEYOR or TRAVIS")
    def test_who(self):
        self.assert_stdout('who.py')

    def test_ps(self):
        self.assert_stdout('ps.py')

    def test_pstree(self):
        self.assert_stdout('pstree.py')

    def test_netstat(self):
        self.assert_stdout('netstat.py')

    # permission denied on travis
    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    def test_ifconfig(self):
        self.assert_stdout('ifconfig.py')

    @unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
    def test_pmap(self):
        self.assert_stdout('pmap.py', str(os.getpid()))

    @unittest.skipIf(not HAS_MEMORY_FULL_INFO, "not supported")
    def test_procsmem(self):
        self.assert_stdout('procsmem.py', stderr=DEVNULL)

    def test_killall(self):
        self.assert_syntax('killall.py')

    def test_nettop(self):
        self.assert_syntax('nettop.py')

    def test_top(self):
        self.assert_syntax('top.py')

    def test_iotop(self):
        self.assert_syntax('iotop.py')

    def test_pidof(self):
        output = self.assert_stdout('pidof.py', psutil.Process().name())
        self.assertIn(str(os.getpid()), output)

    @unittest.skipIf(not WINDOWS, "WINDOWS only")
    def test_winservices(self):
        self.assert_stdout('winservices.py')

    def test_cpu_distribution(self):
        self.assert_syntax('cpu_distribution.py')

    @unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    def test_temperatures(self):
        self.assert_stdout('temperatures.py')

    @unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
    @unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
    def test_fans(self):
        self.assert_stdout('fans.py')

    @unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
    @unittest.skipIf(not HAS_BATTERY, "no battery")
    def test_battery(self):
        self.assert_stdout('battery.py')

    def test_sensors(self):
        self.assert_stdout('sensors.py')


# ===================================================================
# --- Unit tests for test utilities.
# ===================================================================


class TestRetryDecorator(unittest.TestCase):

    @mock.patch('time.sleep')
    def test_retry_success(self, sleep):
        # Fail 3 times out of 5; make sure the decorated fun returns.

        @retry(retries=5, interval=1, logfun=None)
        def foo():
            while queue:
                queue.pop()
                1 / 0
            return 1

        queue = list(range(3))
        self.assertEqual(foo(), 1)
        self.assertEqual(sleep.call_count, 3)

    @mock.patch('time.sleep')
    def test_retry_failure(self, sleep):
        # Fail 6 times out of 5; th function is supposed to raise exc.

        @retry(retries=5, interval=1, logfun=None)
        def foo():
            while queue:
                queue.pop()
                1 / 0
            return 1

        queue = list(range(6))
        self.assertRaises(ZeroDivisionError, foo)
        self.assertEqual(sleep.call_count, 5)

    @mock.patch('time.sleep')
    def test_exception_arg(self, sleep):
        @retry(exception=ValueError, interval=1)
        def foo():
            raise TypeError

        self.assertRaises(TypeError, foo)
        self.assertEqual(sleep.call_count, 0)

    @mock.patch('time.sleep')
    def test_no_interval_arg(self, sleep):
        # if interval is not specified sleep is not supposed to be called

        @retry(retries=5, interval=None, logfun=None)
        def foo():
            1 / 0

        self.assertRaises(ZeroDivisionError, foo)
        self.assertEqual(sleep.call_count, 0)

    @mock.patch('time.sleep')
    def test_retries_arg(self, sleep):

        @retry(retries=5, interval=1, logfun=None)
        def foo():
            1 / 0

        self.assertRaises(ZeroDivisionError, foo)
        self.assertEqual(sleep.call_count, 5)

    @mock.patch('time.sleep')
    def test_retries_and_timeout_args(self, sleep):
        self.assertRaises(ValueError, retry, retries=5, timeout=1)


class TestSyncTestUtils(unittest.TestCase):

    def tearDown(self):
        safe_rmpath(TESTFN)

    def test_wait_for_pid(self):
        wait_for_pid(os.getpid())
        nopid = max(psutil.pids()) + 99999
        with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])):
            self.assertRaises(psutil.NoSuchProcess, wait_for_pid, nopid)

    def test_wait_for_file(self):
        with open(TESTFN, 'w') as f:
            f.write('foo')
        wait_for_file(TESTFN)
        assert not os.path.exists(TESTFN)

    def test_wait_for_file_empty(self):
        with open(TESTFN, 'w'):
            pass
        wait_for_file(TESTFN, empty=True)
        assert not os.path.exists(TESTFN)

    def test_wait_for_file_no_file(self):
        with mock.patch('psutil.tests.retry.__iter__', return_value=iter([0])):
            self.assertRaises(IOError, wait_for_file, TESTFN)

    def test_wait_for_file_no_delete(self):
        with open(TESTFN, 'w') as f:
            f.write('foo')
        wait_for_file(TESTFN, delete=False)
        assert os.path.exists(TESTFN)

    def test_call_until(self):
        ret = call_until(lambda: 1, "ret == 1")
        self.assertEqual(ret, 1)


class TestFSTestUtils(unittest.TestCase):

    def setUp(self):
        safe_rmpath(TESTFN)

    tearDown = setUp

    def test_safe_rmpath(self):
        # test file is removed
        open(TESTFN, 'w').close()
        safe_rmpath(TESTFN)
        assert not os.path.exists(TESTFN)
        # test no exception if path does not exist
        safe_rmpath(TESTFN)
        # test dir is removed
        os.mkdir(TESTFN)
        safe_rmpath(TESTFN)
        assert not os.path.exists(TESTFN)
        # test other exceptions are raised
        with mock.patch('psutil.tests.os.stat',
                        side_effect=OSError(errno.EINVAL, "")) as m:
            with self.assertRaises(OSError):
                safe_rmpath(TESTFN)
            assert m.called

    def test_chdir(self):
        base = os.getcwd()
        os.mkdir(TESTFN)
        with chdir(TESTFN):
            self.assertEqual(os.getcwd(), os.path.join(base, TESTFN))
        self.assertEqual(os.getcwd(), base)


class TestProcessUtils(unittest.TestCase):

    def test_reap_children(self):
        subp = get_test_subprocess()
        p = psutil.Process(subp.pid)
        assert p.is_running()
        reap_children()
        assert not p.is_running()
        assert not psutil.tests._pids_started
        assert not psutil.tests._subprocesses_started

    def test_create_proc_children_pair(self):
        p1, p2 = create_proc_children_pair()
        self.assertNotEqual(p1.pid, p2.pid)
        assert p1.is_running()
        assert p2.is_running()
        children = psutil.Process().children(recursive=True)
        self.assertEqual(len(children), 2)
        self.assertIn(p1, children)
        self.assertIn(p2, children)
        self.assertEqual(p1.ppid(), os.getpid())
        self.assertEqual(p2.ppid(), p1.pid)

        # make sure both of them are cleaned up
        reap_children()
        assert not p1.is_running()
        assert not p2.is_running()
        assert not psutil.tests._pids_started
        assert not psutil.tests._subprocesses_started

    @unittest.skipIf(not POSIX, "POSIX only")
    def test_create_zombie_proc(self):
        zpid = create_zombie_proc()
        self.addCleanup(reap_children, recursive=True)
        p = psutil.Process(zpid)
        self.assertEqual(p.status(), psutil.STATUS_ZOMBIE)


class TestNetUtils(unittest.TestCase):

    def bind_socket(self):
        port = get_free_port()
        with contextlib.closing(bind_socket(addr=('', port))) as s:
            self.assertEqual(s.getsockname()[1], port)

    @unittest.skipIf(not POSIX, "POSIX only")
    def test_bind_unix_socket(self):
        with unix_socket_path() as name:
            sock = bind_unix_socket(name)
            with contextlib.closing(sock):
                self.assertEqual(sock.family, socket.AF_UNIX)
                self.assertEqual(sock.type, socket.SOCK_STREAM)
                self.assertEqual(sock.getsockname(), name)
                assert os.path.exists(name)
                assert stat.S_ISSOCK(os.stat(name).st_mode)
        # UDP
        with unix_socket_path() as name:
            sock = bind_unix_socket(name, type=socket.SOCK_DGRAM)
            with contextlib.closing(sock):
                self.assertEqual(sock.type, socket.SOCK_DGRAM)

    def tcp_tcp_socketpair(self):
        addr = ("127.0.0.1", get_free_port())
        server, client = tcp_socketpair(socket.AF_INET, addr=addr)
        with contextlib.closing(server):
            with contextlib.closing(client):
                # Ensure they are connected and the positions are
                # correct.
                self.assertEqual(server.getsockname(), addr)
                self.assertEqual(client.getpeername(), addr)
                self.assertNotEqual(client.getsockname(), addr)

    @unittest.skipIf(not POSIX, "POSIX only")
    def test_unix_socketpair(self):
        p = psutil.Process()
        num_fds = p.num_fds()
        assert not p.connections(kind='unix')
        with unix_socket_path() as name:
            server, client = unix_socketpair(name)
            try:
                assert os.path.exists(name)
                assert stat.S_ISSOCK(os.stat(name).st_mode)
                self.assertEqual(p.num_fds() - num_fds, 2)
                self.assertEqual(len(p.connections(kind='unix')), 2)
                self.assertEqual(server.getsockname(), name)
                self.assertEqual(client.getpeername(), name)
            finally:
                client.close()
                server.close()

    def test_create_sockets(self):
        with create_sockets() as socks:
            fams = collections.defaultdict(int)
            types = collections.defaultdict(int)
            for s in socks:
                fams[s.family] += 1
                # work around http://bugs.python.org/issue30204
                types[s.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE)] += 1
            self.assertGreaterEqual(fams[socket.AF_INET], 2)
            if supports_ipv6():
                self.assertGreaterEqual(fams[socket.AF_INET6], 2)
            if POSIX and HAS_CONNECTIONS_UNIX:
                self.assertGreaterEqual(fams[socket.AF_UNIX], 2)
            self.assertGreaterEqual(types[socket.SOCK_STREAM], 2)
            self.assertGreaterEqual(types[socket.SOCK_DGRAM], 2)


class TestOtherUtils(unittest.TestCase):

    def test_is_namedtuple(self):
        assert is_namedtuple(collections.namedtuple('foo', 'a b c')(1, 2, 3))
        assert not is_namedtuple(tuple())


if __name__ == '__main__':
    run_test_module_by_name(__file__)
_psosx.py000064400000041475150466730550006457 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""OSX platform implementation."""

import contextlib
import errno
import functools
import os
from socket import AF_INET
from collections import namedtuple

from . import _common
from . import _psposix
from . import _psutil_osx as cext
from . import _psutil_posix as cext_posix
from ._common import AF_INET6
from ._common import conn_tmap
from ._common import isfile_strict
from ._common import memoize_when_activated
from ._common import parse_environ_block
from ._common import sockfam_to_enum
from ._common import socktype_to_enum
from ._common import usage_percent
from ._exceptions import AccessDenied
from ._exceptions import NoSuchProcess
from ._exceptions import ZombieProcess


__extra__all__ = []


# =====================================================================
# --- globals
# =====================================================================


PAGESIZE = os.sysconf("SC_PAGE_SIZE")
AF_LINK = cext_posix.AF_LINK

TCP_STATUSES = {
    cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
    cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
    cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
    cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
    cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
    cext.TCPS_CLOSED: _common.CONN_CLOSE,
    cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
    cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
    cext.TCPS_LISTEN: _common.CONN_LISTEN,
    cext.TCPS_CLOSING: _common.CONN_CLOSING,
    cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
}

PROC_STATUSES = {
    cext.SIDL: _common.STATUS_IDLE,
    cext.SRUN: _common.STATUS_RUNNING,
    cext.SSLEEP: _common.STATUS_SLEEPING,
    cext.SSTOP: _common.STATUS_STOPPED,
    cext.SZOMB: _common.STATUS_ZOMBIE,
}

kinfo_proc_map = dict(
    ppid=0,
    ruid=1,
    euid=2,
    suid=3,
    rgid=4,
    egid=5,
    sgid=6,
    ttynr=7,
    ctime=8,
    status=9,
    name=10,
)

pidtaskinfo_map = dict(
    cpuutime=0,
    cpustime=1,
    rss=2,
    vms=3,
    pfaults=4,
    pageins=5,
    numthreads=6,
    volctxsw=7,
)


# =====================================================================
# --- named tuples
# =====================================================================


# psutil.cpu_times()
scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle'])
# psutil.virtual_memory()
svmem = namedtuple(
    'svmem', ['total', 'available', 'percent', 'used', 'free',
              'active', 'inactive', 'wired'])
# psutil.Process.memory_info()
pmem = namedtuple('pmem', ['rss', 'vms', 'pfaults', 'pageins'])
# psutil.Process.memory_full_info()
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
# psutil.Process.memory_maps(grouped=True)
pmmap_grouped = namedtuple(
    'pmmap_grouped',
    'path rss private swapped dirtied ref_count shadow_depth')
# psutil.Process.memory_maps(grouped=False)
pmmap_ext = namedtuple(
    'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))


# =====================================================================
# --- memory
# =====================================================================


def virtual_memory():
    """System virtual memory as a namedtuple."""
    total, active, inactive, wired, free = cext.virtual_mem()
    avail = inactive + free
    used = active + inactive + wired
    percent = usage_percent((total - avail), total, _round=1)
    return svmem(total, avail, percent, used, free,
                 active, inactive, wired)


def swap_memory():
    """Swap system memory as a (total, used, free, sin, sout) tuple."""
    total, used, free, sin, sout = cext.swap_mem()
    percent = usage_percent(used, total, _round=1)
    return _common.sswap(total, used, free, percent, sin, sout)


# =====================================================================
# --- CPU
# =====================================================================


def cpu_times():
    """Return system CPU times as a namedtuple."""
    user, nice, system, idle = cext.cpu_times()
    return scputimes(user, nice, system, idle)


def per_cpu_times():
    """Return system CPU times as a named tuple"""
    ret = []
    for cpu_t in cext.per_cpu_times():
        user, nice, system, idle = cpu_t
        item = scputimes(user, nice, system, idle)
        ret.append(item)
    return ret


def cpu_count_logical():
    """Return the number of logical CPUs in the system."""
    return cext.cpu_count_logical()


def cpu_count_physical():
    """Return the number of physical CPUs in the system."""
    return cext.cpu_count_phys()


def cpu_stats():
    ctx_switches, interrupts, soft_interrupts, syscalls, traps = \
        cext.cpu_stats()
    return _common.scpustats(
        ctx_switches, interrupts, soft_interrupts, syscalls)


def cpu_freq():
    """Return CPU frequency.
    On OSX per-cpu frequency is not supported.
    Also, the returned frequency never changes, see:
    https://arstechnica.com/civis/viewtopic.php?f=19&t=465002
    """
    curr, min_, max_ = cext.cpu_freq()
    return [_common.scpufreq(curr, min_, max_)]


# =====================================================================
# --- disks
# =====================================================================


disk_usage = _psposix.disk_usage
disk_io_counters = cext.disk_io_counters


def disk_partitions(all=False):
    """Return mounted disk partitions as a list of namedtuples."""
    retlist = []
    partitions = cext.disk_partitions()
    for partition in partitions:
        device, mountpoint, fstype, opts = partition
        if device == 'none':
            device = ''
        if not all:
            if not os.path.isabs(device) or not os.path.exists(device):
                continue
        ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
        retlist.append(ntuple)
    return retlist


# =====================================================================
# --- sensors
# =====================================================================


def sensors_battery():
    """Return battery information.
    """
    try:
        percent, minsleft, power_plugged = cext.sensors_battery()
    except NotImplementedError:
        # no power source - return None according to interface
        return None
    power_plugged = power_plugged == 1
    if power_plugged:
        secsleft = _common.POWER_TIME_UNLIMITED
    elif minsleft == -1:
        secsleft = _common.POWER_TIME_UNKNOWN
    else:
        secsleft = minsleft * 60
    return _common.sbattery(percent, secsleft, power_plugged)


# =====================================================================
# --- network
# =====================================================================


net_io_counters = cext.net_io_counters
net_if_addrs = cext_posix.net_if_addrs


def net_connections(kind='inet'):
    """System-wide network connections."""
    # Note: on OSX this will fail with AccessDenied unless
    # the process is owned by root.
    ret = []
    for pid in pids():
        try:
            cons = Process(pid).connections(kind)
        except NoSuchProcess:
            continue
        else:
            if cons:
                for c in cons:
                    c = list(c) + [pid]
                    ret.append(_common.sconn(*c))
    return ret


def net_if_stats():
    """Get NIC stats (isup, duplex, speed, mtu)."""
    names = net_io_counters().keys()
    ret = {}
    for name in names:
        mtu = cext_posix.net_if_mtu(name)
        isup = cext_posix.net_if_flags(name)
        duplex, speed = cext_posix.net_if_duplex_speed(name)
        if hasattr(_common, 'NicDuplex'):
            duplex = _common.NicDuplex(duplex)
        ret[name] = _common.snicstats(isup, duplex, speed, mtu)
    return ret


# =====================================================================
# --- other system functions
# =====================================================================


def boot_time():
    """The system boot time expressed in seconds since the epoch."""
    return cext.boot_time()


def users():
    """Return currently connected users as a list of namedtuples."""
    retlist = []
    rawlist = cext.users()
    for item in rawlist:
        user, tty, hostname, tstamp, pid = item
        if tty == '~':
            continue  # reboot or shutdown
        if not tstamp:
            continue
        nt = _common.suser(user, tty or None, hostname or None, tstamp, pid)
        retlist.append(nt)
    return retlist


# =====================================================================
# --- processes
# =====================================================================


def pids():
    ls = cext.pids()
    if 0 not in ls:
        # On certain OSX versions pids() C doesn't return PID 0 but
        # "ps" does and the process is querable via sysctl():
        # https://travis-ci.org/giampaolo/psutil/jobs/309619941
        try:
            Process(0).create_time()
            ls.append(0)
        except NoSuchProcess:
            pass
        except AccessDenied:
            ls.append(0)
    return ls


pid_exists = _psposix.pid_exists


def wrap_exceptions(fun):
    """Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except OSError as err:
            if err.errno == errno.ESRCH:
                raise NoSuchProcess(self.pid, self._name)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise
    return wrapper


@contextlib.contextmanager
def catch_zombie(proc):
    """There are some poor C APIs which incorrectly raise ESRCH when
    the process is still alive or it's a zombie, or even RuntimeError
    (those who don't set errno). This is here in order to solve:
    https://github.com/giampaolo/psutil/issues/1044
    """
    try:
        yield
    except (OSError, RuntimeError) as err:
        if isinstance(err, RuntimeError) or err.errno == errno.ESRCH:
            try:
                # status() is not supposed to lie and correctly detect
                # zombies so if it raises ESRCH it's true.
                status = proc.status()
            except NoSuchProcess:
                raise err
            else:
                if status == _common.STATUS_ZOMBIE:
                    raise ZombieProcess(proc.pid, proc._name, proc._ppid)
                else:
                    raise AccessDenied(proc.pid, proc._name)
        else:
            raise


class Process(object):
    """Wrapper class around underlying C implementation."""

    __slots__ = ["pid", "_name", "_ppid"]

    def __init__(self, pid):
        self.pid = pid
        self._name = None
        self._ppid = None

    @memoize_when_activated
    def _get_kinfo_proc(self):
        # Note: should work with all PIDs without permission issues.
        ret = cext.proc_kinfo_oneshot(self.pid)
        assert len(ret) == len(kinfo_proc_map)
        return ret

    @memoize_when_activated
    def _get_pidtaskinfo(self):
        # Note: should work for PIDs owned by user only.
        with catch_zombie(self):
            ret = cext.proc_pidtaskinfo_oneshot(self.pid)
        assert len(ret) == len(pidtaskinfo_map)
        return ret

    def oneshot_enter(self):
        self._get_kinfo_proc.cache_activate()
        self._get_pidtaskinfo.cache_activate()

    def oneshot_exit(self):
        self._get_kinfo_proc.cache_deactivate()
        self._get_pidtaskinfo.cache_deactivate()

    @wrap_exceptions
    def name(self):
        name = self._get_kinfo_proc()[kinfo_proc_map['name']]
        return name if name is not None else cext.proc_name(self.pid)

    @wrap_exceptions
    def exe(self):
        with catch_zombie(self):
            return cext.proc_exe(self.pid)

    @wrap_exceptions
    def cmdline(self):
        with catch_zombie(self):
            return cext.proc_cmdline(self.pid)

    @wrap_exceptions
    def environ(self):
        with catch_zombie(self):
            return parse_environ_block(cext.proc_environ(self.pid))

    @wrap_exceptions
    def ppid(self):
        self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']]
        return self._ppid

    @wrap_exceptions
    def cwd(self):
        with catch_zombie(self):
            return cext.proc_cwd(self.pid)

    @wrap_exceptions
    def uids(self):
        rawtuple = self._get_kinfo_proc()
        return _common.puids(
            rawtuple[kinfo_proc_map['ruid']],
            rawtuple[kinfo_proc_map['euid']],
            rawtuple[kinfo_proc_map['suid']])

    @wrap_exceptions
    def gids(self):
        rawtuple = self._get_kinfo_proc()
        return _common.puids(
            rawtuple[kinfo_proc_map['rgid']],
            rawtuple[kinfo_proc_map['egid']],
            rawtuple[kinfo_proc_map['sgid']])

    @wrap_exceptions
    def terminal(self):
        tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']]
        tmap = _psposix.get_terminal_map()
        try:
            return tmap[tty_nr]
        except KeyError:
            return None

    @wrap_exceptions
    def memory_info(self):
        rawtuple = self._get_pidtaskinfo()
        return pmem(
            rawtuple[pidtaskinfo_map['rss']],
            rawtuple[pidtaskinfo_map['vms']],
            rawtuple[pidtaskinfo_map['pfaults']],
            rawtuple[pidtaskinfo_map['pageins']],
        )

    @wrap_exceptions
    def memory_full_info(self):
        basic_mem = self.memory_info()
        uss = cext.proc_memory_uss(self.pid)
        return pfullmem(*basic_mem + (uss, ))

    @wrap_exceptions
    def cpu_times(self):
        rawtuple = self._get_pidtaskinfo()
        return _common.pcputimes(
            rawtuple[pidtaskinfo_map['cpuutime']],
            rawtuple[pidtaskinfo_map['cpustime']],
            # children user / system times are not retrievable (set to 0)
            0.0, 0.0)

    @wrap_exceptions
    def create_time(self):
        return self._get_kinfo_proc()[kinfo_proc_map['ctime']]

    @wrap_exceptions
    def num_ctx_switches(self):
        # Unvoluntary value seems not to be available;
        # getrusage() numbers seems to confirm this theory.
        # We set it to 0.
        vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']]
        return _common.pctxsw(vol, 0)

    @wrap_exceptions
    def num_threads(self):
        return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']]

    @wrap_exceptions
    def open_files(self):
        if self.pid == 0:
            return []
        files = []
        with catch_zombie(self):
            rawlist = cext.proc_open_files(self.pid)
        for path, fd in rawlist:
            if isfile_strict(path):
                ntuple = _common.popenfile(path, fd)
                files.append(ntuple)
        return files

    @wrap_exceptions
    def connections(self, kind='inet'):
        if kind not in conn_tmap:
            raise ValueError("invalid %r kind argument; choose between %s"
                             % (kind, ', '.join([repr(x) for x in conn_tmap])))
        families, types = conn_tmap[kind]
        with catch_zombie(self):
            rawlist = cext.proc_connections(self.pid, families, types)
        ret = []
        for item in rawlist:
            fd, fam, type, laddr, raddr, status = item
            status = TCP_STATUSES[status]
            fam = sockfam_to_enum(fam)
            type = socktype_to_enum(type)
            if fam in (AF_INET, AF_INET6):
                if laddr:
                    laddr = _common.addr(*laddr)
                if raddr:
                    raddr = _common.addr(*raddr)
            nt = _common.pconn(fd, fam, type, laddr, raddr, status)
            ret.append(nt)
        return ret

    @wrap_exceptions
    def num_fds(self):
        if self.pid == 0:
            return 0
        with catch_zombie(self):
            return cext.proc_num_fds(self.pid)

    @wrap_exceptions
    def wait(self, timeout=None):
        return _psposix.wait_pid(self.pid, timeout, self._name)

    @wrap_exceptions
    def nice_get(self):
        with catch_zombie(self):
            return cext_posix.getpriority(self.pid)

    @wrap_exceptions
    def nice_set(self, value):
        with catch_zombie(self):
            return cext_posix.setpriority(self.pid, value)

    @wrap_exceptions
    def status(self):
        code = self._get_kinfo_proc()[kinfo_proc_map['status']]
        # XXX is '?' legit? (we're not supposed to return it anyway)
        return PROC_STATUSES.get(code, '?')

    @wrap_exceptions
    def threads(self):
        with catch_zombie(self):
            rawlist = cext.proc_threads(self.pid)
        retlist = []
        for thread_id, utime, stime in rawlist:
            ntuple = _common.pthread(thread_id, utime, stime)
            retlist.append(ntuple)
        return retlist

    @wrap_exceptions
    def memory_maps(self):
        with catch_zombie(self):
            return cext.proc_memory_maps(self.pid)
_psposix.py000064400000014311150466730550006775 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Routines common to all posix systems."""

import errno
import glob
import os
import sys
import time

from ._common import memoize
from ._common import sdiskusage
from ._common import usage_percent
from ._compat import PY3
from ._compat import unicode
from ._exceptions import TimeoutExpired


__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map']


def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if pid == 0:
        # According to "man 2 kill" PID 0 has a special meaning:
        # it refers to <<every process in the process group of the
        # calling process>> so we don't want to go any further.
        # If we get here it means this UNIX platform *does* have
        # a process with id 0.
        return True
    try:
        os.kill(pid, 0)
    except OSError as err:
        if err.errno == errno.ESRCH:
            # ESRCH == No such process
            return False
        elif err.errno == errno.EPERM:
            # EPERM clearly means there's a process to deny access to
            return True
        else:
            # According to "man 2 kill" possible error values are
            # (EINVAL, EPERM, ESRCH) therefore we should never get
            # here. If we do let's be explicit in considering this
            # an error.
            raise err
    else:
        return True


def wait_pid(pid, timeout=None, proc_name=None):
    """Wait for process with pid 'pid' to terminate and return its
    exit status code as an integer.

    If pid is not a children of os.getpid() (current process) just
    waits until the process disappears and return None.

    If pid does not exist at all return None immediately.

    Raise TimeoutExpired on timeout expired.
    """
    def check_timeout(delay):
        if timeout is not None:
            if timer() >= stop_at:
                raise TimeoutExpired(timeout, pid=pid, name=proc_name)
        time.sleep(delay)
        return min(delay * 2, 0.04)

    timer = getattr(time, 'monotonic', time.time)
    if timeout is not None:
        def waitcall():
            return os.waitpid(pid, os.WNOHANG)
        stop_at = timer() + timeout
    else:
        def waitcall():
            return os.waitpid(pid, 0)

    delay = 0.0001
    while True:
        try:
            retpid, status = waitcall()
        except OSError as err:
            if err.errno == errno.EINTR:
                delay = check_timeout(delay)
                continue
            elif err.errno == errno.ECHILD:
                # This has two meanings:
                # - pid is not a child of os.getpid() in which case
                #   we keep polling until it's gone
                # - pid never existed in the first place
                # In both cases we'll eventually return None as we
                # can't determine its exit status code.
                while True:
                    if pid_exists(pid):
                        delay = check_timeout(delay)
                    else:
                        return
            else:
                raise
        else:
            if retpid == 0:
                # WNOHANG was used, pid is still running
                delay = check_timeout(delay)
                continue
            # process exited due to a signal; return the integer of
            # that signal
            if os.WIFSIGNALED(status):
                return -os.WTERMSIG(status)
            # process exited using exit(2) system call; return the
            # integer exit(2) system call has been called with
            elif os.WIFEXITED(status):
                return os.WEXITSTATUS(status)
            else:
                # should never happen
                raise ValueError("unknown process exit status %r" % status)


def disk_usage(path):
    """Return disk usage associated with path.
    Note: UNIX usually reserves 5% disk space which is not accessible
    by user. In this function "total" and "used" values reflect the
    total and used disk space whereas "free" and "percent" represent
    the "free" and "used percent" user disk space.
    """
    if PY3:
        st = os.statvfs(path)
    else:
        # os.statvfs() does not support unicode on Python 2:
        # - https://github.com/giampaolo/psutil/issues/416
        # - http://bugs.python.org/issue18695
        try:
            st = os.statvfs(path)
        except UnicodeEncodeError:
            if isinstance(path, unicode):
                try:
                    path = path.encode(sys.getfilesystemencoding())
                except UnicodeEncodeError:
                    pass
                st = os.statvfs(path)
            else:
                raise

    # Total space which is only available to root (unless changed
    # at system level).
    total = (st.f_blocks * st.f_frsize)
    # Remaining free space usable by root.
    avail_to_root = (st.f_bfree * st.f_frsize)
    # Remaining free space usable by user.
    avail_to_user = (st.f_bavail * st.f_frsize)
    # Total space being used in general.
    used = (total - avail_to_root)
    # Total space which is available to user (same as 'total' but
    # for the user).
    total_user = used + avail_to_user
    # User usage percent compared to the total amount of space
    # the user can use. This number would be higher if compared
    # to root's because the user has less space (usually -5%).
    usage_percent_user = usage_percent(used, total_user, _round=1)

    # NB: the percentage is -5% than what shown by df due to
    # reserved blocks that we are currently not considering:
    # https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462
    return sdiskusage(
        total=total, used=used, free=avail_to_user, percent=usage_percent_user)


@memoize
def get_terminal_map():
    """Get a map of device-id -> path as a dict.
    Used by Process.terminal()
    """
    ret = {}
    ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
    for name in ls:
        assert name not in ret, name
        try:
            ret[os.stat(name).st_rdev] = name
        except OSError as err:
            if err.errno != errno.ENOENT:
                raise
    return ret
_pslinux.py000064400000222142150466730550006775 0ustar00# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Linux platform implementation."""

from __future__ import division

import base64
import collections
import errno
import functools
import glob
import os
import re
import socket
import struct
import sys
import traceback
import warnings
from collections import defaultdict
from collections import namedtuple

from . import _common
from . import _psposix
from . import _psutil_linux as cext
from . import _psutil_posix as cext_posix
from ._common import ENCODING
from ._common import ENCODING_ERRS
from ._common import isfile_strict
from ._common import memoize
from ._common import memoize_when_activated
from ._common import NIC_DUPLEX_FULL
from ._common import NIC_DUPLEX_HALF
from ._common import NIC_DUPLEX_UNKNOWN
from ._common import parse_environ_block
from ._common import path_exists_strict
from ._common import supports_ipv6
from ._common import usage_percent
from ._compat import b
from ._compat import basestring
from ._compat import long
from ._compat import PY3
from ._exceptions import AccessDenied
from ._exceptions import NoSuchProcess
from ._exceptions import ZombieProcess

if sys.version_info >= (3, 4):
    import enum
else:
    enum = None


__extra__all__ = [
    #
    'PROCFS_PATH',
    # io prio constants
    "IOPRIO_CLASS_NONE", "IOPRIO_CLASS_RT", "IOPRIO_CLASS_BE",
    "IOPRIO_CLASS_IDLE",
    # connection status constants
    "CONN_ESTABLISHED", "CONN_SYN_SENT", "CONN_SYN_RECV", "CONN_FIN_WAIT1",
    "CONN_FIN_WAIT2", "CONN_TIME_WAIT", "CONN_CLOSE", "CONN_CLOSE_WAIT",
    "CONN_LAST_ACK", "CONN_LISTEN", "CONN_CLOSING", ]


# =====================================================================
# --- globals
# =====================================================================


POWER_SUPPLY_PATH = "/sys/class/power_supply"
HAS_SMAPS = os.path.exists('/proc/%s/smaps' % os.getpid())
HAS_PRLIMIT = hasattr(cext, "linux_prlimit")
_DEFAULT = object()

# RLIMIT_* constants, not guaranteed to be present on all kernels
if HAS_PRLIMIT:
    for name in dir(cext):
        if name.startswith('RLIM'):
            __extra__all__.append(name)

# Number of clock ticks per second
CLOCK_TICKS = os.sysconf("SC_CLK_TCK")
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
BOOT_TIME = None  # set later
# Used when reading "big" files, namely /proc/{pid}/smaps and /proc/net/*.
# On Python 2, using a buffer with open() for such files may result in a
# speedup, see: https://github.com/giampaolo/psutil/issues/708
BIGFILE_BUFFERING = -1 if PY3 else 8192
LITTLE_ENDIAN = sys.byteorder == 'little'
SECTOR_SIZE_FALLBACK = 512
if enum is None:
    AF_LINK = socket.AF_PACKET
else:
    AddressFamily = enum.IntEnum('AddressFamily',
                                 {'AF_LINK': int(socket.AF_PACKET)})
    AF_LINK = AddressFamily.AF_LINK

# ioprio_* constants http://linux.die.net/man/2/ioprio_get
if enum is None:
    IOPRIO_CLASS_NONE = 0
    IOPRIO_CLASS_RT = 1
    IOPRIO_CLASS_BE = 2
    IOPRIO_CLASS_IDLE = 3
else:
    class IOPriority(enum.IntEnum):
        IOPRIO_CLASS_NONE = 0
        IOPRIO_CLASS_RT = 1
        IOPRIO_CLASS_BE = 2
        IOPRIO_CLASS_IDLE = 3

    globals().update(IOPriority.__members__)

# taken from /fs/proc/array.c
PROC_STATUSES = {
    "R": _common.STATUS_RUNNING,
    "S": _common.STATUS_SLEEPING,
    "D": _common.STATUS_DISK_SLEEP,
    "T": _common.STATUS_STOPPED,
    "t": _common.STATUS_TRACING_STOP,
    "Z": _common.STATUS_ZOMBIE,
    "X": _common.STATUS_DEAD,
    "x": _common.STATUS_DEAD,
    "K": _common.STATUS_WAKE_KILL,
    "W": _common.STATUS_WAKING
}

# https://github.com/torvalds/linux/blob/master/include/net/tcp_states.h
TCP_STATUSES = {
    "01": _common.CONN_ESTABLISHED,
    "02": _common.CONN_SYN_SENT,
    "03": _common.CONN_SYN_RECV,
    "04": _common.CONN_FIN_WAIT1,
    "05": _common.CONN_FIN_WAIT2,
    "06": _common.CONN_TIME_WAIT,
    "07": _common.CONN_CLOSE,
    "08": _common.CONN_CLOSE_WAIT,
    "09": _common.CONN_LAST_ACK,
    "0A": _common.CONN_LISTEN,
    "0B": _common.CONN_CLOSING
}


# =====================================================================
# --- named tuples
# =====================================================================


# psutil.virtual_memory()
svmem = namedtuple(
    'svmem', ['total', 'available', 'percent', 'used', 'free',
              'active', 'inactive', 'buffers', 'cached', 'shared'])
# psutil.disk_io_counters()
sdiskio = namedtuple(
    'sdiskio', ['read_count', 'write_count',
                'read_bytes', 'write_bytes',
                'read_time', 'write_time',
                'read_merged_count', 'write_merged_count',
                'busy_time'])
# psutil.Process().open_files()
popenfile = namedtuple(
    'popenfile', ['path', 'fd', 'position', 'mode', 'flags'])
# psutil.Process().memory_info()
pmem = namedtuple('pmem', 'rss vms shared text lib data dirty')
# psutil.Process().memory_full_info()
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', 'pss', 'swap'))
# psutil.Process().memory_maps(grouped=True)
pmmap_grouped = namedtuple(
    'pmmap_grouped',
    ['path', 'rss', 'size', 'pss', 'shared_clean', 'shared_dirty',
     'private_clean', 'private_dirty', 'referenced', 'anonymous', 'swap'])
# psutil.Process().memory_maps(grouped=False)
pmmap_ext = namedtuple(
    'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
# psutil.Process.io_counters()
pio = namedtuple('pio', ['read_count', 'write_count',
                         'read_bytes', 'write_bytes',
                         'read_chars', 'write_chars'])


# =====================================================================
# --- utils
# =====================================================================


def open_binary(fname, **kwargs):
    return open(fname, "rb", **kwargs)


def open_text(fname, **kwargs):
    """On Python 3 opens a file in text mode by using fs encoding and
    a proper en/decoding errors handler.
    On Python 2 this is just an alias for open(name, 'rt').
    """
    if PY3:
        # See:
        # https://github.com/giampaolo/psutil/issues/675
        # https://github.com/giampaolo/psutil/pull/733
        kwargs.setdefault('encoding', ENCODING)
        kwargs.setdefault('errors', ENCODING_ERRS)
    return open(fname, "rt", **kwargs)


if PY3:
    def decode(s):
        return s.decode(encoding=ENCODING, errors=ENCODING_ERRS)
else:
    def decode(s):
        return s


def get_procfs_path():
    """Return updated psutil.PROCFS_PATH constant."""
    return sys.modules['psutil'].PROCFS_PATH


def readlink(path):
    """Wrapper around os.readlink()."""
    assert isinstance(path, basestring), path
    path = os.readlink(path)
    # readlink() might return paths containing null bytes ('\x00')
    # resulting in "TypeError: must be encoded string without NULL
    # bytes, not str" errors when the string is passed to other
    # fs-related functions (os.*, open(), ...).
    # Apparently everything after '\x00' is garbage (we can have
    # ' (deleted)', 'new' and possibly others), see:
    # https://github.com/giampaolo/psutil/issues/717
    path = path.split('\x00')[0]
    # Certain paths have ' (deleted)' appended. Usually this is
    # bogus as the file actually exists. Even if it doesn't we
    # don't care.
    if path.endswith(' (deleted)') and not path_exists_strict(path):
        path = path[:-10]
    return path


def file_flags_to_mode(flags):
    """Convert file's open() flags into a readable string.
    Used by Process.open_files().
    """
    modes_map = {os.O_RDONLY: 'r', os.O_WRONLY: 'w', os.O_RDWR: 'w+'}
    mode = modes_map[flags & (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)]
    if flags & os.O_APPEND:
        mode = mode.replace('w', 'a', 1)
    mode = mode.replace('w+', 'r+')
    # possible values: r, w, a, r+, a+
    return mode


def get_sector_size(partition):
    """Return the sector size of a partition.
    Used by disk_io_counters().
    """
    try:
        with open("/sys/block/%s/queue/hw_sector_size" % partition, "rt") as f:
            return int(f.read())
    except (IOError, ValueError):
        # man iostat states that sectors are equivalent with blocks and
        # have a size of 512 bytes since 2.4 kernels.
        return SECTOR_SIZE_FALLBACK


@memoize
def set_scputimes_ntuple(procfs_path):
    """Set a namedtuple of variable fields depending on the CPU times
    available on this Linux kernel version which may be:
    (user, nice, system, idle, iowait, irq, softirq, [steal, [guest,
     [guest_nice]]])
    Used by cpu_times() function.
    """
    global scputimes
    with open_binary('%s/stat' % procfs_path) as f:
        values = f.readline().split()[1:]
    fields = ['user', 'nice', 'system', 'idle', 'iowait', 'irq', 'softirq']
    vlen = len(values)
    if vlen >= 8:
        # Linux >= 2.6.11
        fields.append('steal')
    if vlen >= 9:
        # Linux >= 2.6.24
        fields.append('guest')
    if vlen >= 10:
        # Linux >= 3.2.0
        fields.append('guest_nice')
    scputimes = namedtuple('scputimes', fields)


def cat(fname, fallback=_DEFAULT, binary=True):
    """Return file content.
    fallback: the value returned in case the file does not exist or
              cannot be read
    binary: whether to open the file in binary or text mode.
    """
    try:
        with open_binary(fname) if binary else open_text(fname) as f:
            return f.read().strip()
    except IOError:
        if fallback is not _DEFAULT:
            return fallback
        else:
            raise


try:
    set_scputimes_ntuple("/proc")
except Exception:
    # Don't want to crash at import time.
    traceback.print_exc()
    scputimes = namedtuple('scputimes', 'user system idle')(0.0, 0.0, 0.0)


# =====================================================================
# --- system memory
# =====================================================================


def calculate_avail_vmem(mems):
    """Fallback for kernels < 3.14 where /proc/meminfo does not provide
    "MemAvailable:" column, see:
    https://blog.famzah.net/2014/09/24/
    This code reimplements the algorithm outlined here:
    https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
        commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773

    XXX: on recent kernels this calculation differs by ~1.5% than
    "MemAvailable:" as it's calculated slightly differently, see:
    https://gitlab.com/procps-ng/procps/issues/42
    https://github.com/famzah/linux-memavailable-procfs/issues/2
    It is still way more realistic than doing (free + cached) though.
    """
    # Fallback for very old distros. According to
    # https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/
    #     commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773
    # ...long ago "avail" was calculated as (free + cached).
    # We might fallback in such cases:
    # "Active(file)" not available: 2.6.28 / Dec 2008
    # "Inactive(file)" not available: 2.6.28 / Dec 2008
    # "SReclaimable:" not available: 2.6.19 / Nov 2006
    # /proc/zoneinfo not available: 2.6.13 / Aug 2005
    free = mems[b'MemFree:']
    fallback = free + mems.get(b"Cached:", 0)
    try:
        lru_active_file = mems[b'Active(file):']
        lru_inactive_file = mems[b'Inactive(file):']
        slab_reclaimable = mems[b'SReclaimable:']
    except KeyError:
        return fallback
    try:
        f = open_binary('%s/zoneinfo' % get_procfs_path())
    except IOError:
        return fallback  # kernel 2.6.13

    watermark_low = 0
    with f:
        for line in f:
            line = line.strip()
            if line.startswith(b'low'):
                watermark_low += int(line.split()[1])
    watermark_low *= PAGESIZE
    watermark_low = watermark_low

    avail = free - watermark_low
    pagecache = lru_active_file + lru_inactive_file
    pagecache -= min(pagecache / 2, watermark_low)
    avail += pagecache
    avail += slab_reclaimable - min(slab_reclaimable / 2.0, watermark_low)
    return int(avail)


def virtual_memory():
    """Report virtual memory stats.
    This implementation matches "free" and "vmstat -s" cmdline
    utility values and procps-ng-3.3.12 source was used as a reference
    (2016-09-18):
    https://gitlab.com/procps-ng/procps/blob/
        24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c
    For reference, procps-ng-3.3.10 is the version available on Ubuntu
    16.04.

    Note about "available" memory: up until psutil 4.3 it was
    calculated as "avail = (free + buffers + cached)". Now
    "MemAvailable:" column (kernel 3.14) from /proc/meminfo is used as
    it's more accurate.
    That matches "available" column in newer versions of "free".
    """
    missing_fields = []
    mems = {}
    with open_binary('%s/meminfo' % get_procfs_path()) as f:
        for line in f:
            fields = line.split()
            mems[fields[0]] = int(fields[1]) * 1024

    # /proc doc states that the available fields in /proc/meminfo vary
    # by architecture and compile options, but these 3 values are also
    # returned by sysinfo(2); as such we assume they are always there.
    total = mems[b'MemTotal:']
    free = mems[b'MemFree:']
    try:
        buffers = mems[b'Buffers:']
    except KeyError:
        # https://github.com/giampaolo/psutil/issues/1010
        buffers = 0
        missing_fields.append('buffers')
    try:
        cached = mems[b"Cached:"]
    except KeyError:
        cached = 0
        missing_fields.append('cached')
    else:
        # "free" cmdline utility sums reclaimable to cached.
        # Older versions of procps used to add slab memory instead.
        # This got changed in:
        # https://gitlab.com/procps-ng/procps/commit/
        #     05d751c4f076a2f0118b914c5e51cfbb4762ad8e
        cached += mems.get(b"SReclaimable:", 0)  # since kernel 2.6.19

    try:
        shared = mems[b'Shmem:']  # since kernel 2.6.32
    except KeyError:
        try:
            shared = mems[b'MemShared:']  # kernels 2.4
        except KeyError:
            shared = 0
            missing_fields.append('shared')

    try:
        active = mems[b"Active:"]
    except KeyError:
        active = 0
        missing_fields.append('active')

    try:
        inactive = mems[b"Inactive:"]
    except KeyError:
        try:
            inactive = \
                mems[b"Inact_dirty:"] + \
                mems[b"Inact_clean:"] + \
                mems[b"Inact_laundry:"]
        except KeyError:
            inactive = 0
            missing_fields.append('inactive')

    used = total - free - cached - buffers
    if used < 0:
        # May be symptomatic of running within a LCX container where such
        # values will be dramatically distorted over those of the host.
        used = total - free

    # - starting from 4.4.0 we match free's "available" column.
    #   Before 4.4.0 we calculated it as (free + buffers + cached)
    #   which matched htop.
    # - free and htop available memory differs as per:
    #   http://askubuntu.com/a/369589
    #   http://unix.stackexchange.com/a/65852/168884
    # - MemAvailable has been introduced in kernel 3.14
    try:
        avail = mems[b'MemAvailable:']
    except KeyError:
        avail = calculate_avail_vmem(mems)

    if avail < 0:
        avail = 0
        missing_fields.append('available')

    # If avail is greater than total or our calculation overflows,
    # that's symptomatic of running within a LCX container where such
    # values will be dramatically distorted over those of the host.
    # https://gitlab.com/procps-ng/procps/blob/
    #     24fd2605c51fccc375ab0287cec33aa767f06718/proc/sysinfo.c#L764
    if avail > total:
        avail = free

    percent = usage_percent((total - avail), total, _round=1)

    # Warn about missing metrics which are set to 0.
    if missing_fields:
        msg = "%s memory stats couldn't be determined and %s set to 0" % (
            ", ".join(missing_fields),
            "was" if len(missing_fields) == 1 else "were")
        warnings.warn(msg, RuntimeWarning)

    return svmem(total, avail, percent, used, free,
                 active, inactive, buffers, cached, shared)


def swap_memory():
    """Return swap memory metrics."""
    mems = {}
    with open_binary('%s/meminfo' % get_procfs_path()) as f:
        for line in f:
            fields = line.split()
            mems[fields[0]] = int(fields[1]) * 1024
    # We prefer /proc/meminfo over sysinfo() syscall so that
    # psutil.PROCFS_PATH can be used in order to allow retrieval
    # for linux containers, see:
    # https://github.com/giampaolo/psutil/issues/1015
    try:
        total = mems[b'SwapTotal:']
        free = mems[b'SwapFree:']
    except KeyError:
        _, _, _, _, total, free, unit_multiplier = cext.linux_sysinfo()
        total *= unit_multiplier
        free *= unit_multiplier

    used = total - free
    percent = usage_percent(used, total, _round=1)
    # get pgin/pgouts
    try:
        f = open_binary("%s/vmstat" % get_procfs_path())
    except IOError as err:
        # see https://github.com/giampaolo/psutil/issues/722
        msg = "'sin' and 'sout' swap memory stats couldn't " \
              "be determined and were set to 0 (%s)" % str(err)
        warnings.warn(msg, RuntimeWarning)
        sin = sout = 0
    else:
        with f:
            sin = sout = None
            for line in f:
                # values are expressed in 4 kilo bytes, we want
                # bytes instead
                if line.startswith(b'pswpin'):
                    sin = int(line.split(b' ')[1]) * 4 * 1024
                elif line.startswith(b'pswpout'):
                    sout = int(line.split(b' ')[1]) * 4 * 1024
                if sin is not None and sout is not None:
                    break
            else:
                # we might get here when dealing with exotic Linux
                # flavors, see:
                # https://github.com/giampaolo/psutil/issues/313
                msg = "'sin' and 'sout' swap memory stats couldn't " \
                      "be determined and were set to 0"
                warnings.warn(msg, RuntimeWarning)
                sin = sout = 0
    return _common.sswap(total, used, free, percent, sin, sout)


# =====================================================================
# --- CPU
# =====================================================================


def cpu_times():
    """Return a named tuple representing the following system-wide
    CPU times:
    (user, nice, system, idle, iowait, irq, softirq [steal, [guest,
     [guest_nice]]])
    Last 3 fields may not be available on all Linux kernel versions.
    """
    procfs_path = get_procfs_path()
    set_scputimes_ntuple(procfs_path)
    with open_binary('%s/stat' % procfs_path) as f:
        values = f.readline().split()
    fields = values[1:len(scputimes._fields) + 1]
    fields = [float(x) / CLOCK_TICKS for x in fields]
    return scputimes(*fields)


def per_cpu_times():
    """Return a list of namedtuple representing the CPU times
    for every CPU available on the system.
    """
    procfs_path = get_procfs_path()
    set_scputimes_ntuple(procfs_path)
    cpus = []
    with open_binary('%s/stat' % procfs_path) as f:
        # get rid of the first line which refers to system wide CPU stats
        f.readline()
        for line in f:
            if line.startswith(b'cpu'):
                values = line.split()
                fields = values[1:len(scputimes._fields) + 1]
                fields = [float(x) / CLOCK_TICKS for x in fields]
                entry = scputimes(*fields)
                cpus.append(entry)
        return cpus


def cpu_count_logical():
    """Return the number of logical CPUs in the system."""
    try:
        return os.sysconf("SC_NPROCESSORS_ONLN")
    except ValueError:
        # as a second fallback we try to parse /proc/cpuinfo
        num = 0
        with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
            for line in f:
                if line.lower().startswith(b'processor'):
                    num += 1

        # unknown format (e.g. amrel/sparc architectures), see:
        # https://github.com/giampaolo/psutil/issues/200
        # try to parse /proc/stat as a last resort
        if num == 0:
            search = re.compile(r'cpu\d')
            with open_text('%s/stat' % get_procfs_path()) as f:
                for line in f:
                    line = line.split(' ')[0]
                    if search.match(line):
                        num += 1

        if num == 0:
            # mimic os.cpu_count()
            return None
        return num


def cpu_count_physical():
    """Return the number of physical cores in the system."""
    mapping = {}
    current_info = {}
    with open_binary('%s/cpuinfo' % get_procfs_path()) as f:
        for line in f:
            line = line.strip().lower()
            if not line:
                # new section
                if (b'physical id' in current_info and
                        b'cpu cores' in current_info):
                    mapping[current_info[b'physical id']] = \
                        current_info[b'cpu cores']
                current_info = {}
            else:
                # ongoing section
                if (line.startswith(b'physical id') or
                        line.startswith(b'cpu cores')):
                    key, value = line.split(b'\t:', 1)
                    current_info[key] = int(value)

    # mimic os.cpu_count()
    return sum(mapping.values()) or None


def cpu_stats():
    """Return various CPU stats as a named tuple."""
    with open_binary('%s/stat' % get_procfs_path()) as f:
        ctx_switches = None
        interrupts = None
        soft_interrupts = None
        for line in f:
            if line.startswith(b'ctxt'):
                ctx_switches = int(line.split()[1])
            elif line.startswith(b'intr'):
                interrupts = int(line.split()[1])
            elif line.startswith(b'softirq'):
                soft_interrupts = int(line.split()[1])
            if ctx_switches is not None and soft_interrupts is not None \
                    and interrupts is not None:
                break
    syscalls = 0
    return _common.scpustats(
        ctx_switches, interrupts, soft_interrupts, syscalls)


if os.path.exists("/sys/devices/system/cpu/cpufreq") or \
        os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq"):
    def cpu_freq():
        """Return frequency metrics for all CPUs.
        Contrarily to other OSes, Linux updates these values in
        real-time.
        """
        # scaling_* files seem preferable to cpuinfo_*, see:
        # http://unix.stackexchange.com/a/87537/168884
        ret = []
        ls = glob.glob("/sys/devices/system/cpu/cpufreq/policy*")
        if ls:
            # Sort the list so that '10' comes after '2'. This should
            # ensure the CPU order is consistent with other CPU functions
            # having a 'percpu' argument and returning results for multiple
            # CPUs (cpu_times(), cpu_percent(), cpu_times_percent()).
            ls.sort(key=lambda x: int(os.path.basename(x)[6:]))
        else:
            # https://github.com/giampaolo/psutil/issues/981
            ls = glob.glob("/sys/devices/system/cpu/cpu[0-9]*/cpufreq")
            ls.sort(key=lambda x: int(re.search('[0-9]+', x).group(0)))

        pjoin = os.path.join
        for path in ls:
            curr = cat(pjoin(path, "scaling_cur_freq"), fallback=None)
            if curr is None:
                # Likely an old RedHat, see:
                # https://github.com/giampaolo/psutil/issues/1071
                curr = cat(pjoin(path, "cpuinfo_cur_freq"), fallback=None)
                if curr is None:
                    raise NotImplementedError(
                        "can't find current frequency file")
            curr = int(curr) / 1000
            max_ = int(cat(pjoin(path, "scaling_max_freq"))) / 1000
            min_ = int(cat(pjoin(path, "scaling_min_freq"))) / 1000
            ret.append(_common.scpufreq(curr, min_, max_))
        return ret


# =====================================================================
# --- network
# =====================================================================


net_if_addrs = cext_posix.net_if_addrs


class _Ipv6UnsupportedError(Exception):
    pass


class Connections:
    """A wrapper on top of /proc/net/* files, retrieving per-process
    and system-wide open connections (TCP, UDP, UNIX) similarly to
    "netstat -an".

    Note: in case of UNIX sockets we're only able to determine the
    local endpoint/path, not the one it's connected to.
    According to [1] it would be possible but not easily.

    [1] http://serverfault.com/a/417946
    """

    def __init__(self):
        tcp4 = ("tcp", socket.AF_INET, socket.SOCK_STREAM)
        tcp6 = ("tcp6", socket.AF_INET6, socket.SOCK_STREAM)
        udp4 = ("udp", socket.AF_INET, socket.SOCK_DGRAM)
        udp6 = ("udp6", socket.AF_INET6, socket.SOCK_DGRAM)
        unix = ("unix", socket.AF_UNIX, None)
        self.tmap = {
            "all": (tcp4, tcp6, udp4, udp6, unix),
            "tcp": (tcp4, tcp6),
            "tcp4": (tcp4,),
            "tcp6": (tcp6,),
            "udp": (udp4, udp6),
            "udp4": (udp4,),
            "udp6": (udp6,),
            "unix": (unix,),
            "inet": (tcp4, tcp6, udp4, udp6),
            "inet4": (tcp4, udp4),
            "inet6": (tcp6, udp6),
        }
        self._procfs_path = None

    def get_proc_inodes(self, pid):
        inodes = defaultdict(list)
        for fd in os.listdir("%s/%s/fd" % (self._procfs_path, pid)):
            try:
                inode = readlink("%s/%s/fd/%s" % (self._procfs_path, pid, fd))
            except OSError as err:
                # ENOENT == file which is gone in the meantime;
                # os.stat('/proc/%s' % self.pid) will be done later
                # to force NSP (if it's the case)
                if err.errno in (errno.ENOENT, errno.ESRCH):
                    continue
                elif err.errno == errno.EINVAL:
                    # not a link
                    continue
                else:
                    raise
            else:
                if inode.startswith('socket:['):
                    # the process is using a socket
                    inode = inode[8:][:-1]
                    inodes[inode].append((pid, int(fd)))
        return inodes

    def get_all_inodes(self):
        inodes = {}
        for pid in pids():
            try:
                inodes.update(self.get_proc_inodes(pid))
            except OSError as err:
                # os.listdir() is gonna raise a lot of access denied
                # exceptions in case of unprivileged user; that's fine
                # as we'll just end up returning a connection with PID
                # and fd set to None anyway.
                # Both netstat -an and lsof does the same so it's
                # unlikely we can do any better.
                # ENOENT just means a PID disappeared on us.
                if err.errno not in (
                        errno.ENOENT, errno.ESRCH, errno.EPERM, errno.EACCES):
                    raise
        return inodes

    @staticmethod
    def decode_address(addr, family):
        """Accept an "ip:port" address as displayed in /proc/net/*
        and convert it into a human readable form, like:

        "0500000A:0016" -> ("10.0.0.5", 22)
        "0000000000000000FFFF00000100007F:9E49" -> ("::ffff:127.0.0.1", 40521)

        The IP address portion is a little or big endian four-byte
        hexadecimal number; that is, the least significant byte is listed
        first, so we need to reverse the order of the bytes to convert it
        to an IP address.
        The port is represented as a two-byte hexadecimal number.

        Reference:
        http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html
        """
        ip, port = addr.split(':')
        port = int(port, 16)
        # this usually refers to a local socket in listen mode with
        # no end-points connected
        if not port:
            return ()
        if PY3:
            ip = ip.encode('ascii')
        if family == socket.AF_INET:
            # see: https://github.com/giampaolo/psutil/issues/201
            if LITTLE_ENDIAN:
                ip = socket.inet_ntop(family, base64.b16decode(ip)[::-1])
            else:
                ip = socket.inet_ntop(family, base64.b16decode(ip))
        else:  # IPv6
            # old version - let's keep it, just in case...
            # ip = ip.decode('hex')
            # return socket.inet_ntop(socket.AF_INET6,
            #          ''.join(ip[i:i+4][::-1] for i in xrange(0, 16, 4)))
            ip = base64.b16decode(ip)
            try:
                # see: https://github.com/giampaolo/psutil/issues/201
                if LITTLE_ENDIAN:
                    ip = socket.inet_ntop(
                        socket.AF_INET6,
                        struct.pack('>4I', *struct.unpack('<4I', ip)))
                else:
                    ip = socket.inet_ntop(
                        socket.AF_INET6,
                        struct.pack('<4I', *struct.unpack('<4I', ip)))
            except ValueError:
                # see: https://github.com/giampaolo/psutil/issues/623
                if not supports_ipv6():
                    raise _Ipv6UnsupportedError
                else:
                    raise
        return _common.addr(ip, port)

    @staticmethod
    def process_inet(file, family, type_, inodes, filter_pid=None):
        """Parse /proc/net/tcp* and /proc/net/udp* files."""
        if file.endswith('6') and not os.path.exists(file):
            # IPv6 not supported
            return
        with open_text(file, buffering=BIGFILE_BUFFERING) as f:
            f.readline()  # skip the first line
            for lineno, line in enumerate(f, 1):
                try:
                    _, laddr, raddr, status, _, _, _, _, _, inode = \
                        line.split()[:10]
                except ValueError:
                    raise RuntimeError(
                        "error while parsing %s; malformed line %s %r" % (
                            file, lineno, line))
                if inode in inodes:
                    # # We assume inet sockets are unique, so we error
                    # # out if there are multiple references to the
                    # # same inode. We won't do this for UNIX sockets.
                    # if len(inodes[inode]) > 1 and family != socket.AF_UNIX:
                    #     raise ValueError("ambiguos inode with multiple "
                    #                      "PIDs references")
                    pid, fd = inodes[inode][0]
                else:
                    pid, fd = None, -1
                if filter_pid is not None and filter_pid != pid:
                    continue
                else:
                    if type_ == socket.SOCK_STREAM:
                        status = TCP_STATUSES[status]
                    else:
                        status = _common.CONN_NONE
                    try:
                        laddr = Connections.decode_address(laddr, family)
                        raddr = Connections.decode_address(raddr, family)
                    except _Ipv6UnsupportedError:
                        continue
                    yield (fd, family, type_, laddr, raddr, status, pid)

    @staticmethod
    def process_unix(file, family, inodes, filter_pid=None):
        """Parse /proc/net/unix files."""
        with open_text(file, buffering=BIGFILE_BUFFERING) as f:
            f.readline()  # skip the first line
            for line in f:
                tokens = line.split()
                try:
                    _, _, _, _, type_, _, inode = tokens[0:7]
                except ValueError:
                    if ' ' not in line:
                        # see: https://github.com/giampaolo/psutil/issues/766
                        continue
                    raise RuntimeError(
                        "error while parsing %s; malformed line %r" % (
                            file, line))
                if inode in inodes:
                    # With UNIX sockets we can have a single inode
                    # referencing many file descriptors.
                    pairs = inodes[inode]
                else:
                    pairs = [(None, -1)]
                for pid, fd in pairs:
                    if filter_pid is not None and filter_pid != pid:
                        continue
                    else:
                        if len(tokens) == 8:
                            path = tokens[-1]
                        else:
                            path = ""
                        type_ = int(type_)
                        # XXX: determining the remote endpoint of a
                        # UNIX socket on Linux is not possible, see:
                        # https://serverfault.com/questions/252723/
                        raddr = ""
                        status = _common.CONN_NONE
                        yield (fd, family, type_, path, raddr, status, pid)

    def retrieve(self, kind, pid=None):
        if kind not in self.tmap:
            raise ValueError("invalid %r kind argument; choose between %s"
                             % (kind, ', '.join([repr(x) for x in self.tmap])))
        self._procfs_path = get_procfs_path()
        if pid is not None:
            inodes = self.get_proc_inodes(pid)
            if not inodes:
                # no connections for this process
                return []
        else:
            inodes = self.get_all_inodes()
        ret = set()
        for f, family, type_ in self.tmap[kind]:
            if family in (socket.AF_INET, socket.AF_INET6):
                ls = self.process_inet(
                    "%s/net/%s" % (self._procfs_path, f),
                    family, type_, inodes, filter_pid=pid)
            else:
                ls = self.process_unix(
                    "%s/net/%s" % (self._procfs_path, f),
                    family, inodes, filter_pid=pid)
            for fd, family, type_, laddr, raddr, status, bound_pid in ls:
                if pid:
                    conn = _common.pconn(fd, family, type_, laddr, raddr,
                                         status)
                else:
                    conn = _common.sconn(fd, family, type_, laddr, raddr,
                                         status, bound_pid)
                ret.add(conn)
        return list(ret)


_connections = Connections()


def net_connections(kind='inet'):
    """Return system-wide open connections."""
    return _connections.retrieve(kind)


def net_io_counters():
    """Return network I/O statistics for every network interface
    installed on the system as a dict of raw tuples.
    """
    with open_text("%s/net/dev" % get_procfs_path()) as f:
        lines = f.readlines()
    retdict = {}
    for line in lines[2:]:
        colon = line.rfind(':')
        assert colon > 0, repr(line)
        name = line[:colon].strip()
        fields = line[colon + 1:].strip().split()

        # in
        (bytes_recv,
         packets_recv,
         errin,
         dropin,
         fifoin,  # unused
         framein,  # unused
         compressedin,  # unused
         multicastin,  # unused
         # out
         bytes_sent,
         packets_sent,
         errout,
         dropout,
         fifoout,  # unused
         collisionsout,  # unused
         carrierout,  # unused
         compressedout) = map(int, fields)

        retdict[name] = (bytes_sent, bytes_recv, packets_sent, packets_recv,
                         errin, errout, dropin, dropout)
    return retdict


def net_if_stats():
    """Get NIC stats (isup, duplex, speed, mtu)."""
    duplex_map = {cext.DUPLEX_FULL: NIC_DUPLEX_FULL,
                  cext.DUPLEX_HALF: NIC_DUPLEX_HALF,
                  cext.DUPLEX_UNKNOWN: NIC_DUPLEX_UNKNOWN}
    names = net_io_counters().keys()
    ret = {}
    for name in names:
        mtu = cext_posix.net_if_mtu(name)
        isup = cext_posix.net_if_flags(name)
        duplex, speed = cext.net_if_duplex_speed(name)
        ret[name] = _common.snicstats(isup, duplex_map[duplex], speed, mtu)
    return ret


# =====================================================================
# --- disks
# =====================================================================


disk_usage = _psposix.disk_usage


def disk_io_counters():
    """Return disk I/O statistics for every disk installed on the
    system as a dict of raw tuples.
    """
    # determine partitions we want to look for
    def get_partitions():
        partitions = []
        with open_text("%s/partitions" % get_procfs_path()) as f:
            lines = f.readlines()[2:]
        for line in reversed(lines):
            _, _, _, name = line.split()
            if name[-1].isdigit():
                # we're dealing with a partition (e.g. 'sda1'); 'sda' will
                # also be around but we want to omit it
                partitions.append(name)
            else:
                if not partitions or not partitions[-1].startswith(name):
                    # we're dealing with a disk entity for which no
                    # partitions have been defined (e.g. 'sda' but
                    # 'sda1' was not around), see:
                    # https://github.com/giampaolo/psutil/issues/338
                    partitions.append(name)
        return partitions

    retdict = {}
    partitions = get_partitions()
    with open_text("%s/diskstats" % get_procfs_path()) as f:
        lines = f.readlines()
    for line in lines:
        # OK, this is a bit confusing. The format of /proc/diskstats can
        # have 3 variations.
        # On Linux 2.4 each line has always 15 fields, e.g.:
        # "3     0   8 hda 8 8 8 8 8 8 8 8 8 8 8"
        # On Linux 2.6+ each line *usually* has 14 fields, and the disk
        # name is in another position, like this:
        # "3    0   hda 8 8 8 8 8 8 8 8 8 8 8"
        # ...unless (Linux 2.6) the line refers to a partition instead
        # of a disk, in which case the line has less fields (7):
        # "3    1   hda1 8 8 8 8"
        # See:
        # https://www.kernel.org/doc/Documentation/iostats.txt
        # https://www.kernel.org/doc/Documentation/ABI/testing/procfs-diskstats
        fields = line.split()
        fields_len = len(fields)
        if fields_len == 15:
            # Linux 2.4
            name = fields[3]
            reads = int(fields[2])
            (reads_merged, rbytes, rtime, writes, writes_merged,
                wbytes, wtime, _, busy_time, _) = map(int, fields[4:14])
        elif fields_len == 14:
            # Linux 2.6+, line referring to a disk
            name = fields[2]
            (reads, reads_merged, rbytes, rtime, writes, writes_merged,
                wbytes, wtime, _, busy_time, _) = map(int, fields[3:14])
        elif fields_len == 7:
            # Linux 2.6+, line referring to a partition
            name = fields[2]
            reads, rbytes, writes, wbytes = map(int, fields[3:])
            rtime = wtime = reads_merged = writes_merged = busy_time = 0
        else:
            raise ValueError("not sure how to interpret line %r" % line)

        if name in partitions:
            ssize = get_sector_size(name)
            rbytes *= ssize
            wbytes *= ssize
            retdict[name] = (reads, writes, rbytes, wbytes, rtime, wtime,
                             reads_merged, writes_merged, busy_time)
    return retdict


def disk_partitions(all=False):
    """Return mounted disk partitions as a list of namedtuples."""
    fstypes = set()
    with open_text("%s/filesystems" % get_procfs_path()) as f:
        for line in f:
            line = line.strip()
            if not line.startswith("nodev"):
                fstypes.add(line.strip())
            else:
                # ignore all lines starting with "nodev" except "nodev zfs"
                fstype = line.split("\t")[1]
                if fstype == "zfs":
                    fstypes.add("zfs")

    retlist = []
    partitions = cext.disk_partitions()
    for partition in partitions:
        device, mountpoint, fstype, opts = partition
        if device == 'none':
            device = ''
        if not all:
            if device == '' or fstype not in fstypes:
                continue
        ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
        retlist.append(ntuple)
    return retlist


# =====================================================================
# --- sensors
# =====================================================================


def sensors_temperatures():
    """Return hardware (CPU and others) temperatures as a dict
    including hardware name, label, current, max and critical
    temperatures.

    Implementation notes:
    - /sys/class/hwmon looks like the most recent interface to
      retrieve this info, and this implementation relies on it
      only (old distros will probably use something else)
    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
    - /sys/class/thermal/thermal_zone* is another one but it's more
      difficult to parse
    """
    ret = collections.defaultdict(list)
    basenames = glob.glob('/sys/class/hwmon/hwmon*/temp*_*')
    # CentOS has an intermediate /device directory:
    # https://github.com/giampaolo/psutil/issues/971
    # https://github.com/nicolargo/glances/issues/1060
    basenames.extend(glob.glob('/sys/class/hwmon/hwmon*/device/temp*_*'))
    basenames = sorted(set([x.split('_')[0] for x in basenames]))

    for base in basenames:
        try:
            current = float(cat(base + '_input')) / 1000.0
        except (IOError, OSError) as err:
            # A lot of things can go wrong here, so let's just skip the
            # whole entry.
            # https://github.com/giampaolo/psutil/issues/1009
            # https://github.com/giampaolo/psutil/issues/1101
            # https://github.com/giampaolo/psutil/issues/1129
            warnings.warn("ignoring %r" % err, RuntimeWarning)
            continue

        unit_name = cat(os.path.join(os.path.dirname(base), 'name'),
                        binary=False)
        high = cat(base + '_max', fallback=None)
        critical = cat(base + '_crit', fallback=None)
        label = cat(base + '_label', fallback='', binary=False)

        if high is not None:
            high = float(high) / 1000.0
        if critical is not None:
            critical = float(critical) / 1000.0

        ret[unit_name].append((label, current, high, critical))

    return ret


def sensors_fans():
    """Return hardware fans info (for CPU and other peripherals) as a
    dict including hardware label and current speed.

    Implementation notes:
    - /sys/class/hwmon looks like the most recent interface to
      retrieve this info, and this implementation relies on it
      only (old distros will probably use something else)
    - lm-sensors on Ubuntu 16.04 relies on /sys/class/hwmon
    """
    ret = collections.defaultdict(list)
    basenames = glob.glob('/sys/class/hwmon/hwmon*/fan*_*')
    if not basenames:
        # CentOS has an intermediate /device directory:
        # https://github.com/giampaolo/psutil/issues/971
        basenames = glob.glob('/sys/class/hwmon/hwmon*/device/fan*_*')

    basenames = sorted(set([x.split('_')[0] for x in basenames]))
    for base in basenames:
        try:
            current = int(cat(base + '_input'))
        except (IOError, OSError) as err:
            warnings.warn("ignoring %r" % err, RuntimeWarning)
            continue
        unit_name = cat(os.path.join(os.path.dirname(base), 'name'),
                        binary=False)
        label = cat(base + '_label', fallback='', binary=False)
        ret[unit_name].append(_common.sfan(label, current))

    return dict(ret)


def sensors_battery():
    """Return battery information.
    Implementation note: it appears /sys/class/power_supply/BAT0/
    directory structure may vary and provide files with the same
    meaning but under different names, see:
    https://github.com/giampaolo/psutil/issues/966
    """
    null = object()

    def multi_cat(*paths):
        """Attempt to read the content of multiple files which may
        not exist. If none of them exist return None.
        """
        for path in paths:
            ret = cat(path, fallback=null)
            if ret != null:
                return int(ret) if ret.isdigit() else ret
        return None

    root = os.path.join(POWER_SUPPLY_PATH, "BAT0")
    if not os.path.exists(root):
        return None

    # Base metrics.
    energy_now = multi_cat(
        root + "/energy_now",
        root + "/charge_now")
    power_now = multi_cat(
        root + "/power_now",
        root + "/current_now")
    energy_full = multi_cat(
        root + "/energy_full",
        root + "/charge_full")
    if energy_now is None or power_now is None:
        return None

    # Percent. If we have energy_full the percentage will be more
    # accurate compared to reading /capacity file (float vs. int).
    if energy_full is not None:
        try:
            percent = 100.0 * energy_now / energy_full
        except ZeroDivisionError:
            percent = 0.0
    else:
        percent = int(cat(root + "/capacity", fallback=-1))
        if percent == -1:
            return None

    # Is AC power cable plugged in?
    # Note: AC0 is not always available and sometimes (e.g. CentOS7)
    # it's called "AC".
    power_plugged = None
    online = multi_cat(
        os.path.join(POWER_SUPPLY_PATH, "AC0/online"),
        os.path.join(POWER_SUPPLY_PATH, "AC/online"))
    if online is not None:
        power_plugged = online == 1
    else:
        status = cat(root + "/status", fallback="", binary=False).lower()
        if status == "discharging":
            power_plugged = False
        elif status in ("charging", "full"):
            power_plugged = True

    # Seconds left.
    # Note to self: we may also calculate the charging ETA as per:
    # https://github.com/thialfihar/dotfiles/blob/
    #     013937745fd9050c30146290e8f963d65c0179e6/bin/battery.py#L55
    if power_plugged:
        secsleft = _common.POWER_TIME_UNLIMITED
    else:
        try:
            secsleft = int(energy_now / power_now * 3600)
        except ZeroDivisionError:
            secsleft = _common.POWER_TIME_UNKNOWN

    return _common.sbattery(percent, secsleft, power_plugged)


# =====================================================================
# --- other system functions
# =====================================================================


def users():
    """Return currently connected users as a list of namedtuples."""
    retlist = []
    rawlist = cext.users()
    for item in rawlist:
        user, tty, hostname, tstamp, user_process, pid = item
        # note: the underlying C function includes entries about
        # system boot, run level and others.  We might want
        # to use them in the future.
        if not user_process:
            continue
        if hostname in (':0.0', ':0'):
            hostname = 'localhost'
        nt = _common.suser(user, tty or None, hostname, tstamp, pid)
        retlist.append(nt)
    return retlist


def boot_time():
    """Return the system boot time expressed in seconds since the epoch."""
    global BOOT_TIME
    path = '%s/stat' % get_procfs_path()
    with open_binary(path) as f:
        for line in f:
            if line.startswith(b'btime'):
                ret = float(line.strip().split()[1])
                BOOT_TIME = ret
                return ret
        raise RuntimeError(
            "line 'btime' not found in %s" % path)


# =====================================================================
# --- processes
# =====================================================================


def pids():
    """Returns a list of PIDs currently running on the system."""
    return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]


def pid_exists(pid):
    """Check for the existence of a unix PID. Linux TIDs are not
    supported (always return False).
    """
    if not _psposix.pid_exists(pid):
        return False
    else:
        # Linux's apparently does not distinguish between PIDs and TIDs
        # (thread IDs).
        # listdir("/proc") won't show any TID (only PIDs) but
        # os.stat("/proc/{tid}") will succeed if {tid} exists.
        # os.kill() can also be passed a TID. This is quite confusing.
        # In here we want to enforce this distinction and support PIDs
        # only, see:
        # https://github.com/giampaolo/psutil/issues/687
        try:
            # Note: already checked that this is faster than using a
            # regular expr. Also (a lot) faster than doing
            # 'return pid in pids()'
            path = "%s/%s/status" % (get_procfs_path(), pid)
            with open_binary(path) as f:
                for line in f:
                    if line.startswith(b"Tgid:"):
                        tgid = int(line.split()[1])
                        # If tgid and pid are the same then we're
                        # dealing with a process PID.
                        return tgid == pid
                raise ValueError("'Tgid' line not found in %s" % path)
        except (EnvironmentError, ValueError):
            return pid in pids()


def ppid_map():
    """Obtain a {pid: ppid, ...} dict for all running processes in
    one shot. Used to speed up Process.children().
    """
    ret = {}
    procfs_path = get_procfs_path()
    for pid in pids():
        try:
            with open_binary("%s/%s/stat" % (procfs_path, pid)) as f:
                data = f.read()
        except EnvironmentError as err:
            # Note: we should be able to access /stat for all processes
            # so we won't bump into EPERM, which is good.
            if err.errno not in (errno.ENOENT, errno.ESRCH,
                                 errno.EPERM, errno.EACCES):
                raise
        else:
            rpar = data.rfind(b')')
            dset = data[rpar + 2:].split()
            ppid = int(dset[1])
            ret[pid] = ppid
    return ret


def wrap_exceptions(fun):
    """Decorator which translates bare OSError and IOError exceptions
    into NoSuchProcess and AccessDenied.
    """
    @functools.wraps(fun)
    def wrapper(self, *args, **kwargs):
        try:
            return fun(self, *args, **kwargs)
        except EnvironmentError as err:
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            # ESRCH (no such process) can be raised on read() if
            # process is gone in the meantime.
            if err.errno == errno.ESRCH:
                raise NoSuchProcess(self.pid, self._name)
            # ENOENT (no such file or directory) can be raised on open().
            if err.errno == errno.ENOENT and not os.path.exists("%s/%s" % (
                    self._procfs_path, self.pid)):
                raise NoSuchProcess(self.pid, self._name)
            # Note: zombies will keep existing under /proc until they're
            # gone so there's no way to distinguish them in here.
            raise
    return wrapper


class Process(object):
    """Linux process implementation."""

    __slots__ = ["pid", "_name", "_ppid", "_procfs_path"]

    def __init__(self, pid):
        self.pid = pid
        self._name = None
        self._ppid = None
        self._procfs_path = get_procfs_path()

    @memoize_when_activated
    def _parse_stat_file(self):
        """Parse /proc/{pid}/stat file. Return a list of fields where
        process name is in position 0.
        Using "man proc" as a reference: where "man proc" refers to
        position N, always substract 2 (e.g starttime pos 22 in
        'man proc' == pos 20 in the list returned here).
        The return value is cached in case oneshot() ctx manager is
        in use.
        """
        with open_binary("%s/%s/stat" % (self._procfs_path, self.pid)) as f:
            data = f.read()
        # Process name is between parentheses. It can contain spaces and
        # other parentheses. This is taken into account by looking for
        # the first occurrence of "(" and the last occurence of ")".
        rpar = data.rfind(b')')
        name = data[data.find(b'(') + 1:rpar]
        others = data[rpar + 2:].split()
        return [name] + others

    @memoize_when_activated
    def _read_status_file(self):
        """Read /proc/{pid}/stat file and return its content.
        The return value is cached in case oneshot() ctx manager is
        in use.
        """
        with open_binary("%s/%s/status" % (self._procfs_path, self.pid)) as f:
            return f.read()

    @memoize_when_activated
    def _read_smaps_file(self):
        with open_binary("%s/%s/smaps" % (self._procfs_path, self.pid),
                         buffering=BIGFILE_BUFFERING) as f:
            return f.read().strip()

    def oneshot_enter(self):
        self._parse_stat_file.cache_activate()
        self._read_status_file.cache_activate()
        self._read_smaps_file.cache_activate()

    def oneshot_exit(self):
        self._parse_stat_file.cache_deactivate()
        self._read_status_file.cache_deactivate()
        self._read_smaps_file.cache_deactivate()

    @wrap_exceptions
    def name(self):
        name = self._parse_stat_file()[0]
        if PY3:
            name = decode(name)
        # XXX - gets changed later and probably needs refactoring
        return name

    def exe(self):
        try:
            return readlink("%s/%s/exe" % (self._procfs_path, self.pid))
        except OSError as err:
            if err.errno in (errno.ENOENT, errno.ESRCH):
                # no such file error; might be raised also if the
                # path actually exists for system processes with
                # low pids (about 0-20)
                if os.path.lexists("%s/%s" % (self._procfs_path, self.pid)):
                    return ""
                else:
                    if not pid_exists(self.pid):
                        raise NoSuchProcess(self.pid, self._name)
                    else:
                        raise ZombieProcess(self.pid, self._name, self._ppid)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(self.pid, self._name)
            raise

    @wrap_exceptions
    def cmdline(self):
        with open_text("%s/%s/cmdline" % (self._procfs_path, self.pid)) as f:
            data = f.read()
        if not data:
            # may happen in case of zombie process
            return []
        # 'man proc' states that args are separated by null bytes '\0'
        # and last char is supposed to be a null byte. Nevertheless
        # some processes may change their cmdline after being started
        # (via setproctitle() or similar), they are usually not
        # compliant with this rule and use spaces instead. Google
        # Chrome process is an example. See:
        # https://github.com/giampaolo/psutil/issues/1179
        sep = '\x00' if data.endswith('\x00') else ' '
        if data.endswith(sep):
            data = data[:-1]
        return [x for x in data.split(sep)]

    @wrap_exceptions
    def environ(self):
        with open_text("%s/%s/environ" % (self._procfs_path, self.pid)) as f:
            data = f.read()
        return parse_environ_block(data)

    @wrap_exceptions
    def terminal(self):
        tty_nr = int(self._parse_stat_file()[5])
        tmap = _psposix.get_terminal_map()
        try:
            return tmap[tty_nr]
        except KeyError:
            return None

    if os.path.exists('/proc/%s/io' % os.getpid()):
        @wrap_exceptions
        def io_counters(self):
            fname = "%s/%s/io" % (self._procfs_path, self.pid)
            fields = {}
            with open_binary(fname) as f:
                for line in f:
                    # https://github.com/giampaolo/psutil/issues/1004
                    line = line.strip()
                    if line:
                        name, value = line.split(b': ')
                        fields[name] = int(value)
            if not fields:
                raise RuntimeError("%s file was empty" % fname)
            return pio(
                fields[b'syscr'],  # read syscalls
                fields[b'syscw'],  # write syscalls
                fields[b'read_bytes'],  # read bytes
                fields[b'write_bytes'],  # write bytes
                fields[b'rchar'],  # read chars
                fields[b'wchar'],  # write chars
            )
    else:
        def io_counters(self):
            raise NotImplementedError("couldn't find /proc/%s/io (kernel "
                                      "too old?)" % self.pid)

    @wrap_exceptions
    def cpu_times(self):
        values = self._parse_stat_file()
        utime = float(values[12]) / CLOCK_TICKS
        stime = float(values[13]) / CLOCK_TICKS
        children_utime = float(values[14]) / CLOCK_TICKS
        children_stime = float(values[15]) / CLOCK_TICKS
        return _common.pcputimes(utime, stime, children_utime, children_stime)

    @wrap_exceptions
    def cpu_num(self):
        """What CPU the process is on."""
        return int(self._parse_stat_file()[37])

    @wrap_exceptions
    def wait(self, timeout=None):
        return _psposix.wait_pid(self.pid, timeout, self._name)

    @wrap_exceptions
    def create_time(self):
        values = self._parse_stat_file()
        # According to documentation, starttime is in field 21 and the
        # unit is jiffies (clock ticks).
        # We first divide it for clock ticks and then add uptime returning
        # seconds since the epoch, in UTC.
        # Also use cached value if available.
        bt = BOOT_TIME or boot_time()
        return (float(values[20]) / CLOCK_TICKS) + bt

    @wrap_exceptions
    def memory_info(self):
        #  ============================================================
        # | FIELD  | DESCRIPTION                         | AKA  | TOP  |
        #  ============================================================
        # | rss    | resident set size                   |      | RES  |
        # | vms    | total program size                  | size | VIRT |
        # | shared | shared pages (from shared mappings) |      | SHR  |
        # | text   | text ('code')                       | trs  | CODE |
        # | lib    | library (unused in Linux 2.6)       | lrs  |      |
        # | data   | data + stack                        | drs  | DATA |
        # | dirty  | dirty pages (unused in Linux 2.6)   | dt   |      |
        #  ============================================================
        with open_binary("%s/%s/statm" % (self._procfs_path, self.pid)) as f:
            vms, rss, shared, text, lib, data, dirty = \
                [int(x) * PAGESIZE for x in f.readline().split()[:7]]
        return pmem(rss, vms, shared, text, lib, data, dirty)

    # /proc/pid/smaps does not exist on kernels < 2.6.14 or if
    # CONFIG_MMU kernel configuration option is not enabled.
    if HAS_SMAPS:

        @wrap_exceptions
        def memory_full_info(
                self,
                _private_re=re.compile(br"Private.*:\s+(\d+)"),
                _pss_re=re.compile(br"Pss.*:\s+(\d+)"),
                _swap_re=re.compile(br"Swap.*:\s+(\d+)")):
            basic_mem = self.memory_info()
            # Note: using 3 regexes is faster than reading the file
            # line by line.
            # XXX: on Python 3 the 2 regexes are 30% slower than on
            # Python 2 though. Figure out why.
            #
            # You might be tempted to calculate USS by subtracting
            # the "shared" value from the "resident" value in
            # /proc/<pid>/statm. But at least on Linux, statm's "shared"
            # value actually counts pages backed by files, which has
            # little to do with whether the pages are actually shared.
            # /proc/self/smaps on the other hand appears to give us the
            # correct information.
            smaps_data = self._read_smaps_file()
            # Note: smaps file can be empty for certain processes.
            # The code below will not crash though and will result to 0.
            uss = sum(map(int, _private_re.findall(smaps_data))) * 1024
            pss = sum(map(int, _pss_re.findall(smaps_data))) * 1024
            swap = sum(map(int, _swap_re.findall(smaps_data))) * 1024
            return pfullmem(*basic_mem + (uss, pss, swap))

    else:
        memory_full_info = memory_info

    if HAS_SMAPS:

        @wrap_exceptions
        def memory_maps(self):
            """Return process's mapped memory regions as a list of named
            tuples. Fields are explained in 'man proc'; here is an updated
            (Apr 2012) version: http://goo.gl/fmebo
            """
            def get_blocks(lines, current_block):
                data = {}
                for line in lines:
                    fields = line.split(None, 5)
                    if not fields[0].endswith(b':'):
                        # new block section
                        yield (current_block.pop(), data)
                        current_block.append(line)
                    else:
                        try:
                            data[fields[0]] = int(fields[1]) * 1024
                        except ValueError:
                            if fields[0].startswith(b'VmFlags:'):
                                # see issue #369
                                continue
                            else:
                                raise ValueError("don't know how to inte"
                                                 "rpret line %r" % line)
                yield (current_block.pop(), data)

            data = self._read_smaps_file()
            # Note: smaps file can be empty for certain processes.
            if not data:
                return []
            lines = data.split(b'\n')
            ls = []
            first_line = lines.pop(0)
            current_block = [first_line]
            for header, data in get_blocks(lines, current_block):
                hfields = header.split(None, 5)
                try:
                    addr, perms, offset, dev, inode, path = hfields
                except ValueError:
                    addr, perms, offset, dev, inode, path = \
                        hfields + ['']
                if not path:
                    path = '[anon]'
                else:
                    if PY3:
                        path = decode(path)
                    path = path.strip()
                    if (path.endswith(' (deleted)') and not
                            path_exists_strict(path)):
                        path = path[:-10]
                ls.append((
                    decode(addr), decode(perms), path,
                    data[b'Rss:'],
                    data.get(b'Size:', 0),
                    data.get(b'Pss:', 0),
                    data.get(b'Shared_Clean:', 0),
                    data.get(b'Shared_Dirty:', 0),
                    data.get(b'Private_Clean:', 0),
                    data.get(b'Private_Dirty:', 0),
                    data.get(b'Referenced:', 0),
                    data.get(b'Anonymous:', 0),
                    data.get(b'Swap:', 0)
                ))
            return ls

    else:  # pragma: no cover
        def memory_maps(self):
            raise NotImplementedError(
                "/proc/%s/smaps does not exist on kernels < 2.6.14 or "
                "if CONFIG_MMU kernel configuration option is not "
                "enabled." % self.pid)

    @wrap_exceptions
    def cwd(self):
        try:
            return readlink("%s/%s/cwd" % (self._procfs_path, self.pid))
        except OSError as err:
            # https://github.com/giampaolo/psutil/issues/986
            if err.errno in (errno.ENOENT, errno.ESRCH):
                if not pid_exists(self.pid):
                    raise NoSuchProcess(self.pid, self._name)
                else:
                    raise ZombieProcess(self.pid, self._name, self._ppid)
            raise

    @wrap_exceptions
    def num_ctx_switches(self,
                         _ctxsw_re=re.compile(br'ctxt_switches:\t(\d+)')):
        data = self._read_status_file()
        ctxsw = _ctxsw_re.findall(data)
        if not ctxsw:
            raise NotImplementedError(
                "'voluntary_ctxt_switches' and 'nonvoluntary_ctxt_switches'"
                "lines were not found in %s/%s/status; the kernel is "
                "probably older than 2.6.23" % (
                    self._procfs_path, self.pid))
        else:
            return _common.pctxsw(int(ctxsw[0]), int(ctxsw[1]))

    @wrap_exceptions
    def num_threads(self, _num_threads_re=re.compile(br'Threads:\t(\d+)')):
        # Note: on Python 3 using a re is faster than iterating over file
        # line by line. On Python 2 is the exact opposite, and iterating
        # over a file on Python 3 is slower than on Python 2.
        data = self._read_status_file()
        return int(_num_threads_re.findall(data)[0])

    @wrap_exceptions
    def threads(self):
        thread_ids = os.listdir("%s/%s/task" % (self._procfs_path, self.pid))
        thread_ids.sort()
        retlist = []
        hit_enoent = False
        for thread_id in thread_ids:
            fname = "%s/%s/task/%s/stat" % (
                self._procfs_path, self.pid, thread_id)
            try:
                with open_binary(fname) as f:
                    st = f.read().strip()
            except IOError as err:
                if err.errno == errno.ENOENT:
                    # no such file or directory; it means thread
                    # disappeared on us
                    hit_enoent = True
                    continue
                raise
            # ignore the first two values ("pid (exe)")
            st = st[st.find(b')') + 2:]
            values = st.split(b' ')
            utime = float(values[11]) / CLOCK_TICKS
            stime = float(values[12]) / CLOCK_TICKS
            ntuple = _common.pthread(int(thread_id), utime, stime)
            retlist.append(ntuple)
        if hit_enoent:
            # raise NSP if the process disappeared on us
            os.stat('%s/%s' % (self._procfs_path, self.pid))
        return retlist

    @wrap_exceptions
    def nice_get(self):
        # with open_text('%s/%s/stat' % (self._procfs_path, self.pid)) as f:
        #   data = f.read()
        #   return int(data.split()[18])

        # Use C implementation
        return cext_posix.getpriority(self.pid)

    @wrap_exceptions
    def nice_set(self, value):
        return cext_posix.setpriority(self.pid, value)

    @wrap_exceptions
    def cpu_affinity_get(self):
        return cext.proc_cpu_affinity_get(self.pid)

    def _get_eligible_cpus(
            self, _re=re.compile(br"Cpus_allowed_list:\t(\d+)-(\d+)")):
        # See: https://github.com/giampaolo/psutil/issues/956
        data = self._read_status_file()
        match = _re.findall(data)
        if match:
            return list(range(int(match[0][0]), int(match[0][1]) + 1))
        else:
            return list(range(len(per_cpu_times())))

    @wrap_exceptions
    def cpu_affinity_set(self, cpus):
        try:
            cext.proc_cpu_affinity_set(self.pid, cpus)
        except (OSError, ValueError) as err:
            if isinstance(err, ValueError) or err.errno == errno.EINVAL:
                eligible_cpus = self._get_eligible_cpus()
                all_cpus = tuple(range(len(per_cpu_times())))
                for cpu in cpus:
                    if cpu not in all_cpus:
                        raise ValueError(
                            "invalid CPU number %r; choose between %s" % (
                                cpu, eligible_cpus))
                    if cpu not in eligible_cpus:
                        raise ValueError(
                            "CPU number %r is not eligible; choose "
                            "between %s" % (cpu, eligible_cpus))
            raise

    # only starting from kernel 2.6.13
    if hasattr(cext, "proc_ioprio_get"):

        @wrap_exceptions
        def ionice_get(self):
            ioclass, value = cext.proc_ioprio_get(self.pid)
            if enum is not None:
                ioclass = IOPriority(ioclass)
            return _common.pionice(ioclass, value)

        @wrap_exceptions
        def ionice_set(self, ioclass, value):
            if value is not None:
                if not PY3 and not isinstance(value, (int, long)):
                    msg = "value argument is not an integer (gor %r)" % value
                    raise TypeError(msg)
                if not 0 <= value <= 7:
                    raise ValueError(
                        "value argument range expected is between 0 and 7")

            if ioclass in (IOPRIO_CLASS_NONE, None):
                if value:
                    msg = "can't specify value with IOPRIO_CLASS_NONE " \
                          "(got %r)" % value
                    raise ValueError(msg)
                ioclass = IOPRIO_CLASS_NONE
                value = 0
            elif ioclass == IOPRIO_CLASS_IDLE:
                if value:
                    msg = "can't specify value with IOPRIO_CLASS_IDLE " \
                          "(got %r)" % value
                    raise ValueError(msg)
                value = 0
            elif ioclass in (IOPRIO_CLASS_RT, IOPRIO_CLASS_BE):
                if value is None:
                    # TODO: add comment explaining why this is 4 (?)
                    value = 4
            else:
                # otherwise we would get OSError(EVINAL)
                raise ValueError("invalid ioclass argument %r" % ioclass)

            return cext.proc_ioprio_set(self.pid, ioclass, value)

    if HAS_PRLIMIT:
        @wrap_exceptions
        def rlimit(self, resource, limits=None):
            # If pid is 0 prlimit() applies to the calling process and
            # we don't want that. We should never get here though as
            # PID 0 is not supported on Linux.
            if self.pid == 0:
                raise ValueError("can't use prlimit() against PID 0 process")
            try:
                if limits is None:
                    # get
                    return cext.linux_prlimit(self.pid, resource)
                else:
                    # set
                    if len(limits) != 2:
                        raise ValueError(
                            "second argument must be a (soft, hard) tuple, "
                            "got %s" % repr(limits))
                    soft, hard = limits
                    cext.linux_prlimit(self.pid, resource, soft, hard)
            except OSError as err:
                if err.errno == errno.ENOSYS and pid_exists(self.pid):
                    # I saw this happening on Travis:
                    # https://travis-ci.org/giampaolo/psutil/jobs/51368273
                    raise ZombieProcess(self.pid, self._name, self._ppid)
                else:
                    raise

    @wrap_exceptions
    def status(self):
        letter = self._parse_stat_file()[1]
        if PY3:
            letter = letter.decode()
        # XXX is '?' legit? (we're not supposed to return it anyway)
        return PROC_STATUSES.get(letter, '?')

    @wrap_exceptions
    def open_files(self):
        retlist = []
        files = os.listdir("%s/%s/fd" % (self._procfs_path, self.pid))
        hit_enoent = False
        for fd in files:
            file = "%s/%s/fd/%s" % (self._procfs_path, self.pid, fd)
            try:
                path = readlink(file)
            except OSError as err:
                # ENOENT == file which is gone in the meantime
                if err.errno in (errno.ENOENT, errno.ESRCH):
                    hit_enoent = True
                    continue
                elif err.errno == errno.EINVAL:
                    # not a link
                    continue
                else:
                    raise
            else:
                # If path is not an absolute there's no way to tell
                # whether it's a regular file or not, so we skip it.
                # A regular file is always supposed to be have an
                # absolute path though.
                if path.startswith('/') and isfile_strict(path):
                    # Get file position and flags.
                    file = "%s/%s/fdinfo/%s" % (
                        self._procfs_path, self.pid, fd)
                    try:
                        with open_binary(file) as f:
                            pos = int(f.readline().split()[1])
                            flags = int(f.readline().split()[1], 8)
                    except IOError as err:
                        if err.errno == errno.ENOENT:
                            # fd gone in the meantime; does not
                            # necessarily mean the process disappeared
                            # on us.
                            hit_enoent = True
                        else:
                            raise
                    else:
                        mode = file_flags_to_mode(flags)
                        ntuple = popenfile(
                            path, int(fd), int(pos), mode, flags)
                        retlist.append(ntuple)
        if hit_enoent:
            # raise NSP if the process disappeared on us
            os.stat('%s/%s' % (self._procfs_path, self.pid))
        return retlist

    @wrap_exceptions
    def connections(self, kind='inet'):
        ret = _connections.retrieve(kind, self.pid)
        # raise NSP if the process disappeared on us
        os.stat('%s/%s' % (self._procfs_path, self.pid))
        return ret

    @wrap_exceptions
    def num_fds(self):
        return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))

    @wrap_exceptions
    def ppid(self):
        return int(self._parse_stat_file()[2])

    @wrap_exceptions
    def uids(self, _uids_re=re.compile(br'Uid:\t(\d+)\t(\d+)\t(\d+)')):
        data = self._read_status_file()
        real, effective, saved = _uids_re.findall(data)[0]
        return _common.puids(int(real), int(effective), int(saved))

    @wrap_exceptions
    def gids(self, _gids_re=re.compile(br'Gid:\t(\d+)\t(\d+)\t(\d+)')):
        data = self._read_status_file()
        real, effective, saved = _gids_re.findall(data)[0]
        return _common.pgids(int(real), int(effective), int(saved))
_psutil_posix.cpython-36m-x86_64-linux-gnu.so000075500000040750150466730550015002 0ustar00ELF>�@�:@8	@�'�' p,p, p, �� �,�, �, 888$$�'�'�'  S�td�'�'�'  P�td�#�#�#��Q�tdR�tdp,p, p, ��GNU����>�O~�ծO�|��'� 	UR '-2BE��,>o���|�ȷԸfW�~���:hde�qX.����H���$���r:,��j% ��]@rx��c� q�C���R~�p�, �F"��c�@1 ����P1 1`!WU��I�D1 H�!��@1 ��3H1 }`"�0__gmon_start___ITM_deregisterTMCloneTable_ITM_registerTMCloneTable__cxa_finalizeNoSuchProcessPyExc_OSErrorPyObject_CallFunctionPyErr_SetObjectstrerrorAccessDeniedpsutil_set_testingPSUTIL_TESTING_Py_NoneStructpsutil_debugstderrfwrite__vfprintf_chkfputc__stack_chk_failpsutil_setupgetenvPSUTIL_DEBUGPyModule_GetStatePyArg_ParseTuplesocketstrncpyioctlclose_Py_TrueStructPy_BuildValuePyErr_SetFromErrno_Py_FalseStructgetnameinfo__sprintf_chkPyList_NewgetifaddrsPyList_Appendfreeifaddrssetpriority__errno_locationgetprioritypsutil_pid_existskillpsutil_raise_for_pidPyExc_RuntimeErrorPyErr_FormatPyInit__psutil_posixPyModule_Create2libpython3.6m.so.1.0libpthread.so.0libc.so.6_edata__bss_start_endGLIBC_2.2.5GLIBC_2.3GLIBC_2.4GLIBC_2.3.4� ui	��ii
�ii
ti	
ui	�p, �x, `�, �, (0 �"@0 �0 P0 �X0  �0 �"�0 � �0 �"�0 #�0 0 �0 #�0 2#�0 ��0 ?#�0 Y#�0 ��0 d#1 u#1 �1 �#�/ �/ �/ �/ �/ �/ -�/ �/ �/ 1�/ !�/ #�/ $�. �. �. �. �. �. �. �. 	�. 
�. (�. �. 
/ / / /  / (/ 0/ 8/ @/ H/ P/ X/ *`/ +h/ p/ x/  �/ "�/ #�/ %�/ &��H��H�� H��t��H����5� �%� ��h�������h��������h�������h�������h�������h�������h�������h��q������h��a������h	��Q������h
��A������h��1������h��!������h
��������h��������h������h�������h��������h�������h�������h�������h�������h�������h��q������h��a������h��Q������h��A������h��1������h��!������h��������h��������h�������%� D���%� D���%� D���%� D���%� D���%} D���%u D���%m D���%e D���%] D���%U D���%M D���%E D���%= D���%5 D���%- D���%% D���% D���% D���%
 D���% D���%� D���%� D���%� D���%� D���%� D���%� D���%� D���%� D���%� D���%� D���%� DH�=I H�B H9�tH�� H��t	�����H�= H�5 H)�H��H��H��?H�H�tH�� H��t��fD�����=� u+UH�=z H��tH�=� �9����d����� ]������w������UH��SH���?t^H�-� H�5�1��H�}� ���H�}H��H���q���H��tH�+tH��1�[]�DH�CH��P0H��1�[]�D����H��듐��UH��SH���?t^H�-g H�581��
H�}���H�}H��H����H��tH�+tH��1�[]�DH�CH��P0H��1�[]�D�
����H��듐��H�
 �H� H����UH��SH���H�t$(H�T$0H�L$8L�D$@L�L$H��t7)D$P)L$`)T$p)�$�)�$�)�$�)�$�)�$�dH�%(H�D$1���H�� H��$�H�=)
�$H�H�D$H�D$ �D$0H�D$����H�;H��H���s���H�3�
�6���H�D$dH3%(u
H���[]�������H��H�=�	����H��t
H�� �H�=�	���H��t
H�� �H������UH��SH���^���H�H��tH���N���H�H�+tH��1�[]��H�CH��P0H��1�[]�ff.�f���ATI��UH��SH�����H�8tH�����[L��H�8H��]A\��D[1�]A\Ð��SH��H�5�	H��@dH�%(H�D$81�H�T$�c�����1���tk1Ҿ������Ã��t{H�L$H�t$�H����������H��1��{������tF�������D$ tXH�5� H�=b1����H�L$8dH3%(uGH��@[�f.���t@���1���H� H�8����H�5 H�=
1��[�������@��SH��H�5�H��@dH�%(H�D$81�H�T$�c�����1���t^1Ҿ������Ã��tkH�L$H�t$�H�������!���H��1��{������t6�������t$ H�=~1����H�L$8dH3%(u-H��@[����t@���A���H�* H�8����������ff.�AWAVAUATUSH��dH�%(H��$1�H��t'����tU��uD�wM����f.�H�� H�H��$dH3%(��H��[]A\A]A^A_�@����H��E�H���H��jE1�E1��|���ZY��u�H��H�=/1�����I��H��N�,7L��L�%6@D�CH��L���1�H��H���$���L9�u�K�vL��H�=��D�1��E����+������ff.���AW1�AVAUATUSH��(dH�%(H�D$1����H�D$H����H�|$���������H�\$H�����h���H�� H�I��I��H��H�sD��M��ATI��L��H�=J1����I��XZM����H�|$L���X�������I�.u
I�FL���P0I�/u
I�GL���P0H�mu
H�EH��P0I�mu
I�EL��P0I�,$uI�D$L��P0H�H����H�{H��t�D�7D�����H;� I��t�H����H�{ D���j���H��H�����C���H�{(D���G���L�%p I��H�f H�M����������E1�H�|$H��t��H�T$H�H�D$H��H���M��tI�.u
I�FL���P0M��tI�/u
I�GL���P0H��tH�mu
H�EH��P0M��tI�mu
I�EL��P0M��tI�,$��H�D$H�L$dH3%(H�D$��H��([]A\A]A^A_ÐH�{(D���T���L�-} I��H�s H�M��������@H�BH��P0M���*����5����I�D$L��P0�n���H�\$H�������e���fDH�|$E1�E1�1�E1�H����������f.�H�|$E1�E1�E1�H����������H�� E1�E1�1�E1�E1�H�8�7��a����M�ff.�f���H��(H��H�5�dH�%(H�D$1�H�T$H�L$���1҅�t�T$�t$1��*���t%H�N H�H�t$dH34%(H��uH��(�f�H�	 H�8��H���������UH��SH��dH�%(H�D$1��>�H��H�5�H���H��1��Q��1���t �4$1��/���u)��H�=�1����H�L$dH3%(uH��[]�f�H�i H�8������f.���H��1��@H��1���¸��t,����t��tH� H�8�������1�H���f���UH��SH��H���K���ueH���}��t)H��
 H��H�5�H�81���H��1�[]�DH��H��H�={�^�H�=r�B�H��1�[]�f�H�i
 H�8��H��1�[]������H�=�
 ����H��H���(is)psutil-dubug> PSUTIL_DEBUGPSUTIL_TESTINGO%02x:(siOOOO)lil%s syscall failedpsutil_posixgetpriorityReturn process prioritysetprioritySet process prioritynet_if_addrsRetrieve NICs informationnet_if_mtuRetrieve NIC MTUnet_if_flagsRetrieve NIC flags%s syscall failed and PID %i no longer exists; assume NoSuchProcess;�������P�0��h��|��@�����������,��P����t����P���,��H����t��������zRx�$@�FJw�?:*3$"D(�4\��E�D�D A
CAFN
CAF4��E�D�D A
CAFN
CAF�`�(�l�E�D�G��
AAA@�IH@0$x�SE�D�D f
CAINCA4X��?F�D�D �W
JBGACB ���E�NP�
AK ����E�NP�
AHX�D���5B�B�B �B(�A0�A8�G�h
8A0A(B BBBEW�J�L�A�X4(���CF�D�B �B(�A0�A8�D`ihLpXhA`�
8A0A(B BBBB�����H0e
C(������E�D�D0n
AAC����WTB<�L����E�D�G v
CAFb
CAJSCA0����GNU��`�, ����
x"p, x, ���o`��
�. ��0	���o���o ���o�o�
���o�, � 0@P`p�������� 0@P`p��������"�0 � �"� �"#0 #2#�?#Y#�d#u#��#GA$3a1��"
GA$3p965�GA*GA$annobin gcc 8.5.0 20210514GA$running gcc 8.5.0 20210514GA*GA*GA!
GA*FORTIFYGA+GLIBCXX_ASSERTIONSGA*GOW*�GA*cf_protectionGA+omit_frame_pointerGA+stack_clashGA!stack_realign
GA$3p965 u"GA*GA$annobin gcc 8.5.0 20210514GA$running gcc 8.5.0 20210514GA*GA*GA!
GA*FORTIFYGA+GLIBCXX_ASSERTIONSGA*GOW*�GA*cf_protectionGA+omit_frame_pointerGA+stack_clashGA!stack_realign
GA*FORTIFY�sGA+GLIBCXX_ASSERTIONSGA*cf_protection_psutil_posix.cpython-36m-x86_64-linux-gnu.so-5.4.3-11.el8.x86_64.debug
N�;�7zXZ�ִF!t/��g�]?�E�h=��ڊ�2N�	=�7��e���X�Cm��?#g9W��^2:�0��j�r�u|�2���r�S�
w��=D����L�<I8=��`kxޙ��ܒ��+�10�ɢ8Q�Ռ9��P,��j8]U���g,!��	��',����*��l>f���4��vF^��=$T���Wd�֞>L���HlJ�Ҳ{��4��сl��q�0�;rO�]>	�LU8�<]-���ښbYB��2l�|��É���D�q�>��\=�t�;��1�M��f��[��
B�9<�ص�iCt��^���@�Q۱u�,3ޏ:_�8�qp�Hʧ��t/Wh)���5��m�H�{��w|��@9���c~����n*����Z��}��Vi�"f��v�{���C^z7��ҳȲ�'<���9�k�m��p˞�-M���V�+�{���jaKp`Y19��yc5Ime��oE�'�{:�?��=���UX�L�B�+��^��dK�GB��;9xsҔ����XG.�/�;&��ͅ
,���&�� �v�I��츛5
��&�Ӯ[N*�����=	1���,yi�u����8:�t���j�a�G  ��(/R$��!���l�1�i�踋-���̍|�F�pIv#彭�Z��2�\�Z��ɀ楛�[<�m�7ΛC�p��}B�p�j�*���c/>����H?ׁ�����ozw���!Ђ$�xr�v�N1�0��i�.�Y����k�"���'}�We��x�-�8-Q�+�I�j_���vw`�+����[�d�ݍA�ٵHV���hrk�^��>R�����j7�῎�>*pߨhK�Obh ��T�/ }��Es�S�oLS�݌��
�|��h��*�_C�0I��z�f�76i�\�&sr�͙5�?�|/�8�UiӇ%�^���L4v�-{'��uյ����wK�X�F�� ˭z��g�YZ.shstrtab.note.gnu.build-id.gnu.hash.dynsym.dynstr.gnu.version.gnu.version_r.rela.dyn.rela.plt.init.plt.sec.text.fini.rodata.eh_frame_hdr.eh_frame.note.gnu.property.init_array.fini_array.data.rel.ro.dynamic.got.data.bss.gnu.build.attributes.gnu_debuglink.gnu_debugdata88$���o```(���0��8���o�
�
hE���o  pT��0^B��h��c��n��w���}x"x"
�2�"�"X��#�#���$�$D��'�' �p, p,�x, x,��, �,��, �,��. �.x�0 0@ �@1 @1�P1`@1�
$5Lp5|9(