~ubuntu-branches/ubuntu/oneiric/python-psutil/oneiric

« back to all changes in this revision

Viewing changes to psutil/_psbsd.py

  • Committer: Bazaar Package Importer
  • Author(s): Sandro Tosi
  • Date: 2011-04-04 20:26:42 UTC
  • mfrom: (2.1.3 sid)
  • Revision ID: james.westby@ubuntu.com-20110404202642-u2fyar19eabqb2mn
Tags: 0.2.1-1
* New upstream release
* debian/copyright
  - extended packaging copyright years
* debian/rules
  - use the correct PYTHONPATH when running tests, for all supported versions
* debian/control
  - it now contains also extensions, so it's an arch:any package
  - move python-support from b-d-i to b-d
  - we now need python-all-dev in b-d
  - added procps to b-d, needed to run tests
* debian/{control, pyversion}
  - removed pyversion, replaced by XS-P-V field

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/env python
2
2
#
3
 
# $Id: _psbsd.py 519 2010-02-23 23:18:51Z billiejoex@gmail.com $
 
3
# $Id: _psbsd.py 944 2011-03-04 17:05:24Z g.rodola $
4
4
#
5
5
 
 
6
import errno
6
7
import os
7
 
import signal
8
 
import errno
9
 
import pwd
10
 
import grp
11
8
 
12
9
import _psutil_bsd
13
 
 
14
 
# import psutil exceptions we can override with our own
15
 
from error import *
16
 
 
17
 
# module level constants (gets pushed up to psutil module)
18
 
NoSuchProcess = _psutil_bsd.NoSuchProcess
 
10
import _psutil_posix
 
11
import _psposix
 
12
from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
 
13
from psutil._compat import namedtuple
 
14
from psutil._common import *
 
15
 
 
16
__all__ = base_module_namespace[:]
 
17
 
 
18
# --- constants
 
19
 
19
20
NUM_CPUS = _psutil_bsd.get_num_cpus()
20
21
TOTAL_PHYMEM = _psutil_bsd.get_total_phymem()
 
22
BOOT_TIME = _psutil_bsd.get_system_boot_time()
 
23
 
 
24
# --- public functions
21
25
 
22
26
def avail_phymem():
23
27
    "Return the amount of physical memory available on the system, in bytes."
39
43
    """Return the amount of used memory currently in use on the system, in bytes."""
40
44
    return _psutil_bsd.get_total_virtmem() - _psutil_bsd.get_avail_virtmem()
41
45
 
 
46
_cputimes_ntuple = namedtuple('cputimes', 'user nice system idle irq')
42
47
def get_system_cpu_times():
43
 
    """Return a dict representing the following CPU times:
44
 
    user, nice, system, idle, interrupt."""
45
 
    values = _psutil_bsd.get_system_cpu_times()
46
 
    return dict(user=values[0], nice=values[1], system=values[2],
47
 
        idle=values[3], irq=values[4])
48
 
 
49
 
 
50
 
def wrap_privileges(callable):
51
 
    """Call callable into a try/except clause so that if an
52
 
    OSError EPERM exception is raised we translate it into
53
 
    psutil.AccessDenied.
54
 
    """
55
 
    def wrapper(*args, **kwargs):
56
 
        try:
57
 
            return callable(*args, **kwargs)
58
 
        except OSError, err:
59
 
            if err.errno == errno.EPERM:
60
 
                raise AccessDenied
61
 
            raise
62
 
    return wrapper
63
 
 
64
 
def prevent_zombie(method):
 
48
    """Return system CPU times as a named tuple"""
 
49
    user, nice, system, idle, irq = _psutil_bsd.get_system_cpu_times()
 
50
    return _cputimes_ntuple(user, nice, system, idle, irq)
 
51
 
 
52
def get_pid_list():
 
53
    """Returns a list of PIDs currently running on the system."""
 
54
    return _psutil_bsd.get_pid_list()
 
55
 
 
56
def pid_exists(pid):
 
57
    """Check For the existence of a unix pid."""
 
58
    return _psposix.pid_exists(pid)
 
