author Alexandre Poirot <>
Wed, 04 Nov 2015 08:56:00 +0100
changeset 307645 f4c516bc60ee0a50885a73c8e9a97b8bb8e58162
parent 286873 2eea7ab5228dde61fdc8706ea8452df10da6dd1d
permissions -rw-r--r--
Bug 1221238 - Fix devtools filter popup inputs width on linux. r=pbrosset

#!/usr/bin/env python

# 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 errno
import functools
import os
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 conn_tmap, usage_percent, isfile_strict
from ._common import sockfam_to_enum, socktype_to_enum

__extra__all__ = []

# --- constants

PAGESIZE = os.sysconf("SC_PAGE_SIZE")
AF_LINK = cext_posix.AF_LINK

    cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
    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_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.SIDL: _common.STATUS_IDLE,
    cext.SRUN: _common.STATUS_RUNNING,
    cext.SSLEEP: _common.STATUS_SLEEPING,
    cext.SSTOP: _common.STATUS_STOPPED,
    cext.SZOMB: _common.STATUS_ZOMBIE,

scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle'])

svmem = namedtuple(
    'svmem', ['total', 'available', 'percent', 'used', 'free',
              'active', 'inactive', 'wired'])

pextmem = namedtuple('pextmem', ['rss', 'vms', 'pfaults', 'pageins'])

pmmap_grouped = namedtuple(
    'path rss private swapped dirtied ref_count shadow_depth')

pmmap_ext = namedtuple(
    'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))

# set later from
NoSuchProcess = None
ZombieProcess = None
AccessDenied = None
TimeoutExpired = None

# --- functions

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)

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)
    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 boot_time():
    """The system boot time expressed in seconds since the epoch."""
    return cext.boot_time()

def disk_partitions(all=False):
    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):
        ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
    return retlist

def users():
    retlist = []
    rawlist = cext.users()
    for item in rawlist:
        user, tty, hostname, tstamp = item
        if tty == '~':
            continue  # reboot or shutdown
        if not tstamp:
        nt = _common.suser(user, tty or None, hostname or None, tstamp)
    return retlist

def net_connections(kind='inet'):
    # Note: on OSX this will fail with AccessDenied unless
    # the process is owned by root.
    ret = []
    for pid in pids():
            cons = Process(pid).connections(kind)
        except NoSuchProcess:
            if cons:
                for c in cons:
                    c = list(c) + [pid]
    return ret

def net_if_stats():
    """Get NIC stats (isup, duplex, speed, mtu)."""
    names = net_io_counters().keys()
    ret = {}
    for name in names:
        isup, duplex, speed, mtu = cext_posix.net_if_stats(name)
        if hasattr(_common, 'NicDuplex'):
            duplex = _common.NicDuplex(duplex)
        ret[name] = _common.snicstats(isup, duplex, speed, mtu)
    return ret

pids = cext.pids
pid_exists = _psposix.pid_exists
disk_usage = _psposix.disk_usage
net_io_counters = cext.net_io_counters
disk_io_counters = cext.disk_io_counters
net_if_addrs = cext_posix.net_if_addrs

def wrap_exceptions(fun):
    """Decorator which translates bare OSError exceptions into
    NoSuchProcess and AccessDenied.
    def wrapper(self, *args, **kwargs):
            return fun(self, *args, **kwargs)
        except OSError as err:
            # support for private module import
            if (NoSuchProcess is None or AccessDenied is None or
                    ZombieProcess is None):
            if err.errno == errno.ESRCH:
                if not pid_exists(
                    raise NoSuchProcess(, self._name)
                    raise ZombieProcess(, self._name, self._ppid)
            if err.errno in (errno.EPERM, errno.EACCES):
                raise AccessDenied(, self._name)
    return wrapper

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

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

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

    def name(self):
        return cext.proc_name(

    def exe(self):
        return cext.proc_exe(

    def cmdline(self):
        if not pid_exists(
            raise NoSuchProcess(, self._name)
        return cext.proc_cmdline(

    def ppid(self):
        return cext.proc_ppid(

    def cwd(self):
        return cext.proc_cwd(

    def uids(self):
        real, effective, saved = cext.proc_uids(
        return _common.puids(real, effective, saved)

    def gids(self):
        real, effective, saved = cext.proc_gids(
        return _common.pgids(real, effective, saved)

    def terminal(self):
        tty_nr = cext.proc_tty_nr(
        tmap = _psposix._get_terminal_map()
            return tmap[tty_nr]
        except KeyError:
            return None

    def memory_info(self):
        rss, vms = cext.proc_memory_info([:2]
        return _common.pmem(rss, vms)

    def memory_info_ex(self):
        rss, vms, pfaults, pageins = cext.proc_memory_info(
        return pextmem(rss, vms, pfaults * PAGESIZE, pageins * PAGESIZE)

    def cpu_times(self):
        user, system = cext.proc_cpu_times(
        return _common.pcputimes(user, system)

    def create_time(self):
        return cext.proc_create_time(

    def num_ctx_switches(self):
        return _common.pctxsw(*cext.proc_num_ctx_switches(

    def num_threads(self):
        return cext.proc_num_threads(

    def open_files(self):
        if == 0:
            return []
        files = []
        rawlist = cext.proc_open_files(
        for path, fd in rawlist:
            if isfile_strict(path):
                ntuple = _common.popenfile(path, fd)
        return files

    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]
        rawlist = cext.proc_connections(, 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)
            nt = _common.pconn(fd, fam, type, laddr, raddr, status)
        return ret

    def num_fds(self):
        if == 0:
            return 0
        return cext.proc_num_fds(

    def wait(self, timeout=None):
            return _psposix.wait_pid(, timeout)
        except _psposix.TimeoutExpired:
            # support for private module import
            if TimeoutExpired is None:
            raise TimeoutExpired(timeout,, self._name)

    def nice_get(self):
        return cext_posix.getpriority(

    def nice_set(self, value):
        return cext_posix.setpriority(, value)

    def status(self):
        code = cext.proc_status(
        # XXX is '?' legit? (we're not supposed to return it anyway)
        return PROC_STATUSES.get(code, '?')

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

    def memory_maps(self):
        return cext.proc_memory_maps(