~ubuntu-branches/ubuntu/trusty/python-psutil/trusty-proposed

« back to all changes in this revision

Viewing changes to psutil/_psmswindows.py

  • Committer: Package Import Robot
  • Author(s): Julian Taylor
  • Date: 2012-07-02 23:51:39 UTC
  • mfrom: (2.1.11 sid)
  • Revision ID: package-import@ubuntu.com-20120702235139-fdlsb5x3t0b2jr06
Tags: 0.5.1-1ubuntu1
* Merge from Debian unstable.  Remaining changes:
  - Switch to dh_python2. (LP: #788514)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/env python
2
2
#
3
 
# $Id: _psmswindows.py 1157 2011-10-14 18:36:03Z g.rodola $
 
3
# $Id: _psmswindows.py 1397 2012-06-29 16:33:08Z g.rodola $
4
4
#
5
5
# Copyright (c) 2009, Jay Loden, Giampaolo Rodola'. All rights reserved.
6
6
# Use of this source code is governed by a BSD-style license that can be
15
15
 
16
16
import _psutil_mswindows
17
17
from psutil.error import AccessDenied, NoSuchProcess, TimeoutExpired
18
 
from psutil._compat import namedtuple
19
18
from psutil._common import *
 
19
from psutil._compat import PY3, xrange, long
20
20
 
21
21
# Windows specific extended namespace
22
22
__extra__all__ = ["ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
28
28
 
29
29
NUM_CPUS = _psutil_mswindows.get_num_cpus()
30
30
BOOT_TIME = _psutil_mswindows.get_system_uptime()
31
 
_WIN2000 = platform.win32_ver()[0] == '2000'
32
31
ERROR_ACCESS_DENIED = 5
33
32
WAIT_TIMEOUT = 0x00000102 # 258 in decimal
34
33
 
42
41
                               REALTIME_PRIORITY_CLASS,
43
42
                               INFINITE)
44
43
 
 
44
@memoize
 
45
def _win32_QueryDosDevice(s):
 
46
    return _psutil_mswindows.win32_QueryDosDevice(s)
 
47
 
 
48
def _convert_raw_path(s):
 
49
    # convert paths using native DOS format like:
 
50
    # "\Device\HarddiskVolume1\Windows\systemew\file.txt"
 
51
    # into: "C:\Windows\systemew\file.txt"
 
52
    if PY3 and not isinstance(s, str):
 
53
        s = s.decode('utf8')
 
54
    rawdrive = '\\'.join(s.split('\\')[:3])
 
55
    driveletter = _win32_QueryDosDevice(rawdrive)
 
56
    return os.path.join(driveletter, s[len(rawdrive):])
 
57
 
 
58
 
45
59
# --- public functions
46
60
 
47
61
def phymem_usage():
49
63
    all = _psutil_mswindows.get_system_phymem()
50
64
    total, free, total_pagef, avail_pagef, total_virt, free_virt, percent = all
51
65
    used = total - free
52
 
    return ntuple_sysmeminfo(total, used, free, round(percent, 1))
 
66
    return nt_sysmeminfo(total, used, free, round(percent, 1))
53
67
 
54
68
def virtmem_usage():
55
69
    """Virtual system memory as a (total, used, free) tuple."""
58
72
    free_virt = all[5]
59
73
    used = total_virt - free_virt
60
74
    percent = usage_percent(used, total_virt, _round=1)
61
 
    return ntuple_sysmeminfo(total_virt, used, free_virt, percent)
 
75
    return nt_sysmeminfo(total_virt, used, free_virt, percent)
62
76
 
63
77
def get_disk_usage(path):
64
78
    """Return disk usage associated with path."""
65
79
    try:
66
80
        total, free = _psutil_mswindows.get_disk_usage(path)
67
 
    except WindowsError, err:
 
81
    except WindowsError:
 
82
        err = sys.exc_info()[1]
68
83
        if not os.path.exists(path):
69
84
            raise OSError(errno.ENOENT, "No such file or directory: '%s'" % path)
70
85
        raise
71
86
    used = total - free
72
87
    percent = usage_percent(used, total, _round=1)
73
 
    return ntuple_diskinfo(total, used, free, percent)
 
88
    return nt_diskinfo(total, used, free, percent)
74
89
 
75
90
def disk_partitions(all):
76
91
    """Return disk partitions."""
77
 
    retlist = []
78
 
    drive_letters = _psutil_mswindows.win32_GetLogicalDriveStrings()
79
 
    for letter in drive_letters:
80
 
        mountpoint = letter
81
 
        type = _psutil_mswindows.win32_GetDriveType(letter)
82
 
        if not os.path.exists(mountpoint):
83
 
            # usually a CD-ROM device with no disk inserted
84
 
            mountpoint = ""
85
 
        if not all:
86
 
            if type not in ('cdrom', 'fixed', 'removable'):
87
 
                continue
88
 
            if not mountpoint:
89
 
                continue
90
 
        ntuple = ntuple_partition(letter, mountpoint, type)
91
 
        retlist.append(ntuple)
92
 
    return retlist
 
92
    rawlist = _psutil_mswindows.get_disk_partitions(all)
 
93
    return [nt_partition(*x) for x in rawlist]
93
94
 
94
95
 
95
96
_cputimes_ntuple = namedtuple('cputimes', 'user system idle')
113
114
        ret.append(item)
114
115
    return ret
115
116
 
 
117
def get_system_users():
 
118
    """Return currently connected users as a list of namedtuples."""
 
119
    retlist = []
 
120
    rawlist = _psutil_mswindows.get_system_users()
 
121
    for item in rawlist:
 
122
        user, hostname, tstamp = item
 
123
        nt = nt_user(user, None, hostname, tstamp)
 
124
        retlist.append(nt)
 
125
    return retlist
 
126
 
116
127
get_pid_list = _psutil_mswindows.get_pid_list
117
128
pid_exists = _psutil_mswindows.pid_exists
118
129
network_io_counters = _psutil_mswindows.get_network_io_counters
128
139
    def wrapper(self, *args, **kwargs):
129
140
        try:
130
141
            return callable(self, *args, **kwargs)
131
 
        except OSError, err:
 
142
        except OSError:
 
143
            err = sys.exc_info()[1]
132
144
            if err.errno in (errno.EPERM, errno.EACCES, ERROR_ACCESS_DENIED):
133
145
                raise AccessDenied(self.pid, self._process_name)
134
146
            if err.errno == errno.ESRCH:
152
164
        """Return process name as a string of limited len (15)."""
153
165
        return _psutil_mswindows.get_process_name(self.pid)
154
166
 
 
167
    @wrap_exceptions
155
168
    def get_process_exe(self):
156
 
        # no such thing as "exe" on Windows; it will maybe be determined
157
 
        # later from cmdline[0]
158
 
        if not pid_exists(self.pid):
159
 
            raise NoSuchProcess(self.pid, self._process_name)
160
 
        if self.pid in (0, 4):
161
 
            raise AccessDenied(self.pid, self._process_name)
162
 
        return ""
 
169
        exe = _convert_raw_path(_psutil_mswindows.get_process_exe(self.pid))
 
170
        # Note: if the folder containing the executable is changed
 
171
        # GetProcessImageFileName() returns the previous name, hence
 
172
        # this check. An empty string signals to try to guess the exe
 
173
        # from cmdline later.
 
174
        if not os.path.exists(exe):
 
175
            exe = ""
 
176
        return exe
163
177
 
164
178
    @wrap_exceptions
165
179
    def get_process_cmdline(self):
176
190
        """Returns a tuple or RSS/VMS memory usage in bytes."""
177
191
        # special case for 0 (kernel processes) PID
178
192
        if self.pid == 0:
179
 
            return ntuple_meminfo(0, 0)
 
193
            return nt_meminfo(0, 0)
180
194
        rss, vms = _psutil_mswindows.get_memory_info(self.pid)
181
 
        return ntuple_meminfo(rss, vms)
 
195
        return nt_meminfo(rss, vms)
 
196
 
 
197
    nt_mmap_grouped = namedtuple('mmap', 'path rss')
 
198
    nt_mmap_ext = namedtuple('mmap', 'addr perms path rss')
 
199
 
 
200
    def get_memory_maps(self):
 
201
        try:
 
202
            raw = _psutil_mswindows.get_process_memory_maps(self.pid)
 
203
        except OSError:
 
204
            # XXX - can't use wrap_exceptions decorator as we're
 
205
            # returning a generator; probably needs refactoring.
 
206
            err = sys.exc_info()[1]
 
207
            if err.errno in (errno.EPERM, errno.EACCES, ERROR_ACCESS_DENIED):
 
208
                raise AccessDenied(self.pid, self._process_name)
 
209
            if err.errno == errno.ESRCH:
 
210
                raise NoSuchProcess(self.pid, self._process_name)
 
211
            raise
 
212
        else:
 
213
            for addr, perm, path, rss in raw:
 
214
                path = _convert_raw_path(path)
 
215
                addr = hex(addr)
 
216
                yield (addr, perm, path, rss)
182
217
 
183
218
    @wrap_exceptions
184
219
    def kill_process(self):
200
235
    @wrap_exceptions
201
236
    def get_process_username(self):
202
237
        """Return the name of the user that owns the process"""
203
 
        if self.pid in (0, 4) or self.pid == 8 and _WIN2000:
 
238
        if self.pid in (0, 4):
204
239
            return 'NT AUTHORITY\\SYSTEM'
205
 
        return _psutil_mswindows.get_process_username(self.pid);
 
240
        return _psutil_mswindows.get_process_username(self.pid)
206
241
 
207
242
    @wrap_exceptions
208
243
    def get_process_create_time(self):
209
244
        # special case for kernel process PIDs; return system boot time
210
 
        if self.pid in (0, 4) or self.pid == 8 and _WIN2000:
 
245
        if self.pid in (0, 4):
211
246
            return BOOT_TIME
212
247
        return _psutil_mswindows.get_process_create_time(self.pid)
213
248
 
220
255
        rawlist = _psutil_mswindows.get_process_threads(self.pid)
221
256
        retlist = []
222
257
        for thread_id, utime, stime in rawlist:
223
 
            ntuple = ntuple_thread(thread_id, utime, stime)
 
258
            ntuple = nt_thread(thread_id, utime, stime)
224
259
            retlist.append(ntuple)
225
260
        return retlist
226
261
 
227
262
    @wrap_exceptions
228
263
    def get_cpu_times(self):
229
264
        user, system = _psutil_mswindows.get_process_cpu_times(self.pid)
230
 
        return ntuple_cputimes(user, system)
 
265
        return nt_cputimes(user, system)
231
266
 
232
267
    @wrap_exceptions
233
268
    def suspend_process(self):
239
274
 
240
275
    @wrap_exceptions
241
276
    def get_process_cwd(self):
242
 
        if self.pid in (0, 4) or self.pid == 8 and _WIN2000:
 
277
        if self.pid in (0, 4):
243
278
            raise AccessDenied(self.pid, self._process_name)
244
279
        # return a normalized pathname since the native C function appends
245
280
        # "\\" at the and of the path
248
283
 
249
284
    @wrap_exceptions
250
285
    def get_open_files(self):
251
 
        if self.pid in (0, 4) or self.pid == 8 and _WIN2000:
 
286
        if self.pid in (0, 4):
252
287
            return []
253
288
        retlist = []
254
289
        # Filenames come in in native format like:
257
292
        # (e.g. "C:\") by using Windows's QueryDosDevice()
258
293
        raw_file_names = _psutil_mswindows.get_process_open_files(self.pid)
259
294
        for file in raw_file_names:
260
 
            if sys.version_info >= (3,):
261
 
                file = file.decode('utf8')
262
 
            if file.startswith('\\Device\\'):
263
 
                rawdrive = '\\'.join(file.split('\\')[:3])
264
 
                driveletter = _psutil_mswindows.win32_QueryDosDevice(rawdrive)
265
 
                file = file.replace(rawdrive, driveletter)
266
 
                if os.path.isfile(file) and file not in retlist:
267
 
                    ntuple = ntuple_openfile(file, -1)
268
 
                    retlist.append(ntuple)
 
295
            file = _convert_raw_path(file)
 
296
            if os.path.isfile(file) and file not in retlist:
 
297
                ntuple = nt_openfile(file, -1)
 
298
                retlist.append(ntuple)
269
299
        return retlist
270
300
 
271
301
    @wrap_exceptions
275
305
                             % (kind, ', '.join([repr(x) for x in conn_tmap])))