59
 
 
60
 
 
61
def wrap_exceptions(method):
65
62
    """Call method(self, pid) into a try/except clause so that if an
66
63
    OSError "No such process" exception is raised we assume the process
67
64
    has died and raise psutil.NoSuchProcess instead.
68
65
    """
69
 
    def wrapper(self, pid, *args, **kwargs):
 
66
    def wrapper(self, *args, **kwargs):
70
67
        try:
71
 
            return method(self, pid, *args, **kwargs)
 
68
            return method(self, *args, **kwargs)
72
69
        except OSError, err:
73
70
            if err.errno == errno.ESRCH:
74
 
                raise NoSuchProcess(pid)
 
71
                raise NoSuchProcess(self.pid, self._process_name)
 
72
            if err.errno in (errno.EPERM, errno.EACCES):
 
73
                raise AccessDenied(self.pid, self._process_name)
75
74
            raise
76
75
    return wrapper
77
76
 
78
 
 
79
 
class Impl(object):
80
 
 
81
 
    @wrap_privileges
82
 
    def get_process_info(self, pid):
83
 
        """Returns a tuple that can be passed to the psutil.ProcessInfo class
84
 
        constructor.
85
 
        """
86
 
        infoTuple = _psutil_bsd.get_process_info(pid)
87
 
        return infoTuple
88
 
 
89
 
    @wrap_privileges
90
 
    def kill_process(self, pid, sig=signal.SIGKILL):
91
 
        """Terminates the process with the given PID."""
92
 
        if sig is None:
93
 
            sig = signal.SIGKILL
94
 
        try:
95
 
            os.kill(pid, sig)
96
 
        except OSError, err:
97
 
            if err.errno == errno.ESRCH:
98
 
                raise NoSuchProcess(pid)
99
 
            raise
100
 
 
101
 
    @wrap_privileges
102
 
    def get_cpu_times(self, pid):
 
77
_status_map = {
 
78
    _psutil_bsd.SSTOP : STATUS_STOPPED,
 
79
    _psutil_bsd.SSLEEP : STATUS_SLEEPING,
 
80
    _psutil_bsd.SRUN : STATUS_RUNNING,
 
81
    _psutil_bsd.SIDL : STATUS_IDLE,
 
82
    _psutil_bsd.SWAIT : STATUS_WAITING,
 
83
    _psutil_bsd.SLOCK : STATUS_LOCKED,
 
84
    _psutil_bsd.SZOMB : STATUS_ZOMBIE,
 
85
}
 
86
 
 
87
 
 
88
class BSDProcess(object):
 
89
    """Wrapper class around underlying C implementation."""
 
90
 
 
91
    __slots__ = ["pid", "_process_name"]
 
92
 
 
93
    def __init__(self, pid):
 
94
        self.pid = pid
 
95
        self._process_name = None
 
96
 
 
97
    @wrap_exceptions
 
98
    def get_process_name(self):
 
99
        """Return process name as a string of limited len (15)."""
 
100
        return _psutil_bsd.get_process_name(self.pid)
 
101
 
 
102
    @wrap_exceptions
 
103
    def get_process_exe(self):
 
104
        """Return process executable pathname."""
 
105
        return _psutil_bsd.get_process_exe(self.pid)
 
106
 
 
107
    @wrap_exceptions
 
108
    def get_process_cmdline(self):
 
109
        """Return process cmdline as a list of arguments."""
 
110
        return _psutil_bsd.get_process_cmdline(self.pid)
 
111
 
 
112
    @wrap_exceptions
 
113
    def get_process_ppid(self):
 
114
        """Return process parent pid."""
 
115
        return _psutil_bsd.get_process_ppid(self.pid)
 
116
 
 
117
    @wrap_exceptions
 
118
    def get_process_uids(self):
 
119
        """Return real, effective and saved user ids."""
 
120
        real, effective, saved = _psutil_bsd.get_process_uids(self.pid)
 
121
        return ntuple_uids(real, effective, saved)
 
122
 
 
123
    @wrap_exceptions
 
124
    def get_process_gids(self):
 
125
        """Return real, effective and saved group ids."""
 
126
        real, effective, saved = _psutil_bsd.get_process_gids(self.pid)
 
127
        return ntuple_gids(real, effective, saved)
 
128
 
 
129
    @wrap_exceptions
 
130
    def get_cpu_times(self):
103
131
        """return a tuple containing process user/kernel time."""
104
 
        return _psutil_bsd.get_cpu_times(pid)
 
132
        user, system = _psutil_bsd.get_cpu_times(self.pid)
 
133
        return ntuple_cputimes(user, system)
105
134
 
106
 
    @prevent_zombie
107
 
    def get_memory_info(self, pid):
 
135
    @wrap_exceptions
 
136
    def get_memory_info(self):
108
137
        """Return a tuple with the process' RSS and VMS size."""
109
 
        return _psutil_bsd.get_memory_info(pid)
110
 
 
111
 
    @prevent_zombie
112
 
    def get_process_create_time(self, pid):
113
 
        return _psutil_bsd.get_process_create_time(pid)
114
 
 
115
 
    def get_pid_list(self):
116
 
        """Returns a list of PIDs currently running on the system."""
117
 
        return _psutil_bsd.get_pid_list()
118
 
 
119
 
    def pid_exists(self, pid):
120
 
        """Check For the existence of a unix pid."""
121
 
        if pid < 0:
122
 
            return False
123
 
 
 
138
        rss, vms = _psutil_bsd.get_memory_info(self.pid)
 
139
        return ntuple_meminfo(rss, vms)
 
140
 
 
141
    @wrap_exceptions
 
142
    def get_process_create_time(self):
 
143
        """Return the start time of the process as a number of seconds since
 
144
        the epoch."""
 
145
        return _psutil_bsd.get_process_create_time(self.pid)
 
146
 
 
147
    @wrap_exceptions
 
148
    def get_process_num_threads(self):
 
149
        """Return the number of threads belonging to the process."""
 
150
        return _psutil_bsd.get_process_num_threads(self.pid)
 
151
 
 
152
    @wrap_exceptions
 
153
    def get_process_threads(self):
 
154
        """Return the number of threads belonging to the process."""
 
155
        rawlist = _psutil_bsd.get_process_threads(self.pid)
 
156
        retlist = []
 
157
        for thread_id, utime, stime in rawlist:
 
158
            ntuple = ntuple_thread(thread_id, utime, stime)
 
159
            retlist.append(ntuple)
 
160
        return retlist
 
161
 
 
162
 
 
163
    def get_open_files(self):
 
164
        """Return files opened by process by parsing lsof output."""
 
165
        lsof = _psposix.LsofParser(self.pid, self._process_name)
 
166
        return lsof.get_process_open_files()
 
167
 
 
168
    def get_connections(self):
 
169
        """Return network connections opened by a process as a list of
 
170
        namedtuples by parsing lsof output.
 
171
        """
 
172
        lsof = _psposix.LsofParser(self.pid, self._process_name)
 
173
        return lsof.get_process_connections()
 
174
 
 
175
    @wrap_exceptions
 
176
    def process_wait(self, timeout=None):
124
177
        try:
125
 
            os.kill(pid, 0)
126
 
        except OSError, e:
127
 
            return e.errno == errno.EPERM
128
 
        else:
129
 
            return True
130
 
 
 
178
            return _psposix.wait_pid(self.pid, timeout)
 
179
        except TimeoutExpired:
 
180
            raise TimeoutExpired(self.pid, self._process_name)
 
181
 
 
182
    @wrap_exceptions
 
183
    def get_process_nice(self):
 
184
        return _psutil_posix.getpriority(self.pid)
 
185
 
 
186
    @wrap_exceptions
 
187
    def set_process_nice(self, value):
 
188
        return _psutil_posix.setpriority(self.pid, value)
 
189
 
 
190
    @wrap_exceptions
 
191
    def get_process_status(self):
 
192
        code = _psutil_bsd.get_process_status(self.pid)
 
193
        if code in _status_map:
 
194
            return _status_map[code]
 
195
        return constant(-1, "?")
 
196
 
 
197
    @wrap_exceptions
 
198
    def get_process_io_counters(self):
 
199
        rc, wc, rb, wb = _psutil_bsd.get_process_io_counters(self.pid)
 
200
        return ntuple_io(rc, wc, rb, wb)
 
201
 
 
202
 
 
203
PlatformProcess = BSDProcess
131
204