276
306
        families, types = conn_tmap[kind]
277
307
        ret = _psutil_mswindows.get_process_connections(self.pid, families, types)
278
 
        return [ntuple_connection(*conn) for conn in ret]
 
308
        return [nt_connection(*conn) for conn in ret]
279
309
 
280
310
    @wrap_exceptions
281
311
    def get_process_nice(self):
288
318
    @wrap_exceptions
289
319
    def get_process_io_counters(self):
290
320
        rc, wc, rb, wb =_psutil_mswindows.get_process_io_counters(self.pid)
291
 
        return ntuple_io(rc, wc, rb, wb)
 
321
        return nt_io(rc, wc, rb, wb)
292
322
 
293
323
    @wrap_exceptions
294
324
    def get_process_status(self):
297
327
            return STATUS_STOPPED
298
328
        else:
299
329
            return STATUS_RUNNING
 
330
 
 
331
    @wrap_exceptions
 
332
    def get_process_cpu_affinity(self):
 
333
        from_bitmask = lambda x: [i for i in xrange(64) if (1 << i) & x]
 
334
        bitmask = _psutil_mswindows.get_process_cpu_affinity(self.pid)
 
335
        return from_bitmask(bitmask)
 
336
 
 
337
    @wrap_exceptions
 
338
    def set_process_cpu_affinity(self, value):
 
339
        def to_bitmask(l):
 
340
            if not l:
 
341
                raise ValueError("invalid argument %r" % l)
 
342
            out = 0
 
343
            for b in l:
 
344
                if not isinstance(b, (int, long)) or b < 0:
 
345
                    raise ValueError("invalid argument %r" % b)
 
346
                out |= 2**b
 
347
            return out
 
348
 
 
349
        # SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
 
350
        # is returned for an invalid CPU but this seems not to be true,
 
351
        # therefore we check CPUs validy beforehand.
 
352
        allcpus = list(range(len(get_system_per_cpu_times())))
 
353
        for cpu in value:
 
354
            if cpu not in allcpus:
 
355
                raise ValueError("invalid CPU %i" % cpu)
 
356
 
 
357
        bitmask = to_bitmask(value)
 
358
        _psutil_mswindows.set_process_cpu_affinity(self.pid, bitmask)
 
359
 
 
360
    @wrap_exceptions
 
361
    def get_num_handles(self):
 
362
        return _psutil_mswindows.get_process_num_handles(self.pid)