mirror of
https://gitlab.winehq.org/wine/wine-gecko.git
synced 2024-09-13 09:24:08 -07:00
Backed out changesets 1ad8a6674785 and ed0b6a11532d (bug 908296) for OSX mach bustage.
This commit is contained in:
parent
555d6e8e35
commit
4fcf10824d
@ -5,7 +5,7 @@
|
||||
# This file contains code for populating the virtualenv environment for
|
||||
# Mozilla's build system. It is typically called as part of configure.
|
||||
|
||||
from __future__ import print_function, unicode_literals
|
||||
from __future__ import print_function, unicode_literals, with_statement
|
||||
|
||||
import distutils.sysconfig
|
||||
import os
|
||||
|
@ -1,3 +1,4 @@
|
||||
|
||||
Intro
|
||||
=====
|
||||
|
||||
@ -10,23 +11,24 @@ name (N), e-mail (E), web-address (W), country (C), description (D), (I) issues
|
||||
(issue tracker is at http://code.google.com/p/psutil/issues/list).
|
||||
Really thanks to all of you.
|
||||
|
||||
Author
|
||||
======
|
||||
|
||||
Maintainers
|
||||
===========
|
||||
|
||||
N: Giampaolo Rodola'
|
||||
C: Italy
|
||||
E: g.rodola@gmail.com
|
||||
W: http://www.linkedin.com/in/grodola
|
||||
|
||||
Contributors
|
||||
============
|
||||
|
||||
N: Jay Loden
|
||||
C: NJ, USA
|
||||
E: jloden@gmail.com
|
||||
D: original co-author, initial design/bootstrap and continuing bug fixes
|
||||
W: http://www.jayloden.com
|
||||
|
||||
|
||||
Contributors
|
||||
============
|
||||
|
||||
N: Jeremy Whitlock
|
||||
E: jcscoobyrs@gmail.com
|
||||
I: 125, 150, 174, 206
|
||||
@ -41,11 +43,6 @@ C: Bologna, Italy
|
||||
E: yanraber@gmail.com
|
||||
D: help on Windows development
|
||||
|
||||
N: Justin Venus
|
||||
E: justin.venus@gmail.com
|
||||
D: Solaris support
|
||||
I: 18
|
||||
|
||||
N: Dave Daeschler
|
||||
C: USA
|
||||
E: david.daeschler@gmail.com
|
||||
@ -165,18 +162,3 @@ I: 370
|
||||
N: Jan Beich
|
||||
E: jbeich@tormail.org
|
||||
I: 325
|
||||
|
||||
N: floppymaster
|
||||
E: floppymaster@gmail.com
|
||||
I: 380
|
||||
|
||||
N: Arfrever.FTA
|
||||
E: Arfrever.FTA@gmail.com
|
||||
I: 369, 404
|
||||
|
||||
N: danudey
|
||||
E: danudey@gmail.com
|
||||
I: 386
|
||||
|
||||
N: Adrien Fallou
|
||||
I: 224
|
||||
|
@ -1,42 +1,5 @@
|
||||
Bug tracker at http://code.google.com/p/psutil/issues
|
||||
|
||||
|
||||
1.0.1 - 2013-07-12
|
||||
------------------
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* #405: network_io_counters(pernic=True) no longer works as intended in 1.0.0.
|
||||
|
||||
|
||||
1.0.0 - 2013-07-10
|
||||
------------------
|
||||
|
||||
NEW FEATURES
|
||||
|
||||
* #18: Solaris support (yay!) (thanks Justin Venus)
|
||||
* #367: Process.get_connections() 'status' strings are now constants.
|
||||
* #380: test suite exits with non-zero on failure. (patch by floppymaster)
|
||||
* #391: extensively use unittest2 module in unit tests and provide
|
||||
workarounds if this is not installed on python < 2.7.
|
||||
|
||||
BUG FIXES
|
||||
|
||||
* #374: [Windows] negative memory usage reported when processes use a lot of
|
||||
memory.
|
||||
* #379: [Linux] Process.get_memory_maps() may raise ValueError.
|
||||
* #394: [OSX] Mapped memory regions report incorrect file name.
|
||||
* #404: [Linux] sched_*affinity() are implicitly declared. (patch by Arfrever)
|
||||
|
||||
API CHANGES
|
||||
|
||||
* Process.get_connections() 'status' field is no longer a string but a constant
|
||||
object (psutil.CONN_*).
|
||||
* Process.get_connections() 'local_address' and 'remote_address' fields renamed
|
||||
to 'laddr' and 'raddr'.
|
||||
* psutil.network_io_counters() renamed to psutil.net_io_counters().
|
||||
|
||||
|
||||
0.7.1 - 2013-05-03
|
||||
------------------
|
||||
|
||||
|
@ -3,7 +3,6 @@ include HISTORY
|
||||
include LICENSE
|
||||
include MANIFEST.in
|
||||
include README
|
||||
include TODO
|
||||
include setup.py
|
||||
recursive-include psutil *.py *.c *.h
|
||||
recursive-include test *.py
|
||||
|
@ -1,12 +1,12 @@
|
||||
Metadata-Version: 1.1
|
||||
Name: psutil
|
||||
Version: 1.0.1
|
||||
Version: 0.7.1
|
||||
Summary: A process and system utilities module for Python
|
||||
Home-page: http://code.google.com/p/psutil/
|
||||
Author: Giampaolo Rodola
|
||||
Author-email: g.rodola <at> gmail <dot> com
|
||||
License: License :: OSI Approved :: BSD License
|
||||
Download-URL: http://psutil.googlecode.com/files/psutil-1.0.1.tar.gz
|
||||
Download-URL: http://psutil.googlecode.com/files/psutil-0.7.1.tar.gz
|
||||
Description: ===========
|
||||
Quick links
|
||||
===========
|
||||
@ -25,9 +25,9 @@ Description: ===========
|
||||
command line tools such as: **ps, top, df, kill, free, lsof, free, netstat,
|
||||
ifconfig, nice, ionice, iostat, iotop, uptime, pidof, tty, who, taskset, pmap**.
|
||||
|
||||
It currently supports **Linux**, **Windows**, **OSX**, **FreeBSD**,
|
||||
**Sun Solaris** both **32-bit** and **64-bit** with Python versions from **2.4**
|
||||
to **3.3** by using a single code base.
|
||||
It currently supports **Linux**, **Windows**, **OSX** and **FreeBSD** both
|
||||
**32-bit** and **64-bit** with Python versions from **2.4** to **3.3** by using
|
||||
a single code base.
|
||||
|
||||
==============
|
||||
Example usages
|
||||
@ -39,7 +39,7 @@ Description: ===========
|
||||
>>> import psutil
|
||||
>>> psutil.cpu_times()
|
||||
cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
|
||||
iowait=629.509, irq=0.0, softirq=19.422, steal=0.0, guest=0, nice=0.0)
|
||||
iowait=629.509, irq=0.0, softirq=19.422)
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_percent(interval=1)
|
||||
@ -55,15 +55,7 @@ Description: ===========
|
||||
[7.0, 8.5]
|
||||
[1.2, 9.0]
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_times_percent(interval=1, percpu=False)
|
||||
...
|
||||
cpupercent(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0,
|
||||
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
|
||||
cpupercent(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0,
|
||||
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
|
||||
cpupercent(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0,
|
||||
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
|
||||
|
||||
|
||||
Memory
|
||||
======
|
||||
@ -97,22 +89,21 @@ Description: ===========
|
||||
Network
|
||||
=======
|
||||
|
||||
>>> psutil.net_io_counters(pernic=True)
|
||||
>>> psutil.network_io_counters(pernic=True)
|
||||
{'lo': iostat(bytes_sent=799953745, bytes_recv=799953745,
|
||||
packets_sent=453698, packets_recv=453698),
|
||||
'eth0': iostat(bytes_sent=734324837, bytes_recv=4163935363,
|
||||
packets_sent=3605828, packets_recv=4096685)}
|
||||
>>>
|
||||
|
||||
Other system info
|
||||
=================
|
||||
|
||||
Users
|
||||
=====
|
||||
|
||||
>>> psutil.get_users()
|
||||
[user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
|
||||
user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
|
||||
>>>
|
||||
>>> psutil.get_boot_time()
|
||||
1365519115.0
|
||||
|
||||
|
||||
Process management
|
||||
@ -181,14 +172,14 @@ Description: ===========
|
||||
[openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
|
||||
>>>
|
||||
>>> p.get_connections()
|
||||
[connection(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776),
|
||||
raddr=('93.186.135.91', 80), status='ESTABLISHED'),
|
||||
connection(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761),
|
||||
raddr=('72.14.234.100', 80), status='CLOSING'),
|
||||
connection(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759),
|
||||
raddr=('72.14.234.104', 80), status='ESTABLISHED'),
|
||||
connection(fd=123, family=2, type=1, laddr=('10.0.0.1', 51314),
|
||||
raddr=('72.14.234.83', 443), status='SYN_SENT')]
|
||||
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
|
||||
remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
|
||||
connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
|
||||
remote_address=('72.14.234.100', 80), status='CLOSING'),
|
||||
connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
|
||||
remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
|
||||
connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
|
||||
remote_address=('72.14.234.83', 443), status='SYN_SENT')]
|
||||
>>>
|
||||
>>> p.get_num_threads()
|
||||
4
|
||||
@ -235,7 +226,6 @@ Classifier: Operating System :: Microsoft :: Windows :: Windows NT/2000
|
||||
Classifier: Operating System :: POSIX
|
||||
Classifier: Operating System :: POSIX :: Linux
|
||||
Classifier: Operating System :: POSIX :: BSD :: FreeBSD
|
||||
Classifier: Operating System :: POSIX :: SunOS/Solaris
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Programming Language :: C
|
||||
Classifier: Programming Language :: Python
|
||||
|
@ -16,9 +16,9 @@ a portable way by using Python, implementing many functionalities offered by
|
||||
command line tools such as: **ps, top, df, kill, free, lsof, free, netstat,
|
||||
ifconfig, nice, ionice, iostat, iotop, uptime, pidof, tty, who, taskset, pmap**.
|
||||
|
||||
It currently supports **Linux**, **Windows**, **OSX**, **FreeBSD**,
|
||||
**Sun Solaris** both **32-bit** and **64-bit** with Python versions from **2.4**
|
||||
to **3.3** by using a single code base.
|
||||
It currently supports **Linux**, **Windows**, **OSX** and **FreeBSD** both
|
||||
**32-bit** and **64-bit** with Python versions from **2.4** to **3.3** by using
|
||||
a single code base.
|
||||
|
||||
==============
|
||||
Example usages
|
||||
@ -30,7 +30,7 @@ CPU
|
||||
>>> import psutil
|
||||
>>> psutil.cpu_times()
|
||||
cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
|
||||
iowait=629.509, irq=0.0, softirq=19.422, steal=0.0, guest=0, nice=0.0)
|
||||
iowait=629.509, irq=0.0, softirq=19.422)
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_percent(interval=1)
|
||||
@ -46,15 +46,7 @@ cputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540,
|
||||
[7.0, 8.5]
|
||||
[1.2, 9.0]
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_times_percent(interval=1, percpu=False)
|
||||
...
|
||||
cpupercent(user=1.5, nice=0.0, system=0.5, idle=96.5, iowait=1.5, irq=0.0,
|
||||
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
|
||||
cpupercent(user=1.0, nice=0.0, system=0.0, idle=99.0, iowait=0.0, irq=0.0,
|
||||
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
|
||||
cpupercent(user=2.0, nice=0.0, system=0.0, idle=98.0, iowait=0.0, irq=0.0,
|
||||
softirq=0.0, steal=0.0, guest=0.0, guest_nice=0.0)
|
||||
|
||||
|
||||
Memory
|
||||
======
|
||||
@ -88,22 +80,21 @@ iostat(read_count=719566, write_count=1082197, read_bytes=18626220032,
|
||||
Network
|
||||
=======
|
||||
|
||||
>>> psutil.net_io_counters(pernic=True)
|
||||
>>> psutil.network_io_counters(pernic=True)
|
||||
{'lo': iostat(bytes_sent=799953745, bytes_recv=799953745,
|
||||
packets_sent=453698, packets_recv=453698),
|
||||
'eth0': iostat(bytes_sent=734324837, bytes_recv=4163935363,
|
||||
packets_sent=3605828, packets_recv=4096685)}
|
||||
>>>
|
||||
|
||||
Other system info
|
||||
=================
|
||||
|
||||
Users
|
||||
=====
|
||||
|
||||
>>> psutil.get_users()
|
||||
[user(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0),
|
||||
user(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0)]
|
||||
>>>
|
||||
>>> psutil.get_boot_time()
|
||||
1365519115.0
|
||||
|
||||
|
||||
Process management
|
||||
@ -172,14 +163,14 @@ io(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632)
|
||||
[openfile(path='/home/giampaolo/svn/psutil/somefile', fd=3)]
|
||||
>>>
|
||||
>>> p.get_connections()
|
||||
[connection(fd=115, family=2, type=1, laddr=('10.0.0.1', 48776),
|
||||
raddr=('93.186.135.91', 80), status='ESTABLISHED'),
|
||||
connection(fd=117, family=2, type=1, laddr=('10.0.0.1', 43761),
|
||||
raddr=('72.14.234.100', 80), status='CLOSING'),
|
||||
connection(fd=119, family=2, type=1, laddr=('10.0.0.1', 60759),
|
||||
raddr=('72.14.234.104', 80), status='ESTABLISHED'),
|
||||
connection(fd=123, family=2, type=1, laddr=('10.0.0.1', 51314),
|
||||
raddr=('72.14.234.83', 443), status='SYN_SENT')]
|
||||
[connection(fd=115, family=2, type=1, local_address=('10.0.0.1', 48776),
|
||||
remote_address=('93.186.135.91', 80), status='ESTABLISHED'),
|
||||
connection(fd=117, family=2, type=1, local_address=('10.0.0.1', 43761),
|
||||
remote_address=('72.14.234.100', 80), status='CLOSING'),
|
||||
connection(fd=119, family=2, type=1, local_address=('10.0.0.1', 60759),
|
||||
remote_address=('72.14.234.104', 80), status='ESTABLISHED'),
|
||||
connection(fd=123, family=2, type=1, local_address=('10.0.0.1', 51314),
|
||||
remote_address=('72.14.234.83', 443), status='SYN_SENT')]
|
||||
>>>
|
||||
>>> p.get_num_threads()
|
||||
4
|
||||
|
@ -1,95 +0,0 @@
|
||||
TODO
|
||||
====
|
||||
|
||||
A collection of ideas and notes about stuff to implement in future versions.
|
||||
"#NNN" occurrences refer to bug tracker issues at:
|
||||
https://code.google.com/p/psutil/issues/list
|
||||
|
||||
|
||||
HIGHER PRIORITY
|
||||
===============
|
||||
|
||||
* #387: system-wide connections (netstat).
|
||||
* OpenBSD support.
|
||||
|
||||
* #371: CPU temperature (apparently OSX and Linux only; on Linux it requires
|
||||
lm-sensors lib).
|
||||
|
||||
* #250: net ifaces speed.
|
||||
|
||||
* (Linux) resource limit get/set - see man prlimit.
|
||||
|
||||
* Process.name on Windows is slow:
|
||||
http://stackoverflow.com/questions/6587036/
|
||||
|
||||
* Windows binary for Python 3.3 64-bit.
|
||||
|
||||
* #269: expose network ifaces RX/TW queues.
|
||||
|
||||
|
||||
LOWER PRIORITY
|
||||
==============
|
||||
|
||||
* #355: Android support.
|
||||
|
||||
* #276: GNU/Hurd support.
|
||||
|
||||
* NetBSD support?
|
||||
|
||||
* DranflyBSD support?
|
||||
|
||||
* AIX support?
|
||||
|
||||
* examples/pidof.py (same as 'pidof' cli tool)
|
||||
|
||||
* examples/pstree.py (same as 'pstree' cli tool)
|
||||
* get_threads() should also return thread names in order to implement it
|
||||
|
||||
* examples/taskmgr-gui.py (using tk).
|
||||
|
||||
* system-wide # open file descriptors:
|
||||
* https://jira.hyperic.com/browse/SIGAR-30
|
||||
* http://www.netadmintools.com/part295.html
|
||||
|
||||
* Number of system threads.
|
||||
* Windows: http://msdn.microsoft.com/en-us/library/windows/desktop/ms684824(v=vs.85).aspx
|
||||
|
||||
* #357: what CPU a process is on.
|
||||
|
||||
* thread names:
|
||||
* https://code.google.com/p/plcrashreporter/issues/detail?id=65
|
||||
|
||||
|
||||
DEBATABLE
|
||||
=========
|
||||
|
||||
* [Linux]: process cgroups (http://en.wikipedia.org/wiki/Cgroups). They look
|
||||
similar to prlimit() in terms of functionality but uglier (they should allow
|
||||
limiting per-process network IO resources though, which is great). Needs
|
||||
further reading.
|
||||
|
||||
* cpu_percent(): current default interval is 0.1 so that by default it will
|
||||
produce a meaningful value. It represents a trap in case the user iterates
|
||||
over multiple processes though, as it introduces a big slowdown.
|
||||
Should it default to 0.0?
|
||||
|
||||
* Rename connection ntuple's fields 'local_address', 'remote_address' to
|
||||
'laddr', 'raddr' (note in accordance with http://bugs.python.org/issue17675)
|
||||
|
||||
* Process per-cpus percent (XXX Windows only?), see:
|
||||
https://groups.google.com/forum/?fromgroups#!topic/psutil/ErrKTxAbu50
|
||||
|
||||
* Should we expose OS constants (psutil.WINDOWS, psutil.OSX etc.)?
|
||||
|
||||
* Python 3.3. exposed different sched.h functions:
|
||||
http://docs.python.org/dev/whatsnew/3.3.html#os
|
||||
http://bugs.python.org/issue12655
|
||||
http://docs.python.org/dev/library/os.html#interface-to-the-scheduler
|
||||
It might be worth to take a look and figure out whether we can include some
|
||||
of those in psutil.
|
||||
Also, we can probably reimplement wait_pid() on POSIX which is currently
|
||||
implemented as a busy-loop.
|
||||
|
||||
* Certain systems (XXX figure out which ones exactly) provide CPU times about
|
||||
process children. On those systems Process.get_cpu_times() might return
|
||||
a (user, system, user_children, system_children) ntuple.
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -9,7 +9,6 @@ List all mounted disk partitions a-la "df -h" command.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import psutil
|
||||
from psutil._compat import print_
|
||||
|
||||
@ -34,9 +33,6 @@ def main():
|
||||
templ = "%-17s %8s %8s %8s %5s%% %9s %s"
|
||||
print_(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
|
||||
for part in psutil.disk_partitions(all=False):
|
||||
if os.name == 'nt' and 'cdrom' in part.opts:
|
||||
# may raise ENOENT if there's no cd-rom in the drive
|
||||
continue
|
||||
usage = psutil.disk_usage(part.mountpoint)
|
||||
print_(templ % (part.device,
|
||||
bytes2human(usage.total),
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -33,14 +33,12 @@ def main():
|
||||
cons = p.get_connections(kind='inet')
|
||||
except psutil.AccessDenied:
|
||||
print_(templ % (AD, AD, AD, AD, p.pid, name))
|
||||
except psutil.NoSuchProcess:
|
||||
continue
|
||||
else:
|
||||
for c in cons:
|
||||
raddr = ""
|
||||
laddr = "%s:%s" % (c.laddr)
|
||||
if c.raddr:
|
||||
raddr = "%s:%s" % (c.raddr)
|
||||
laddr = "%s:%s" % (c.local_address)
|
||||
if c.remote_address:
|
||||
raddr = "%s:%s" % (c.remote_address)
|
||||
print_(templ % (proto_map[(c.family, c.type)],
|
||||
laddr,
|
||||
raddr,
|
||||
|
@ -2,7 +2,7 @@
|
||||
#
|
||||
# $Id: iotop.py 1160 2011-10-14 18:50:36Z g.rodola@gmail.com $
|
||||
#
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -72,12 +72,12 @@ def bytes2human(n):
|
||||
|
||||
def poll(interval):
|
||||
"""Retrieve raw stats within an interval window."""
|
||||
tot_before = psutil.net_io_counters()
|
||||
pnic_before = psutil.net_io_counters(pernic=True)
|
||||
tot_before = psutil.network_io_counters()
|
||||
pnic_before = psutil.network_io_counters(pernic=True)
|
||||
# sleep some time
|
||||
time.sleep(interval)
|
||||
tot_after = psutil.net_io_counters()
|
||||
pnic_after = psutil.net_io_counters(pernic=True)
|
||||
tot_after = psutil.network_io_counters()
|
||||
pnic_after = psutil.network_io_counters(pernic=True)
|
||||
return (tot_before, tot_after, pnic_before, pnic_after)
|
||||
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -55,7 +55,7 @@ def run(pid):
|
||||
parent = ''
|
||||
started = datetime.datetime.fromtimestamp(pinfo['create_time']
|
||||
).strftime('%Y-%M-%d %H:%M')
|
||||
io = pinfo.get('io_counters', ACCESS_DENIED)
|
||||
io = pinfo.get('io_counters', None)
|
||||
mem = '%s%% (resident=%s, virtual=%s) ' % (
|
||||
round(pinfo['memory_percent'], 1),
|
||||
convert_bytes(pinfo['memory_info'].rss),
|
||||
@ -69,18 +69,16 @@ def run(pid):
|
||||
print_('cmdline', ' '.join(pinfo['cmdline']))
|
||||
print_('started', started)
|
||||
print_('user', pinfo['username'])
|
||||
if os.name == 'posix' and pinfo['uids'] and pinfo['gids']:
|
||||
print_('uids', 'real=%s, effective=%s, saved=%s' % pinfo['uids'])
|
||||
if os.name == 'posix' and pinfo['gids']:
|
||||
print_('gids', 'real=%s, effective=%s, saved=%s' % pinfo['gids'])
|
||||
if os.name == 'posix':
|
||||
print_('uids', 'real=%s, effective=%s, saved=%s' % pinfo['uids'])
|
||||
print_('gids', 'real=%s, effective=%s, saved=%s' % pinfo['gids'])
|
||||
print_('terminal', pinfo['terminal'] or '')
|
||||
if hasattr(p, 'getcwd'):
|
||||
print_('cwd', pinfo['cwd'])
|
||||
print_('memory', mem)
|
||||
print_('cpu', '%s%% (user=%s, system=%s)' % (pinfo['cpu_percent'],
|
||||
getattr(pinfo['cpu_times'], 'user', '?'),
|
||||
getattr(pinfo['cpu_times'], 'system', '?')))
|
||||
pinfo['cpu_times'].user,
|
||||
pinfo['cpu_times'].system))
|
||||
print_('status', pinfo['status'])
|
||||
print_('niceness', pinfo['nice'])
|
||||
print_('num threads', pinfo['num_threads'])
|
||||
@ -112,11 +110,11 @@ def run(pid):
|
||||
type = 'UDP'
|
||||
else:
|
||||
type = 'UNIX'
|
||||
lip, lport = conn.laddr
|
||||
if not conn.raddr:
|
||||
lip, lport = conn.local_address
|
||||
if not conn.remote_address:
|
||||
rip, rport = '*', '*'
|
||||
else:
|
||||
rip, rport = conn.raddr
|
||||
rip, rport = conn.remote_address
|
||||
print_('', '%s:%s -> %s:%s type=%s status=%s' \
|
||||
% (lip, lport, rip, rport, type, conn.status))
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -167,12 +167,8 @@ def refresh_window(procs, procs_status):
|
||||
p.dict['memory_percent'] = ''
|
||||
if p.dict['cpu_percent'] is None:
|
||||
p.dict['cpu_percent'] = ''
|
||||
if p.dict['username']:
|
||||
username = p.dict['username'][:8]
|
||||
else:
|
||||
username = ""
|
||||
line = templ % (p.pid,
|
||||
username,
|
||||
p.dict['username'][:8],
|
||||
p.dict['nice'],
|
||||
bytes2human(getattr(p.dict['memory_info'], 'vms', 0)),
|
||||
bytes2human(getattr(p.dict['memory_info'], 'rss', 0)),
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -12,7 +12,7 @@ Python.
|
||||
|
||||
from __future__ import division
|
||||
|
||||
__version__ = "1.0.1"
|
||||
__version__ = "0.7.1"
|
||||
version_info = tuple([int(num) for num in __version__.split('.')])
|
||||
|
||||
__all__ = [
|
||||
@ -24,16 +24,13 @@ __all__ = [
|
||||
"STATUS_RUNNING", "STATUS_IDLE", "STATUS_SLEEPING", "STATUS_DISK_SLEEP",
|
||||
"STATUS_STOPPED", "STATUS_TRACING_STOP", "STATUS_ZOMBIE", "STATUS_DEAD",
|
||||
"STATUS_WAKING", "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",
|
||||
# classes
|
||||
"Process", "Popen",
|
||||
# functions
|
||||
"pid_exists", "get_pid_list", "process_iter", # proc
|
||||
"virtual_memory", "swap_memory", # memory
|
||||
"cpu_times", "cpu_percent", "cpu_times_percent", # cpu
|
||||
"net_io_counters", # network
|
||||
"network_io_counters", # network
|
||||
"disk_io_counters", "disk_partitions", "disk_usage", # disk
|
||||
"get_users", "get_boot_time", # others
|
||||
]
|
||||
@ -62,12 +59,7 @@ from psutil._common import (deprecated as _deprecated,
|
||||
from psutil._common import (STATUS_RUNNING, STATUS_IDLE, STATUS_SLEEPING,
|
||||
STATUS_DISK_SLEEP, STATUS_STOPPED,
|
||||
STATUS_TRACING_STOP, STATUS_ZOMBIE, STATUS_DEAD,
|
||||
STATUS_WAKING, 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)
|
||||
STATUS_WAKING, STATUS_LOCKED)
|
||||
|
||||
# import the appropriate module for our platform only
|
||||
if sys.platform.startswith("linux"):
|
||||
@ -88,8 +80,7 @@ elif sys.platform.startswith("win32"):
|
||||
HIGH_PRIORITY_CLASS,
|
||||
IDLE_PRIORITY_CLASS,
|
||||
NORMAL_PRIORITY_CLASS,
|
||||
REALTIME_PRIORITY_CLASS,
|
||||
CONN_DELETE_TCB)
|
||||
REALTIME_PRIORITY_CLASS)
|
||||
|
||||
elif sys.platform.startswith("darwin"):
|
||||
import psutil._psosx as _psplatform
|
||||
@ -97,11 +88,6 @@ elif sys.platform.startswith("darwin"):
|
||||
elif sys.platform.startswith("freebsd"):
|
||||
import psutil._psbsd as _psplatform
|
||||
|
||||
elif sys.platform.startswith("sunos"):
|
||||
import psutil._pssunos as _psplatform
|
||||
from psutil._pssunos import (CONN_IDLE,
|
||||
CONN_BOUND)
|
||||
|
||||
else:
|
||||
raise NotImplementedError('platform %s is not supported' % sys.platform)
|
||||
|
||||
@ -314,11 +300,9 @@ class Process(object):
|
||||
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):
|
||||
rexe = os.path.realpath(exe) # ...in case it's a symlink
|
||||
if os.path.isabs(rexe) and os.path.isfile(rexe) \
|
||||
and os.access(rexe, os.X_OK):
|
||||
return exe
|
||||
if isinstance(fallback, AccessDenied):
|
||||
raise fallback
|
||||
@ -1238,7 +1222,7 @@ def disk_io_counters(perdisk=False):
|
||||
# --- network related functions
|
||||
# =====================================================================
|
||||
|
||||
def net_io_counters(pernic=False):
|
||||
def network_io_counters(pernic=False):
|
||||
"""Return network I/O statistics as a namedtuple including
|
||||
the following attributes:
|
||||
|
||||
@ -1257,7 +1241,7 @@ def net_io_counters(pernic=False):
|
||||
with network interface names as the keys and the namedtuple
|
||||
described above as the values.
|
||||
"""
|
||||
rawdict = _psplatform.net_io_counters()
|
||||
rawdict = _psplatform.network_io_counters()
|
||||
if not rawdict:
|
||||
raise RuntimeError("couldn't find any network interface")
|
||||
if pernic:
|
||||
@ -1333,10 +1317,6 @@ def used_virtmem():
|
||||
def avail_virtmem():
|
||||
return virtmem_usage().free
|
||||
|
||||
@_deprecated("psutil.net_io_counters()")
|
||||
def network_io_counters(pernic=False):
|
||||
return net_io_counters(pernic)
|
||||
|
||||
def test():
|
||||
"""List info of all currently running processes emulating ps aux
|
||||
output.
|
||||
@ -1346,10 +1326,9 @@ def test():
|
||||
|
||||
today_day = datetime.date.today()
|
||||
templ = "%-10s %5s %4s %4s %7s %7s %-13s %5s %7s %s"
|
||||
attrs = ['pid', 'get_cpu_percent', 'get_memory_percent', 'name',
|
||||
attrs = ['pid', 'username', 'get_cpu_percent', 'get_memory_percent', 'name',
|
||||
'get_cpu_times', 'create_time', 'get_memory_info']
|
||||
if os.name == 'posix':
|
||||
attrs.append('uids')
|
||||
attrs.append('terminal')
|
||||
print_(templ % ("USER", "PID", "%CPU", "%MEM", "VSZ", "RSS", "TTY", "START",
|
||||
"TIME", "COMMAND"))
|
||||
@ -1368,18 +1347,7 @@ def test():
|
||||
else:
|
||||
ctime = ''
|
||||
cputime = time.strftime("%M:%S", time.localtime(sum(pinfo['cpu_times'])))
|
||||
try:
|
||||
user = p.username
|
||||
except KeyError:
|
||||
if os.name == 'posix':
|
||||
if pinfo['uids']:
|
||||
user = str(pinfo['uids'].real)
|
||||
else:
|
||||
user = ''
|
||||
else:
|
||||
raise
|
||||
except Error:
|
||||
user = ''
|
||||
user = pinfo['username']
|
||||
if os.name == 'nt' and '\\' in user:
|
||||
user = user.split('\\')[1]
|
||||
vms = pinfo['memory_info'] and \
|
||||
|
@ -1,6 +1,6 @@
|
||||
#/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -132,19 +132,6 @@ STATUS_IDLE = constant(9, "idle") # BSD
|
||||
STATUS_LOCKED = constant(10, "locked") # BSD
|
||||
STATUS_WAITING = constant(11, "waiting") # BSD
|
||||
|
||||
CONN_ESTABLISHED = constant(0, "ESTABLISHED")
|
||||
CONN_SYN_SENT = constant(1, "SYN_SENT")
|
||||
CONN_SYN_RECV = constant(2, "SYN_RECV")
|
||||
CONN_FIN_WAIT1 = constant(3, "FIN_WAIT1")
|
||||
CONN_FIN_WAIT2 = constant(4, "FIN_WAIT2")
|
||||
CONN_TIME_WAIT = constant(5, "TIME_WAIT")
|
||||
CONN_CLOSE = constant(6, "CLOSE")
|
||||
CONN_CLOSE_WAIT = constant(7, "CLOSE_WAIT")
|
||||
CONN_LAST_ACK = constant(8, "LAST_ACK")
|
||||
CONN_LISTEN = constant(9, "LISTEN")
|
||||
CONN_CLOSING = constant(10, "CLOSING")
|
||||
CONN_NONE = constant(20, "NONE")
|
||||
|
||||
# --- Process.get_connections() 'kind' parameter mapping
|
||||
|
||||
import socket
|
||||
@ -194,25 +181,10 @@ nt_user = namedtuple('user', 'name terminal host started')
|
||||
nt_meminfo = namedtuple('meminfo', 'rss vms')
|
||||
nt_cputimes = namedtuple('cputimes', 'user system')
|
||||
nt_openfile = namedtuple('openfile', 'path fd')
|
||||
nt_connection = namedtuple('connection', 'fd family type local_address remote_address status')
|
||||
nt_thread = namedtuple('thread', 'id user_time system_time')
|
||||
nt_uids = namedtuple('user', 'real effective saved')
|
||||
nt_gids = namedtuple('group', 'real effective saved')
|
||||
nt_io = namedtuple('io', 'read_count write_count read_bytes write_bytes')
|
||||
nt_ionice = namedtuple('ionice', 'ioclass value')
|
||||
nt_ctxsw = namedtuple('amount', 'voluntary involuntary')
|
||||
|
||||
class nt_connection(namedtuple('connection',
|
||||
'fd family type laddr raddr status')):
|
||||
__slots__ = ()
|
||||
|
||||
@property
|
||||
def local_address(self):
|
||||
warnings.warn("'local_address' field is deprecated; use 'laddr'" \
|
||||
"instead", category=DeprecationWarning, stacklevel=2)
|
||||
return self.laddr
|
||||
|
||||
@property
|
||||
def remote_address(self):
|
||||
warnings.warn("'remote_address' field is deprecated; use 'raddr'" \
|
||||
"instead", category=DeprecationWarning, stacklevel=2)
|
||||
return self.raddr
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -138,7 +138,7 @@ def get_system_users():
|
||||
get_pid_list = _psutil_bsd.get_pid_list
|
||||
pid_exists = _psposix.pid_exists
|
||||
get_disk_usage = _psposix.get_disk_usage
|
||||
net_io_counters = _psutil_bsd.get_net_io_counters
|
||||
network_io_counters = _psutil_bsd.get_network_io_counters
|
||||
disk_io_counters = _psutil_bsd.get_disk_io_counters
|
||||
|
||||
|
||||
@ -169,20 +169,6 @@ _status_map = {
|
||||
_psutil_bsd.SZOMB : STATUS_ZOMBIE,
|
||||
}
|
||||
|
||||
_conn_status_map = {_psutil_bsd.TCPS_ESTABLISHED : CONN_ESTABLISHED,
|
||||
_psutil_bsd.TCPS_SYN_SENT : CONN_SYN_SENT,
|
||||
_psutil_bsd.TCPS_SYN_RECEIVED : CONN_SYN_RECV,
|
||||
_psutil_bsd.TCPS_FIN_WAIT_1 : CONN_FIN_WAIT1,
|
||||
_psutil_bsd.TCPS_FIN_WAIT_2 : CONN_FIN_WAIT2,
|
||||
_psutil_bsd.TCPS_TIME_WAIT : CONN_TIME_WAIT,
|
||||
_psutil_bsd.TCPS_CLOSED : CONN_CLOSE,
|
||||
_psutil_bsd.TCPS_CLOSE_WAIT : CONN_CLOSE_WAIT,
|
||||
_psutil_bsd.TCPS_LAST_ACK : CONN_LAST_ACK,
|
||||
_psutil_bsd.TCPS_LISTEN : CONN_LISTEN,
|
||||
_psutil_bsd.TCPS_CLOSING : CONN_CLOSING,
|
||||
_psutil_bsd.PSUTIL_CONN_NONE : CONN_NONE,
|
||||
}
|
||||
|
||||
|
||||
class Process(object):
|
||||
"""Wrapper class around underlying C implementation."""
|
||||
@ -312,14 +298,8 @@ class Process(object):
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in conn_tmap])))
|
||||
families, types = conn_tmap[kind]
|
||||
rawlist = _psutil_bsd.get_process_connections(self.pid, families, types)
|
||||
ret = []
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status = item
|
||||
status = _conn_status_map[status]
|
||||
nt = nt_connection(fd, fam, type, laddr, raddr, status)
|
||||
ret.append(nt)
|
||||
return ret
|
||||
ret = _psutil_bsd.get_process_connections(self.pid, families, types)
|
||||
return [nt_connection(*conn) for conn in ret]
|
||||
|
||||
@wrap_exceptions
|
||||
def process_wait(self, timeout=None):
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -25,14 +25,8 @@ from psutil._common import *
|
||||
from psutil._compat import PY3, xrange, long, namedtuple, wraps
|
||||
|
||||
__extra__all__ = [
|
||||
# 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",
|
||||
# other
|
||||
"phymem_buffers", "cached_phymem"]
|
||||
|
||||
|
||||
@ -115,17 +109,17 @@ IOPRIO_CLASS_BE = 2
|
||||
IOPRIO_CLASS_IDLE = 3
|
||||
|
||||
# http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
|
||||
_TCP_STATES_TABLE = {"01" : CONN_ESTABLISHED,
|
||||
"02" : CONN_SYN_SENT,
|
||||
"03" : CONN_SYN_RECV,
|
||||
"04" : CONN_FIN_WAIT1,
|
||||
"05" : CONN_FIN_WAIT2,
|
||||
"06" : CONN_TIME_WAIT,
|
||||
"07" : CONN_CLOSE,
|
||||
"08" : CONN_CLOSE_WAIT,
|
||||
"09" : CONN_LAST_ACK,
|
||||
"0A" : CONN_LISTEN,
|
||||
"0B" : CONN_CLOSING
|
||||
_TCP_STATES_TABLE = {"01" : "ESTABLISHED",
|
||||
"02" : "SYN_SENT",
|
||||
"03" : "SYN_RECV",
|
||||
"04" : "FIN_WAIT1",
|
||||
"05" : "FIN_WAIT2",
|
||||
"06" : "TIME_WAIT",
|
||||
"07" : "CLOSE",
|
||||
"08" : "CLOSE_WAIT",
|
||||
"09" : "LAST_ACK",
|
||||
"0A" : "LISTEN",
|
||||
"0B" : "CLOSING"
|
||||
}
|
||||
|
||||
# --- system memory functions
|
||||
@ -334,7 +328,7 @@ def pid_exists(pid):
|
||||
"""Check For the existence of a unix pid."""
|
||||
return _psposix.pid_exists(pid)
|
||||
|
||||
def net_io_counters():
|
||||
def network_io_counters():
|
||||
"""Return network I/O statistics for every network interface
|
||||
installed on the system as a dict of raw tuples.
|
||||
"""
|
||||
@ -399,7 +393,6 @@ def disk_io_counters():
|
||||
finally:
|
||||
f.close()
|
||||
for line in lines:
|
||||
# http://www.mjmwired.net/kernel/Documentation/iostats.txt
|
||||
_, _, name, reads, _, rbytes, rtime, writes, _, wbytes, wtime = \
|
||||
line.split()[:11]
|
||||
if name in partitions:
|
||||
@ -633,20 +626,11 @@ class Process(object):
|
||||
data = {}
|
||||
for line in f:
|
||||
fields = line.split(None, 5)
|
||||
if not fields[0].endswith(':'):
|
||||
# new block section
|
||||
if len(fields) >= 5:
|
||||
yield (current_block.pop(), data)
|
||||
current_block.append(line)
|
||||
else:
|
||||
try:
|
||||
data[fields[0]] = int(fields[1]) * 1024
|
||||
except ValueError:
|
||||
if fields[0].startswith('VmFlags:'):
|
||||
# see issue #369
|
||||
continue
|
||||
else:
|
||||
raise ValueError("don't know how to interpret" \
|
||||
" line %r" % line)
|
||||
data[fields[0]] = int(fields[1]) * 1024
|
||||
yield (current_block.pop(), data)
|
||||
|
||||
if first_line: # smaps file can be empty
|
||||
@ -691,7 +675,7 @@ class Process(object):
|
||||
f.close()
|
||||
|
||||
if not os.path.exists('/proc/%s/smaps' % os.getpid()):
|
||||
def get_memory_maps(self, ext):
|
||||
def get_shared_libs(self, ext):
|
||||
msg = "couldn't find /proc/%s/smaps; kernel < 2.6.14 or CONFIG_MMU " \
|
||||
"kernel configuration option is not enabled" % self.pid
|
||||
raise NotImplementedError(msg)
|
||||
@ -947,7 +931,7 @@ class Process(object):
|
||||
if type_ == socket.SOCK_STREAM:
|
||||
status = _TCP_STATES_TABLE[status]
|
||||
else:
|
||||
status = CONN_NONE
|
||||
status = ""
|
||||
fd = int(inodes[inode])
|
||||
conn = nt_connection(fd, family, type_, laddr,
|
||||
raddr, status)
|
||||
@ -964,7 +948,7 @@ class Process(object):
|
||||
fd = int(inodes[inode])
|
||||
type_ = int(type_)
|
||||
conn = nt_connection(fd, family, type_, path,
|
||||
None, CONN_NONE)
|
||||
None, "")
|
||||
retlist.append(conn)
|
||||
else:
|
||||
raise ValueError(family)
|
||||
@ -1001,6 +985,13 @@ class Process(object):
|
||||
os.stat('/proc/%s' % self.pid)
|
||||
return ret
|
||||
|
||||
|
||||
# --- lsof implementation
|
||||
#
|
||||
# def get_connections(self):
|
||||
# lsof = _psposix.LsofParser(self.pid, self._process_name)
|
||||
# return lsof.get_process_connections()
|
||||
|
||||
@wrap_exceptions
|
||||
def get_num_fds(self):
|
||||
return len(os.listdir("/proc/%s/fd" % self.pid))
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -21,10 +21,7 @@ from psutil._compat import PY3, xrange, long, wraps
|
||||
# Windows specific extended namespace
|
||||
__extra__all__ = ["ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
|
||||
"HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS",
|
||||
"NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS",
|
||||
#
|
||||
"CONN_DELETE_TCB",
|
||||
]
|
||||
"NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS"]
|
||||
|
||||
|
||||
# --- module level constants (gets pushed up to psutil module)
|
||||
@ -49,25 +46,8 @@ except Exception:
|
||||
TOTAL_PHYMEM = None
|
||||
warnings.warn("couldn't determine platform's TOTAL_PHYMEM", RuntimeWarning)
|
||||
|
||||
CONN_DELETE_TCB = constant(11, "DELETE_TCB")
|
||||
WAIT_TIMEOUT = 0x00000102 # 258 in decimal
|
||||
ACCESS_DENIED_SET = frozenset([errno.EPERM, errno.EACCES, ERROR_ACCESS_DENIED])
|
||||
TCP_STATES_TABLE = {
|
||||
_psutil_mswindows.MIB_TCP_STATE_ESTAB : CONN_ESTABLISHED,
|
||||
_psutil_mswindows.MIB_TCP_STATE_SYN_SENT : CONN_SYN_SENT,
|
||||
_psutil_mswindows.MIB_TCP_STATE_SYN_RCVD : CONN_SYN_RECV,
|
||||
_psutil_mswindows.MIB_TCP_STATE_FIN_WAIT1 : CONN_FIN_WAIT1,
|
||||
_psutil_mswindows.MIB_TCP_STATE_FIN_WAIT2 : CONN_FIN_WAIT2,
|
||||
_psutil_mswindows.MIB_TCP_STATE_TIME_WAIT : CONN_TIME_WAIT,
|
||||
_psutil_mswindows.MIB_TCP_STATE_CLOSED : CONN_CLOSE,
|
||||
_psutil_mswindows.MIB_TCP_STATE_CLOSE_WAIT : CONN_CLOSE_WAIT,
|
||||
_psutil_mswindows.MIB_TCP_STATE_LAST_ACK : CONN_LAST_ACK,
|
||||
_psutil_mswindows.MIB_TCP_STATE_LISTEN : CONN_LISTEN,
|
||||
_psutil_mswindows.MIB_TCP_STATE_CLOSING : CONN_CLOSING,
|
||||
_psutil_mswindows.MIB_TCP_STATE_DELETE_TCB : CONN_DELETE_TCB,
|
||||
_psutil_mswindows.PSUTIL_CONN_NONE : CONN_NONE,
|
||||
}
|
||||
|
||||
|
||||
# process priority constants:
|
||||
# http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
|
||||
@ -175,7 +155,7 @@ def get_system_users():
|
||||
|
||||
get_pid_list = _psutil_mswindows.get_pid_list
|
||||
pid_exists = _psutil_mswindows.pid_exists
|
||||
net_io_counters = _psutil_mswindows.get_net_io_counters
|
||||
network_io_counters = _psutil_mswindows.get_network_io_counters
|
||||
disk_io_counters = _psutil_mswindows.get_disk_io_counters
|
||||
|
||||
# --- decorator
|
||||
@ -386,15 +366,8 @@ class Process(object):
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in conn_tmap])))
|
||||
families, types = conn_tmap[kind]
|
||||
rawlist = _psutil_mswindows.get_process_connections(self.pid, families,
|
||||
types)
|
||||
ret = []
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status = item
|
||||
status = TCP_STATES_TABLE[status]
|
||||
nt = nt_connection(fd, fam, type, laddr, raddr, status)
|
||||
ret.append(nt)
|
||||
return ret
|
||||
ret = _psutil_mswindows.get_process_connections(self.pid, families, types)
|
||||
return [nt_connection(*conn) for conn in ret]
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_nice(self):
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -44,20 +44,6 @@ except Exception:
|
||||
|
||||
_PAGESIZE = os.sysconf("SC_PAGE_SIZE")
|
||||
_cputimes_ntuple = namedtuple('cputimes', 'user nice system idle')
|
||||
# http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
|
||||
_TCP_STATES_TABLE = {_psutil_osx.TCPS_ESTABLISHED : CONN_ESTABLISHED,
|
||||
_psutil_osx.TCPS_SYN_SENT : CONN_SYN_SENT,
|
||||
_psutil_osx.TCPS_SYN_RECEIVED : CONN_SYN_RECV,
|
||||
_psutil_osx.TCPS_FIN_WAIT_1 : CONN_FIN_WAIT1,
|
||||
_psutil_osx.TCPS_FIN_WAIT_2 : CONN_FIN_WAIT2,
|
||||
_psutil_osx.TCPS_TIME_WAIT : CONN_TIME_WAIT,
|
||||
_psutil_osx.TCPS_CLOSED : CONN_CLOSE,
|
||||
_psutil_osx.TCPS_CLOSE_WAIT : CONN_CLOSE_WAIT,
|
||||
_psutil_osx.TCPS_LAST_ACK : CONN_LAST_ACK,
|
||||
_psutil_osx.TCPS_LISTEN : CONN_LISTEN,
|
||||
_psutil_osx.TCPS_CLOSING : CONN_CLOSING,
|
||||
_psutil_osx.PSUTIL_CONN_NONE : CONN_NONE,
|
||||
}
|
||||
|
||||
# --- functions
|
||||
|
||||
@ -132,7 +118,7 @@ def get_system_users():
|
||||
get_pid_list = _psutil_osx.get_pid_list
|
||||
pid_exists = _psposix.pid_exists
|
||||
get_disk_usage = _psposix.get_disk_usage
|
||||
net_io_counters = _psutil_osx.get_net_io_counters
|
||||
network_io_counters = _psutil_osx.get_network_io_counters
|
||||
disk_io_counters = _psutil_osx.get_disk_io_counters
|
||||
|
||||
# --- decorator
|
||||
@ -274,14 +260,8 @@ class Process(object):
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in conn_tmap])))
|
||||
families, types = conn_tmap[kind]
|
||||
rawlist = _psutil_osx.get_process_connections(self.pid, families, types)
|
||||
ret = []
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status = item
|
||||
status = _TCP_STATES_TABLE[status]
|
||||
nt = nt_connection(fd, fam, type, laddr, raddr, status)
|
||||
ret.append(nt)
|
||||
return ret
|
||||
ret = _psutil_osx.get_process_connections(self.pid, families, types)
|
||||
return [nt_connection(*conn) for conn in ret]
|
||||
|
||||
@wrap_exceptions
|
||||
def get_num_fds(self):
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,481 +0,0 @@
|
||||
#!/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.
|
||||
|
||||
"""Sun OS Solaris platform implementation."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import socket
|
||||
|
||||
import _psutil_sunos
|
||||
import _psutil_posix
|
||||
from psutil import _psposix
|
||||
from psutil._error import AccessDenied, NoSuchProcess, TimeoutExpired
|
||||
from psutil._compat import namedtuple, PY3
|
||||
from psutil._common import *
|
||||
|
||||
|
||||
__extra__all__ = ["CONN_IDLE", "CONN_BOUND"]
|
||||
|
||||
PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
|
||||
NUM_CPUS = os.sysconf("SC_NPROCESSORS_ONLN")
|
||||
BOOT_TIME = _psutil_sunos.get_process_basic_info(0)[3]
|
||||
TOTAL_PHYMEM = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
|
||||
|
||||
CONN_IDLE = constant(11, "IDLE")
|
||||
CONN_BOUND = constant(12, "BOUND")
|
||||
|
||||
_PAGESIZE = os.sysconf("SC_PAGE_SIZE")
|
||||
_cputimes_ntuple = namedtuple('cputimes', 'user system idle iowait')
|
||||
|
||||
disk_io_counters = _psutil_sunos.get_disk_io_counters
|
||||
net_io_counters = _psutil_sunos.get_net_io_counters
|
||||
get_disk_usage = _psposix.get_disk_usage
|
||||
get_system_boot_time = lambda: _psutil_sunos.get_process_basic_info(0)[3]
|
||||
|
||||
nt_virtmem_info = namedtuple('vmem', ' '.join([
|
||||
# all platforms
|
||||
'total', 'available', 'percent', 'used', 'free']))
|
||||
|
||||
def virtual_memory():
|
||||
# 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 nt_virtmem_info(total, avail, percent, used, free)
|
||||
|
||||
def swap_memory():
|
||||
sin, sout = _psutil_sunos.get_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(['swap', '-l', '-k'], stdout=subprocess.PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
if PY3:
|
||||
stdout = stdout.decode(sys.stdout.encoding)
|
||||
if p.returncode != 0:
|
||||
raise RuntimeError("'swap -l -k' failed (retcode=%s)" % retcode)
|
||||
|
||||
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:]
|
||||
t = t.replace('K', '')
|
||||
f = f.replace('K', '')
|
||||
total += int(int(t) * 1024)
|
||||
free += int(int(f) * 1024)
|
||||
used = total - free
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return nt_swapmeminfo(total, used, free, percent,
|
||||
sin * _PAGESIZE, sout * _PAGESIZE)
|
||||
|
||||
def get_pid_list():
|
||||
"""Returns a list of PIDs currently running on the system."""
|
||||
return [int(x) for x in os.listdir('/proc') if x.isdigit()]
|
||||
|
||||
def pid_exists(pid):
|
||||
"""Check for the existence of a unix pid."""
|
||||
return _psposix.pid_exists(pid)
|
||||
|
||||
def get_system_cpu_times():
|
||||
"""Return system-wide CPU times as a named tuple"""
|
||||
ret = _psutil_sunos.get_system_per_cpu_times()
|
||||
return _cputimes_ntuple(*[sum(x) for x in zip(*ret)])
|
||||
|
||||
def get_system_per_cpu_times():
|
||||
"""Return system per-CPU times as a list of named tuples"""
|
||||
ret = _psutil_sunos.get_system_per_cpu_times()
|
||||
return [_cputimes_ntuple(*x) for x in ret]
|
||||
|
||||
def get_system_users():
|
||||
"""Return currently connected users as a list of namedtuples."""
|
||||
retlist = []
|
||||
rawlist = _psutil_sunos.get_system_users()
|
||||
localhost = (':0.0', ':0')
|
||||
for item in rawlist:
|
||||
user, tty, hostname, tstamp, user_process = 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 = nt_user(user, tty, hostname, tstamp)
|
||||
retlist.append(nt)
|
||||
return retlist
|
||||
|
||||
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 = _psutil_sunos.get_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 get_disk_usage(mountpoint).total:
|
||||
continue
|
||||
ntuple = nt_partition(device, mountpoint, fstype, opts)
|
||||
retlist.append(ntuple)
|
||||
return retlist
|
||||
|
||||
|
||||
def wrap_exceptions(callable):
|
||||
"""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 callable(self, *args, **kwargs)
|
||||
except EnvironmentError:
|
||||
# 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.
|
||||
err = sys.exc_info()[1]
|
||||
if err.errno in (errno.ENOENT, errno.ESRCH):
|
||||
raise NoSuchProcess(self.pid, self._process_name)
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise AccessDenied(self.pid, self._process_name)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
_status_map = {
|
||||
_psutil_sunos.SSLEEP : STATUS_SLEEPING,
|
||||
_psutil_sunos.SRUN : STATUS_RUNNING,
|
||||
_psutil_sunos.SZOMB : STATUS_ZOMBIE,
|
||||
_psutil_sunos.SSTOP : STATUS_STOPPED,
|
||||
_psutil_sunos.SIDL : STATUS_IDLE,
|
||||
_psutil_sunos.SONPROC : STATUS_RUNNING, # same as run
|
||||
_psutil_sunos.SWAIT : STATUS_WAITING,
|
||||
}
|
||||
|
||||
_conn_status_map = {_psutil_sunos.TCPS_ESTABLISHED : CONN_ESTABLISHED,
|
||||
_psutil_sunos.TCPS_SYN_SENT : CONN_SYN_SENT,
|
||||
_psutil_sunos.TCPS_SYN_RCVD : CONN_SYN_RECV,
|
||||
_psutil_sunos.TCPS_FIN_WAIT_1 : CONN_FIN_WAIT1,
|
||||
_psutil_sunos.TCPS_FIN_WAIT_2 : CONN_FIN_WAIT2,
|
||||
_psutil_sunos.TCPS_TIME_WAIT : CONN_TIME_WAIT,
|
||||
_psutil_sunos.TCPS_CLOSED : CONN_CLOSE,
|
||||
_psutil_sunos.TCPS_CLOSE_WAIT : CONN_CLOSE_WAIT,
|
||||
_psutil_sunos.TCPS_LAST_ACK : CONN_LAST_ACK,
|
||||
_psutil_sunos.TCPS_LISTEN : CONN_LISTEN,
|
||||
_psutil_sunos.TCPS_CLOSING : CONN_CLOSING,
|
||||
_psutil_sunos.PSUTIL_CONN_NONE : CONN_NONE,
|
||||
_psutil_sunos.TCPS_IDLE : CONN_IDLE, # sunos specific
|
||||
_psutil_sunos.TCPS_BOUND : CONN_BOUND, # sunos specific
|
||||
}
|
||||
|
||||
|
||||
class Process(object):
|
||||
"""Wrapper class around underlying C implementation."""
|
||||
|
||||
__slots__ = ["pid", "_process_name"]
|
||||
|
||||
def __init__(self, pid):
|
||||
self.pid = pid
|
||||
self._process_name = None
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_name(self):
|
||||
# note: max len == 15
|
||||
return _psutil_sunos.get_process_name_and_args(self.pid)[0]
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_exe(self):
|
||||
# Will be guess 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.get_process_cmdline()
|
||||
return ""
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_cmdline(self):
|
||||
return _psutil_sunos.get_process_name_and_args(self.pid)[1].split(' ')
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_create_time(self):
|
||||
return _psutil_sunos.get_process_basic_info(self.pid)[3]
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_num_threads(self):
|
||||
return _psutil_sunos.get_process_basic_info(self.pid)[5]
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_nice(self):
|
||||
# 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.
|
||||
try:
|
||||
return _psutil_posix.getpriority(self.pid)
|
||||
except EnvironmentError:
|
||||
err = sys.exc_info()[1]
|
||||
if err.errno in (errno.ENOENT, errno.ESRCH):
|
||||
if pid_exists(self.pid):
|
||||
raise AccessDenied(self.pid, self._process_name)
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def set_process_nice(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._process_name)
|
||||
return _psutil_posix.setpriority(self.pid, value)
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_ppid(self):
|
||||
return _psutil_sunos.get_process_basic_info(self.pid)[0]
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_uids(self):
|
||||
real, effective, saved, _, _, _ = _psutil_sunos.get_process_cred(self.pid)
|
||||
return nt_uids(real, effective, saved)
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_gids(self):
|
||||
_, _, _, real, effective, saved = _psutil_sunos.get_process_cred(self.pid)
|
||||
return nt_uids(real, effective, saved)
|
||||
|
||||
@wrap_exceptions
|
||||
def get_cpu_times(self):
|
||||
user, system = _psutil_sunos.get_process_cpu_times(self.pid)
|
||||
return nt_cputimes(user, system)
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_terminal(self):
|
||||
hit_enoent = False
|
||||
tty = wrap_exceptions(_psutil_sunos.get_process_basic_info(self.pid)[0])
|
||||
if tty != _psutil_sunos.PRNODEV:
|
||||
for x in (0, 1, 2, 255):
|
||||
try:
|
||||
return os.readlink('/proc/%d/path/%d' % (self.pid, x))
|
||||
except OSError:
|
||||
err = sys.exc_info()[1]
|
||||
if err.errno == errno.ENOENT:
|
||||
hit_enoent = True
|
||||
continue
|
||||
raise
|
||||
if hit_enoent:
|
||||
# raise NSP if the process disappeared on us
|
||||
os.stat('/proc/%s' % self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_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
|
||||
try:
|
||||
return os.readlink("/proc/%s/path/cwd" % self.pid)
|
||||
except OSError:
|
||||
err = sys.exc_info()[1]
|
||||
if err.errno == errno.ENOENT:
|
||||
os.stat("/proc/%s" % self.pid)
|
||||
return None
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def get_memory_info(self):
|
||||
ret = _psutil_sunos.get_process_basic_info(self.pid)
|
||||
rss, vms = ret[1] * 1024, ret[2] * 1024
|
||||
return nt_meminfo(rss, vms)
|
||||
|
||||
# it seems Solaris uses rss and vms only
|
||||
get_ext_memory_info = get_memory_info
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_status(self):
|
||||
code = _psutil_sunos.get_process_basic_info(self.pid)[6]
|
||||
if code in _status_map:
|
||||
return _status_map[code]
|
||||
return constant(-1, "?")
|
||||
|
||||
@wrap_exceptions
|
||||
def get_process_threads(self):
|
||||
ret = []
|
||||
tids = os.listdir('/proc/%d/lwp' % self.pid)
|
||||
hit_enoent = False
|
||||
for tid in tids:
|
||||
tid = int(tid)
|
||||
try:
|
||||
utime, stime = _psutil_sunos.query_process_thread(self.pid, tid)
|
||||
except EnvironmentError:
|
||||
# ENOENT == thread gone in meantime
|
||||
err = sys.exc_info()[1]
|
||||
if err.errno == errno.ENOENT:
|
||||
hit_enoent = True
|
||||
continue
|
||||
raise
|
||||
else:
|
||||
nt = nt_thread(tid, utime, stime)
|
||||
ret.append(nt)
|
||||
if hit_enoent:
|
||||
# raise NSP if the process disappeared on us
|
||||
os.stat('/proc/%s' % self.pid)
|
||||
return ret
|
||||
|
||||
@wrap_exceptions
|
||||
def get_open_files(self):
|
||||
retlist = []
|
||||
hit_enoent = False
|
||||
pathdir = '/proc/%d/path' % self.pid
|
||||
for fd in os.listdir('/proc/%d/fd' % self.pid):
|
||||
path = os.path.join(pathdir, fd)
|
||||
if os.path.islink(path):
|
||||
try:
|
||||
file = os.readlink(path)
|
||||
except OSError:
|
||||
# ENOENT == file which is gone in the meantime
|
||||
err = sys.exc_info()[1]
|
||||
if err.errno == errno.ENOENT:
|
||||
hit_enoent = True
|
||||
continue
|
||||
raise
|
||||
else:
|
||||
if isfile_strict(file):
|
||||
retlist.append(nt_openfile(file, int(fd)))
|
||||
if hit_enoent:
|
||||
# raise NSP if the process disappeared on us
|
||||
os.stat('/proc/%s' % 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._process_name)
|
||||
if 'no such process' in stderr.lower():
|
||||
raise NoSuchProcess(self.pid, self._process_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, "", CONN_NONE)
|
||||
|
||||
@wrap_exceptions
|
||||
def get_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 = _psutil_sunos.get_process_connections(self.pid, families, types)
|
||||
# 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 rawlist:
|
||||
os.stat('/proc/%s' % self.pid) # will raise NSP if process is gone
|
||||
|
||||
ret = []
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status = item
|
||||
if fam not in families:
|
||||
continue
|
||||
if type not in types:
|
||||
continue
|
||||
status = _conn_status_map[status]
|
||||
nt = nt_connection(fd, fam, type, laddr, raddr, status)
|
||||
ret.append(nt)
|
||||
|
||||
# UNIX sockets
|
||||
if socket.AF_UNIX in families:
|
||||
ret.extend([nt_connection(*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 get_memory_maps(self):
|
||||
def toaddr(start, end):
|
||||
return '%s-%s' % (hex(start)[2:].strip('L'), hex(end)[2:].strip('L'))
|
||||
|
||||
retlist = []
|
||||
rawlist = _psutil_sunos.get_process_memory_maps(self.pid)
|
||||
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('/proc/%s/path/%s' % (self.pid, name))
|
||||
except OSError:
|
||||
err = sys.exc_info()[1]
|
||||
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 = '/proc/%s/path/%s' % (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('/proc/%s' % self.pid)
|
||||
return retlist
|
||||
|
||||
@wrap_exceptions
|
||||
def get_num_fds(self):
|
||||
return len(os.listdir("/proc/%s/fd" % self.pid))
|
||||
|
||||
@wrap_exceptions
|
||||
def get_num_ctx_switches(self):
|
||||
return nt_ctxsw(*_psutil_sunos.get_process_num_ctx_switches(self.pid))
|
||||
|
||||
@wrap_exceptions
|
||||
def process_wait(self, timeout=None):
|
||||
try:
|
||||
return _psposix.wait_pid(self.pid, timeout)
|
||||
except TimeoutExpired:
|
||||
raise TimeoutExpired(self.pid, self._process_name)
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*
|
||||
@ -993,10 +993,6 @@ psutil_search_tcplist(char *buf, struct kinfo_file *kif)
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
// a signaler for connections without an actual status
|
||||
static int PSUTIL_CONN_NONE = 128;
|
||||
|
||||
/*
|
||||
* Return connections opened by process.
|
||||
*/
|
||||
@ -1049,9 +1045,10 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
}
|
||||
|
||||
for (i = 0; i < cnt; i++) {
|
||||
int lport, rport, state;
|
||||
int lport, rport;
|
||||
char lip[200], rip[200];
|
||||
char path[PATH_MAX];
|
||||
char *state;
|
||||
int inseq;
|
||||
tuple = NULL;
|
||||
laddr = NULL;
|
||||
@ -1078,11 +1075,11 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
if ((kif->kf_sock_domain == AF_INET) ||
|
||||
(kif->kf_sock_domain == AF_INET6)) {
|
||||
// fill status
|
||||
state = PSUTIL_CONN_NONE;
|
||||
state = "";
|
||||
if (kif->kf_sock_type == SOCK_STREAM) {
|
||||
tcp = psutil_search_tcplist(tcplist, kif);
|
||||
if (tcp != NULL)
|
||||
state = (int)tcp->t_state;
|
||||
state = get_connection_status((int)tcp->t_state);
|
||||
}
|
||||
|
||||
// build addr and port
|
||||
@ -1109,7 +1106,7 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
}
|
||||
if (!raddr)
|
||||
goto error;
|
||||
tuple = Py_BuildValue("(iiiNNi)", kif->kf_fd,
|
||||
tuple = Py_BuildValue("(iiiNNs)", kif->kf_fd,
|
||||
kif->kf_sock_domain,
|
||||
kif->kf_sock_type,
|
||||
laddr,
|
||||
@ -1130,12 +1127,12 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
(sun->sun_len - (sizeof(*sun) - sizeof(sun->sun_path))),
|
||||
sun->sun_path);
|
||||
|
||||
tuple = Py_BuildValue("(iiisOi)", kif->kf_fd,
|
||||
tuple = Py_BuildValue("(iiisOs)", kif->kf_fd,
|
||||
kif->kf_sock_domain,
|
||||
kif->kf_sock_type,
|
||||
path,
|
||||
Py_None,
|
||||
PSUTIL_CONN_NONE);
|
||||
"");
|
||||
if (!tuple)
|
||||
goto error;
|
||||
if (PyList_Append(retList, tuple))
|
||||
@ -1467,7 +1464,7 @@ error:
|
||||
* Return a Python list of named tuples with overall network I/O information
|
||||
*/
|
||||
static PyObject*
|
||||
get_net_io_counters(PyObject* self, PyObject* args)
|
||||
get_network_io_counters(PyObject* self, PyObject* args)
|
||||
{
|
||||
char *buf = NULL, *lim, *next;
|
||||
struct if_msghdr *ifm;
|
||||
@ -1776,7 +1773,7 @@ PsutilMethods[] =
|
||||
{"get_disk_partitions", get_disk_partitions, METH_VARARGS,
|
||||
"Return a list of tuples including device, mount point and "
|
||||
"fs type for all partitions mounted on the system."},
|
||||
{"get_net_io_counters", get_net_io_counters, METH_VARARGS,
|
||||
{"get_network_io_counters", get_network_io_counters, METH_VARARGS,
|
||||
"Return dict of tuples of networks I/O information."},
|
||||
{"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
|
||||
"Return a Python dict of tuples for disk I/O information"},
|
||||
@ -1839,7 +1836,6 @@ void init_psutil_bsd(void)
|
||||
#else
|
||||
PyObject *module = Py_InitModule("_psutil_bsd", PsutilMethods);
|
||||
#endif
|
||||
// process status constants
|
||||
PyModule_AddIntConstant(module, "SSTOP", SSTOP);
|
||||
PyModule_AddIntConstant(module, "SSLEEP", SSLEEP);
|
||||
PyModule_AddIntConstant(module, "SRUN", SRUN);
|
||||
@ -1847,19 +1843,6 @@ void init_psutil_bsd(void)
|
||||
PyModule_AddIntConstant(module, "SWAIT", SWAIT);
|
||||
PyModule_AddIntConstant(module, "SLOCK", SLOCK);
|
||||
PyModule_AddIntConstant(module, "SZOMB", SZOMB);
|
||||
// connection status constants
|
||||
PyModule_AddIntConstant(module, "TCPS_CLOSED", TCPS_CLOSED);
|
||||
PyModule_AddIntConstant(module, "TCPS_CLOSING", TCPS_CLOSING);
|
||||
PyModule_AddIntConstant(module, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT);
|
||||
PyModule_AddIntConstant(module, "TCPS_LISTEN", TCPS_LISTEN);
|
||||
PyModule_AddIntConstant(module, "TCPS_ESTABLISHED", TCPS_ESTABLISHED);
|
||||
PyModule_AddIntConstant(module, "TCPS_SYN_SENT", TCPS_SYN_SENT);
|
||||
PyModule_AddIntConstant(module, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED);
|
||||
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1);
|
||||
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2);
|
||||
PyModule_AddIntConstant(module, "TCPS_LAST_ACK", TCPS_LAST_ACK);
|
||||
PyModule_AddIntConstant(module, "TCPS_TIME_WAIT", TCPS_TIME_WAIT);
|
||||
PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
|
||||
|
||||
if (module == NULL) {
|
||||
INITERROR;
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*
|
||||
@ -45,6 +45,6 @@ static PyObject* get_system_per_cpu_times(PyObject* self, PyObject* args);
|
||||
#endif
|
||||
static PyObject* get_system_boot_time(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
|
||||
static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_network_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_system_users(PyObject* self, PyObject* args);
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*/
|
||||
|
@ -1,12 +1,11 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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 functions.
|
||||
*/
|
||||
|
||||
#define _GNU_SOURCE
|
||||
#include <Python.h>
|
||||
#include <errno.h>
|
||||
#include <stdlib.h>
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*
|
||||
|
@ -610,25 +610,10 @@ get_process_memory_info(PyObject* self, PyObject* args)
|
||||
|
||||
CloseHandle(hProcess);
|
||||
|
||||
// PROCESS_MEMORY_COUNTERS values are defined as SIZE_T which on 64bits
|
||||
// is an (unsigned long long) and on 32bits is an (unsigned int).
|
||||
// "_WIN64" is defined if we're running a 64bit Python interpreter not
|
||||
// exclusively if the *system* is 64bit.
|
||||
#if defined(_WIN64)
|
||||
return Py_BuildValue("(kKKKKKKKKK)",
|
||||
cnt.PageFaultCount, // unsigned long
|
||||
(unsigned long long)cnt.PeakWorkingSetSize,
|
||||
(unsigned long long)cnt.WorkingSetSize,
|
||||
(unsigned long long)cnt.QuotaPeakPagedPoolUsage,
|
||||
(unsigned long long)cnt.QuotaPagedPoolUsage,
|
||||
(unsigned long long)cnt.QuotaPeakNonPagedPoolUsage,
|
||||
(unsigned long long)cnt.QuotaNonPagedPoolUsage,
|
||||
(unsigned long long)cnt.PagefileUsage,
|
||||
(unsigned long long)cnt.PeakPagefileUsage,
|
||||
(unsigned long long)private);
|
||||
#else
|
||||
// py 2.4
|
||||
#if (PY_MAJOR_VERSION == 2) && (PY_MINOR_VERSION <= 4)
|
||||
return Py_BuildValue("(kIIIIIIIII)",
|
||||
cnt.PageFaultCount, // unsigned long
|
||||
cnt.PageFaultCount,
|
||||
(unsigned int)cnt.PeakWorkingSetSize,
|
||||
(unsigned int)cnt.WorkingSetSize,
|
||||
(unsigned int)cnt.QuotaPeakPagedPoolUsage,
|
||||
@ -638,6 +623,19 @@ get_process_memory_info(PyObject* self, PyObject* args)
|
||||
(unsigned int)cnt.PagefileUsage,
|
||||
(unsigned int)cnt.PeakPagefileUsage,
|
||||
(unsigned int)private);
|
||||
#else
|
||||
// py >= 2.5
|
||||
return Py_BuildValue("(knnnnnnnnn)",
|
||||
cnt.PageFaultCount,
|
||||
cnt.PeakWorkingSetSize,
|
||||
cnt.WorkingSetSize,
|
||||
cnt.QuotaPeakPagedPoolUsage,
|
||||
cnt.QuotaPagedPoolUsage,
|
||||
cnt.QuotaPeakNonPagedPoolUsage,
|
||||
cnt.QuotaNonPagedPoolUsage,
|
||||
cnt.PagefileUsage,
|
||||
cnt.PeakPagefileUsage,
|
||||
private);
|
||||
#endif
|
||||
}
|
||||
|
||||
@ -651,7 +649,8 @@ get_process_memory_info_2(PyObject* self, PyObject* args)
|
||||
DWORD pid;
|
||||
PSYSTEM_PROCESS_INFORMATION process;
|
||||
PVOID buffer;
|
||||
SIZE_T private;
|
||||
ULONG m0;
|
||||
SIZE_T m1, m2, m3, m4, m5, m6, m7, m8, m9;
|
||||
|
||||
if (! PyArg_ParseTuple(args, "l", &pid)) {
|
||||
return NULL;
|
||||
@ -659,41 +658,31 @@ get_process_memory_info_2(PyObject* self, PyObject* args)
|
||||
if (! get_process_info(pid, &process, &buffer)) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
m0 = process->PageFaultCount;
|
||||
m1 = process->PeakWorkingSetSize;
|
||||
m2 = process->WorkingSetSize;
|
||||
m3 = process->QuotaPeakPagedPoolUsage;
|
||||
m4 = process->QuotaPagedPoolUsage;
|
||||
m5 = process->QuotaPeakNonPagedPoolUsage;
|
||||
m6 = process->QuotaNonPagedPoolUsage;
|
||||
m7 = process->PagefileUsage;
|
||||
m8 = process->PeakPagefileUsage;
|
||||
#if (_WIN32_WINNT >= 0x0501)
|
||||
private = process->PrivatePageCount;
|
||||
m9 = process->PrivatePageCount; // private me
|
||||
#else
|
||||
private = 0;
|
||||
m9 = 0;
|
||||
#endif
|
||||
free(buffer);
|
||||
|
||||
// SYSTEM_PROCESS_INFORMATIONvalues are defined as SIZE_T which on 64
|
||||
// bits is an (unsigned long long) and on 32bits is an (unsigned int).
|
||||
// "_WIN64" is defined if we're running a 64bit Python interpreter not
|
||||
// exclusively if the *system* is 64bit.
|
||||
#if defined(_WIN64)
|
||||
return Py_BuildValue("(kKKKKKKKKK)",
|
||||
process->PageFaultCount, // unsigned long
|
||||
(unsigned long long)process->PeakWorkingSetSize,
|
||||
(unsigned long long)process->WorkingSetSize,
|
||||
(unsigned long long)process->QuotaPeakPagedPoolUsage,
|
||||
(unsigned long long)process->QuotaPagedPoolUsage,
|
||||
(unsigned long long)process->QuotaPeakNonPagedPoolUsage,
|
||||
(unsigned long long)process->QuotaNonPagedPoolUsage,
|
||||
(unsigned long long)process->PagefileUsage,
|
||||
(unsigned long long)process->PeakPagefileUsage,
|
||||
(unsigned long long)private);
|
||||
#else
|
||||
// py 2.4
|
||||
#if (PY_MAJOR_VERSION == 2) && (PY_MINOR_VERSION <= 4)
|
||||
return Py_BuildValue("(kIIIIIIIII)",
|
||||
process->PageFaultCount, // unsigned long
|
||||
(unsigned int)process->PeakWorkingSetSize,
|
||||
(unsigned int)process->WorkingSetSize,
|
||||
(unsigned int)process->QuotaPeakPagedPoolUsage,
|
||||
(unsigned int)process->QuotaPagedPoolUsage,
|
||||
(unsigned int)process->QuotaPeakNonPagedPoolUsage,
|
||||
(unsigned int)process->QuotaNonPagedPoolUsage,
|
||||
(unsigned int)process->PagefileUsage,
|
||||
(unsigned int)process->PeakPagefileUsage,
|
||||
(unsigned int)private);
|
||||
(unsigned int)m0, (unsigned int)m1, (unsigned int)m2, (unsigned int)m3,
|
||||
(unsigned int)m4, (unsigned int)m5, (unsigned int)m6, (unsigned int)m7,
|
||||
(unsigned int)m8, (unsigned int)m9);
|
||||
#else
|
||||
return Py_BuildValue("(knnnnnnnnn)",
|
||||
m0, m1, m2, m3, m4, m5, m6, m7, m8, m9);
|
||||
#endif
|
||||
}
|
||||
|
||||
@ -1387,6 +1376,39 @@ get_process_username(PyObject* self, PyObject* args)
|
||||
#define AF_INET6 23
|
||||
#endif
|
||||
|
||||
static char *state_to_string(ULONG state)
|
||||
{
|
||||
switch (state)
|
||||
{
|
||||
case MIB_TCP_STATE_CLOSED:
|
||||
return "CLOSE";
|
||||
case MIB_TCP_STATE_LISTEN:
|
||||
return "LISTEN";
|
||||
case MIB_TCP_STATE_SYN_SENT:
|
||||
return "SYN_SENT";
|
||||
case MIB_TCP_STATE_SYN_RCVD:
|
||||
return "SYN_RECV";
|
||||
case MIB_TCP_STATE_ESTAB:
|
||||
return "ESTABLISHED";
|
||||
case MIB_TCP_STATE_FIN_WAIT1:
|
||||
return "FIN_WAIT1";
|
||||
case MIB_TCP_STATE_FIN_WAIT2:
|
||||
return "FIN_WAIT2";
|
||||
case MIB_TCP_STATE_CLOSE_WAIT:
|
||||
return "CLOSE_WAIT";
|
||||
case MIB_TCP_STATE_CLOSING:
|
||||
return "CLOSING";
|
||||
case MIB_TCP_STATE_LAST_ACK:
|
||||
return "LAST_ACK";
|
||||
case MIB_TCP_STATE_TIME_WAIT:
|
||||
return "TIME_WAIT";
|
||||
case MIB_TCP_STATE_DELETE_TCB:
|
||||
return "DELETE_TCB";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/* mingw support */
|
||||
#ifndef _IPRTRMIB_H
|
||||
typedef struct _MIB_TCP6ROW_OWNER_PID
|
||||
@ -1457,10 +1479,6 @@ typedef struct _MIB_UDP6TABLE_OWNER_PID
|
||||
Py_DECREF(_SOCK_STREAM);\
|
||||
Py_DECREF(_SOCK_DGRAM);
|
||||
|
||||
// a signaler for connections without an actual status
|
||||
static int PSUTIL_CONN_NONE = 128;
|
||||
|
||||
|
||||
/*
|
||||
* Return a list of network connections opened by a process
|
||||
*/
|
||||
@ -1623,13 +1641,13 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
if (addressTupleRemote == NULL)
|
||||
goto error;
|
||||
|
||||
connectionTuple = Py_BuildValue("(iiiNNi)",
|
||||
connectionTuple = Py_BuildValue("(iiiNNs)",
|
||||
-1,
|
||||
AF_INET,
|
||||
SOCK_STREAM,
|
||||
addressTupleLocal,
|
||||
addressTupleRemote,
|
||||
tcp4Table->table[i].dwState
|
||||
state_to_string(tcp4Table->table[i].dwState)
|
||||
);
|
||||
if (!connectionTuple)
|
||||
goto error;
|
||||
@ -1711,13 +1729,13 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
if (addressTupleRemote == NULL)
|
||||
goto error;
|
||||
|
||||
connectionTuple = Py_BuildValue("(iiiNNi)",
|
||||
connectionTuple = Py_BuildValue("(iiiNNs)",
|
||||
-1,
|
||||
AF_INET6,
|
||||
SOCK_STREAM,
|
||||
addressTupleLocal,
|
||||
addressTupleRemote,
|
||||
tcp6Table->table[i].dwState
|
||||
state_to_string(tcp6Table->table[i].dwState)
|
||||
);
|
||||
if (!connectionTuple)
|
||||
goto error;
|
||||
@ -1778,13 +1796,13 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
if (addressTupleLocal == NULL)
|
||||
goto error;
|
||||
|
||||
connectionTuple = Py_BuildValue("(iiiNNi)",
|
||||
connectionTuple = Py_BuildValue("(iiiNNs)",
|
||||
-1,
|
||||
AF_INET,
|
||||
SOCK_DGRAM,
|
||||
addressTupleLocal,
|
||||
PyTuple_New(0),
|
||||
PSUTIL_CONN_NONE
|
||||
""
|
||||
);
|
||||
if (!connectionTuple)
|
||||
goto error;
|
||||
@ -1845,13 +1863,13 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
if (addressTupleLocal == NULL)
|
||||
goto error;
|
||||
|
||||
connectionTuple = Py_BuildValue("(iiiNNi)",
|
||||
connectionTuple = Py_BuildValue("(iiiNNs)",
|
||||
-1,
|
||||
AF_INET6,
|
||||
SOCK_DGRAM,
|
||||
addressTupleLocal,
|
||||
PyTuple_New(0),
|
||||
PSUTIL_CONN_NONE
|
||||
""
|
||||
);
|
||||
if (!connectionTuple)
|
||||
goto error;
|
||||
@ -2197,11 +2215,10 @@ get_disk_usage(PyObject* self, PyObject* args)
|
||||
* Return a Python list of named tuples with overall network I/O information
|
||||
*/
|
||||
static PyObject*
|
||||
get_net_io_counters(PyObject* self, PyObject* args)
|
||||
get_network_io_counters(PyObject* self, PyObject* args)
|
||||
{
|
||||
int attempts = 0;
|
||||
int outBufLen = 15000;
|
||||
char ifname[2000];
|
||||
DWORD dwRetVal = 0;
|
||||
MIB_IFROW *pIfRow = NULL;
|
||||
ULONG flags = 0;
|
||||
@ -2211,6 +2228,7 @@ get_net_io_counters(PyObject* self, PyObject* args)
|
||||
|
||||
PyObject* py_retdict = PyDict_New();
|
||||
PyObject* py_nic_info = NULL;
|
||||
PyObject* py_pre_nic_name = NULL;
|
||||
PyObject* py_nic_name = NULL;
|
||||
|
||||
if (py_retdict == NULL) {
|
||||
@ -2243,6 +2261,7 @@ get_net_io_counters(PyObject* self, PyObject* args)
|
||||
|
||||
pCurrAddresses = pAddresses;
|
||||
while (pCurrAddresses) {
|
||||
py_pre_nic_name = NULL;
|
||||
py_nic_name = NULL;
|
||||
py_nic_info = NULL;
|
||||
pIfRow = (MIB_IFROW *) malloc(sizeof(MIB_IFROW));
|
||||
@ -2271,12 +2290,17 @@ get_net_io_counters(PyObject* self, PyObject* args)
|
||||
if (!py_nic_info)
|
||||
goto error;
|
||||
|
||||
sprintf(ifname, "%wS", pCurrAddresses->FriendlyName);
|
||||
py_nic_name = Py_BuildValue("s", ifname);
|
||||
py_pre_nic_name = PyUnicode_FromWideChar(
|
||||
pCurrAddresses->FriendlyName,
|
||||
wcslen(pCurrAddresses->FriendlyName));
|
||||
if (py_pre_nic_name == NULL)
|
||||
goto error;
|
||||
py_nic_name = PyUnicode_FromObject(py_pre_nic_name);
|
||||
if (py_nic_name == NULL)
|
||||
goto error;
|
||||
if (PyDict_SetItem(py_retdict, py_nic_name, py_nic_info))
|
||||
goto error;
|
||||
Py_XDECREF(py_pre_nic_name);
|
||||
Py_XDECREF(py_nic_name);
|
||||
Py_XDECREF(py_nic_info);
|
||||
|
||||
@ -2288,6 +2312,7 @@ get_net_io_counters(PyObject* self, PyObject* args)
|
||||
return py_retdict;
|
||||
|
||||
error:
|
||||
Py_XDECREF(py_pre_nic_name);
|
||||
Py_XDECREF(py_nic_name);
|
||||
Py_XDECREF(py_nic_info);
|
||||
Py_DECREF(py_retdict);
|
||||
@ -2953,7 +2978,7 @@ PsutilMethods[] =
|
||||
"Return system per-cpu times as a list of tuples"},
|
||||
{"get_disk_usage", get_disk_usage, METH_VARARGS,
|
||||
"Return path's disk total and free as a Python tuple."},
|
||||
{"get_net_io_counters", get_net_io_counters, METH_VARARGS,
|
||||
{"get_network_io_counters", get_network_io_counters, METH_VARARGS,
|
||||
"Return dict of tuples of networks I/O information."},
|
||||
{"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
|
||||
"Return dict of tuples of disks I/O information."},
|
||||
@ -3033,7 +3058,7 @@ struct module_state {
|
||||
INITERROR;
|
||||
}
|
||||
|
||||
// process status constants
|
||||
// Public constants
|
||||
// http://msdn.microsoft.com/en-us/library/ms683211(v=vs.85).aspx
|
||||
PyModule_AddIntConstant(module, "ABOVE_NORMAL_PRIORITY_CLASS",
|
||||
ABOVE_NORMAL_PRIORITY_CLASS);
|
||||
@ -3047,37 +3072,7 @@ struct module_state {
|
||||
NORMAL_PRIORITY_CLASS);
|
||||
PyModule_AddIntConstant(module, "REALTIME_PRIORITY_CLASS",
|
||||
REALTIME_PRIORITY_CLASS);
|
||||
// connection status constants
|
||||
// http://msdn.microsoft.com/en-us/library/cc669305.aspx
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_CLOSED",
|
||||
MIB_TCP_STATE_CLOSED);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_CLOSING",
|
||||
MIB_TCP_STATE_CLOSING);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_CLOSE_WAIT",
|
||||
MIB_TCP_STATE_CLOSE_WAIT);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_LISTEN",
|
||||
MIB_TCP_STATE_LISTEN);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_ESTAB",
|
||||
MIB_TCP_STATE_ESTAB);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_SYN_SENT",
|
||||
MIB_TCP_STATE_SYN_SENT);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_SYN_RCVD",
|
||||
MIB_TCP_STATE_SYN_RCVD);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_FIN_WAIT1",
|
||||
MIB_TCP_STATE_FIN_WAIT1);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_FIN_WAIT2",
|
||||
MIB_TCP_STATE_FIN_WAIT2);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_LAST_ACK",
|
||||
MIB_TCP_STATE_LAST_ACK);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_TIME_WAIT",
|
||||
MIB_TCP_STATE_TIME_WAIT);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_TIME_WAIT",
|
||||
MIB_TCP_STATE_TIME_WAIT);
|
||||
PyModule_AddIntConstant(module, "MIB_TCP_STATE_DELETE_TCB",
|
||||
MIB_TCP_STATE_DELETE_TCB);
|
||||
PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE",
|
||||
PSUTIL_CONN_NONE);
|
||||
// ...for internal use in _psutil_mswindows.py
|
||||
// private constants
|
||||
PyModule_AddIntConstant(module, "INFINITE", INFINITE);
|
||||
PyModule_AddIntConstant(module, "ERROR_ACCESS_DENIED", ERROR_ACCESS_DENIED);
|
||||
SetSeDebug();
|
||||
|
@ -59,7 +59,7 @@ static PyObject* get_system_cpu_times(PyObject* self, PyObject* args);
|
||||
static PyObject* pid_exists(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_usage(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
|
||||
static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_network_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_system_users(PyObject* self, PyObject* args);
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*
|
||||
@ -284,7 +284,7 @@ get_process_memory_maps(PyObject* self, PyObject* args)
|
||||
int pagesize = getpagesize();
|
||||
long pid;
|
||||
kern_return_t err = KERN_SUCCESS;
|
||||
mach_port_t task = MACH_PORT_NULL;
|
||||
mach_port_t task;
|
||||
uint32_t depth = 1;
|
||||
vm_address_t address = 0;
|
||||
vm_size_t size = 0;
|
||||
@ -343,6 +343,8 @@ get_process_memory_maps(PyObject* self, PyObject* args)
|
||||
(info.max_protection & VM_PROT_WRITE) ? 'w' : '-',
|
||||
(info.max_protection & VM_PROT_EXECUTE) ? 'x' : '-');
|
||||
|
||||
address += size;
|
||||
|
||||
err = proc_regionfilename(pid, address, buf, sizeof(buf));
|
||||
|
||||
if (info.share_mode == SM_COW && info.ref_count == 1) {
|
||||
@ -398,9 +400,6 @@ get_process_memory_maps(PyObject* self, PyObject* args)
|
||||
goto error;
|
||||
Py_DECREF(py_tuple);
|
||||
}
|
||||
|
||||
//increment address for the next map/file
|
||||
address += size;
|
||||
}
|
||||
|
||||
if (task != MACH_PORT_NULL)
|
||||
@ -888,10 +887,10 @@ get_process_threads(PyObject* self, PyObject* args)
|
||||
int err, j, ret;
|
||||
kern_return_t kr;
|
||||
unsigned int info_count = TASK_BASIC_INFO_COUNT;
|
||||
mach_port_t task = MACH_PORT_NULL;
|
||||
mach_port_t task;
|
||||
struct task_basic_info tasks_info;
|
||||
thread_act_port_array_t thread_list = NULL;
|
||||
thread_info_data_t thinfo_basic;
|
||||
thread_info_data_t thinfo;
|
||||
thread_basic_info_t basic_info_th;
|
||||
mach_msg_type_number_t thread_count, thread_info_count;
|
||||
|
||||
@ -942,15 +941,15 @@ get_process_threads(PyObject* self, PyObject* args)
|
||||
pyTuple = NULL;
|
||||
thread_info_count = THREAD_INFO_MAX;
|
||||
kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
|
||||
(thread_info_t)thinfo_basic, &thread_info_count);
|
||||
(thread_info_t)thinfo, &thread_info_count);
|
||||
if (kr != KERN_SUCCESS) {
|
||||
PyErr_Format(PyExc_RuntimeError, "thread_info() with flag THREAD_BASIC_INFO failed");
|
||||
PyErr_Format(PyExc_RuntimeError, "thread_info() failed");
|
||||
goto error;
|
||||
}
|
||||
|
||||
basic_info_th = (thread_basic_info_t)thinfo_basic;
|
||||
pyTuple = Py_BuildValue("Iff",
|
||||
j+1,
|
||||
basic_info_th = (thread_basic_info_t)thinfo;
|
||||
// XXX - thread_info structure does not provide any process id;
|
||||
// the best we can do is assigning an incremental bogus value
|
||||
pyTuple = Py_BuildValue("Iff", j + 1,
|
||||
(float)basic_info_th->user_time.microseconds / 1000000.0,
|
||||
(float)basic_info_th->system_time.microseconds / 1000000.0
|
||||
);
|
||||
@ -1103,8 +1102,40 @@ error:
|
||||
}
|
||||
|
||||
|
||||
// a signaler for connections without an actual status
|
||||
static int PSUTIL_CONN_NONE = 128;
|
||||
/*
|
||||
* mathes Linux net/tcp_states.h:
|
||||
* http://students.mimuw.edu.pl/lxr/source/include/net/tcp_states.h
|
||||
*/
|
||||
static char *
|
||||
get_connection_status(int st) {
|
||||
switch (st) {
|
||||
case TCPS_CLOSED:
|
||||
return "CLOSE";
|
||||
case TCPS_CLOSING:
|
||||
return "CLOSING";
|
||||
case TCPS_CLOSE_WAIT:
|
||||
return "CLOSE_WAIT";
|
||||
case TCPS_LISTEN:
|
||||
return "LISTEN";
|
||||
case TCPS_ESTABLISHED:
|
||||
return "ESTABLISHED";
|
||||
case TCPS_SYN_SENT:
|
||||
return "SYN_SENT";
|
||||
case TCPS_SYN_RECEIVED:
|
||||
return "SYN_RECV";
|
||||
case TCPS_FIN_WAIT_1:
|
||||
return "FIN_WAIT_1";
|
||||
case TCPS_FIN_WAIT_2:
|
||||
return "FIN_WAIT_2";
|
||||
case TCPS_LAST_ACK:
|
||||
return "LAST_ACK";
|
||||
case TCPS_TIME_WAIT:
|
||||
return "TIME_WAIT";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Return process TCP and UDP connections as a list of tuples.
|
||||
@ -1202,8 +1233,9 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
// --- /errors checking
|
||||
|
||||
//
|
||||
int fd, family, type, lport, rport, state;
|
||||
int fd, family, type, lport, rport;
|
||||
char lip[200], rip[200];
|
||||
char *state;
|
||||
int inseq;
|
||||
PyObject* _family;
|
||||
PyObject* _type;
|
||||
@ -1260,10 +1292,11 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
lport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_lport);
|
||||
rport = ntohs(si.psi.soi_proto.pri_tcp.tcpsi_ini.insi_fport);
|
||||
if (type == SOCK_STREAM) {
|
||||
state = (int)si.psi.soi_proto.pri_tcp.tcpsi_state;
|
||||
state = get_connection_status((int)si.psi.soi_proto.pri_tcp.tcpsi_state);
|
||||
}
|
||||
|
||||
else {
|
||||
state = PSUTIL_CONN_NONE;
|
||||
state = "";
|
||||
}
|
||||
|
||||
laddr = Py_BuildValue("(si)", lip, lport);
|
||||
@ -1279,7 +1312,7 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
goto error;
|
||||
|
||||
// construct the python list
|
||||
tuple = Py_BuildValue("(iiiNNi)", fd, family, type, laddr, raddr,
|
||||
tuple = Py_BuildValue("(iiiNNs)", fd, family, type, laddr, raddr,
|
||||
state);
|
||||
if (!tuple)
|
||||
goto error;
|
||||
@ -1289,11 +1322,11 @@ get_process_connections(PyObject* self, PyObject* args)
|
||||
}
|
||||
else if (family == AF_UNIX) {
|
||||
// construct the python list
|
||||
tuple = Py_BuildValue("(iiissi)",
|
||||
tuple = Py_BuildValue("(iiisss)",
|
||||
fd, family, type,
|
||||
si.psi.soi_proto.pri_un.unsi_addr.ua_sun.sun_path,
|
||||
si.psi.soi_proto.pri_un.unsi_caddr.ua_sun.sun_path,
|
||||
PSUTIL_CONN_NONE);
|
||||
"");
|
||||
if (!tuple)
|
||||
goto error;
|
||||
if (PyList_Append(retList, tuple))
|
||||
@ -1369,7 +1402,7 @@ get_process_num_fds(PyObject* self, PyObject* args)
|
||||
* Return a Python list of named tuples with overall network I/O information
|
||||
*/
|
||||
static PyObject*
|
||||
get_net_io_counters(PyObject* self, PyObject* args)
|
||||
get_network_io_counters(PyObject* self, PyObject* args)
|
||||
{
|
||||
char *buf = NULL, *lim, *next;
|
||||
struct if_msghdr *ifm;
|
||||
@ -1539,12 +1572,7 @@ get_disk_io_counters(PyObject* self, PyObject* args)
|
||||
}
|
||||
|
||||
CFNumberRef number;
|
||||
int64_t reads = 0;
|
||||
int64_t writes = 0;
|
||||
int64_t read_bytes = 0;
|
||||
int64_t write_bytes = 0;
|
||||
int64_t read_time = 0;
|
||||
int64_t write_time = 0;
|
||||
int64_t reads, writes, read_bytes, write_bytes, read_time, write_time = 0;
|
||||
|
||||
/* Get disk reads/writes */
|
||||
if ((number = (CFNumberRef)CFDictionaryGetValue(
|
||||
@ -1727,7 +1755,7 @@ PsutilMethods[] =
|
||||
{"get_disk_partitions", get_disk_partitions, METH_VARARGS,
|
||||
"Return a list of tuples including device, mount point and "
|
||||
"fs type for all partitions mounted on the system."},
|
||||
{"get_net_io_counters", get_net_io_counters, METH_VARARGS,
|
||||
{"get_network_io_counters", get_network_io_counters, METH_VARARGS,
|
||||
"Return dict of tuples of networks I/O information."},
|
||||
{"get_disk_io_counters", get_disk_io_counters, METH_VARARGS,
|
||||
"Return dict of tuples of disks I/O information."},
|
||||
@ -1800,19 +1828,6 @@ init_psutil_osx(void)
|
||||
PyModule_AddIntConstant(module, "SSLEEP", SSLEEP);
|
||||
PyModule_AddIntConstant(module, "SSTOP", SSTOP);
|
||||
PyModule_AddIntConstant(module, "SZOMB", SZOMB);
|
||||
// connection status constants
|
||||
PyModule_AddIntConstant(module, "TCPS_CLOSED", TCPS_CLOSED);
|
||||
PyModule_AddIntConstant(module, "TCPS_CLOSING", TCPS_CLOSING);
|
||||
PyModule_AddIntConstant(module, "TCPS_CLOSE_WAIT", TCPS_CLOSE_WAIT);
|
||||
PyModule_AddIntConstant(module, "TCPS_LISTEN", TCPS_LISTEN);
|
||||
PyModule_AddIntConstant(module, "TCPS_ESTABLISHED", TCPS_ESTABLISHED);
|
||||
PyModule_AddIntConstant(module, "TCPS_SYN_SENT", TCPS_SYN_SENT);
|
||||
PyModule_AddIntConstant(module, "TCPS_SYN_RECEIVED", TCPS_SYN_RECEIVED);
|
||||
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_1", TCPS_FIN_WAIT_1);
|
||||
PyModule_AddIntConstant(module, "TCPS_FIN_WAIT_2", TCPS_FIN_WAIT_2);
|
||||
PyModule_AddIntConstant(module, "TCPS_LAST_ACK", TCPS_LAST_ACK);
|
||||
PyModule_AddIntConstant(module, "TCPS_TIME_WAIT", TCPS_TIME_WAIT);
|
||||
PyModule_AddIntConstant(module, "PSUTIL_CONN_NONE", PSUTIL_CONN_NONE);
|
||||
|
||||
if (module == NULL) {
|
||||
INITERROR;
|
||||
|
@ -37,6 +37,6 @@ static PyObject* get_system_cpu_times(PyObject* self, PyObject* args);
|
||||
static PyObject* get_system_per_cpu_times(PyObject* self, PyObject* args);
|
||||
static PyObject* get_system_boot_time(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
|
||||
static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_network_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_system_users(PyObject* self, PyObject* args);
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*
|
||||
@ -127,3 +127,6 @@ void init_psutil_posix(void)
|
||||
return module;
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
* Copyright (c) 2009, Jay Loden, 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.
|
||||
*
|
||||
|
File diff suppressed because it is too large
Load Diff
@ -1,29 +0,0 @@
|
||||
/*
|
||||
* $Id$
|
||||
*
|
||||
* 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 module functions for _psutil_sunos extension
|
||||
*/
|
||||
|
||||
#include <Python.h>
|
||||
|
||||
// processes
|
||||
static PyObject* query_process_thread(PyObject* self, PyObject* args);
|
||||
static PyObject* get_process_basic_info(PyObject* self, PyObject* args);
|
||||
static PyObject* get_process_name_and_args(PyObject* self, PyObject* args);
|
||||
static PyObject* get_process_cpu_times(PyObject* self, PyObject* args);
|
||||
static PyObject* get_process_cred(PyObject* self, PyObject* args);
|
||||
static PyObject* get_process_memory_maps(PyObject* self, PyObject* args);
|
||||
static PyObject* get_process_num_ctx_switches(PyObject* self, PyObject* args);
|
||||
static PyObject* get_process_connections(PyObject* self, PyObject* args);
|
||||
|
||||
// system
|
||||
static PyObject* get_swap_mem(PyObject* self, PyObject* args);
|
||||
static PyObject* get_system_users(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_partitions(PyObject* self, PyObject* args);
|
||||
static PyObject* get_system_per_cpu_times(PyObject* self, PyObject* args);
|
||||
static PyObject* get_disk_io_counters(PyObject* self, PyObject* args);
|
||||
static PyObject* get_net_io_counters(PyObject* self, PyObject* args);
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
|
@ -1,5 +0,0 @@
|
||||
[egg_info]
|
||||
tag_build =
|
||||
tag_date = 0
|
||||
tag_svn_revision = 0
|
||||
|
@ -1,41 +1,17 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009 Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
import sys
|
||||
import os
|
||||
import shutil
|
||||
import fnmatch
|
||||
try:
|
||||
from setuptools import setup, Extension
|
||||
except ImportError:
|
||||
from distutils.core import setup, Extension
|
||||
|
||||
|
||||
def clean():
|
||||
"""'python setup.py clean' custom command."""
|
||||
def rglob(path, pattern):
|
||||
return [os.path.join(dirpath, f)
|
||||
for dirpath, dirnames, files in os.walk(path)
|
||||
for f in fnmatch.filter(files, pattern)]
|
||||
|
||||
for dirname in ('build', 'dist'):
|
||||
if os.path.isdir(dirname):
|
||||
sys.stdout.write('removing directory: %s\n' % dirname)
|
||||
shutil.rmtree(dirname)
|
||||
|
||||
for dirpath, dirnames, files in os.walk('.'):
|
||||
if dirpath.endswith(('__pycache__', '.egg-info')):
|
||||
sys.stdout.write('removing directory %s\n' % dirpath)
|
||||
shutil.rmtree(dirpath)
|
||||
|
||||
for pattern in ['*.py[co]', '*.s[ol]', '*~', '*.orig', '*.rej', '*.swp']:
|
||||
for x in rglob('.', pattern):
|
||||
sys.stdout.write('removing file %s\n' % x)
|
||||
os.remove(x)
|
||||
|
||||
def get_version():
|
||||
INIT = os.path.abspath(os.path.join(os.path.dirname(__file__),
|
||||
'psutil', '__init__.py'))
|
||||
@ -114,22 +90,11 @@ elif sys.platform.startswith("linux"):
|
||||
sources=['psutil/_psutil_linux.c'],
|
||||
),
|
||||
posix_extension]
|
||||
# Solaris
|
||||
elif sys.platform.lower().startswith('sunos'):
|
||||
extensions = [Extension('_psutil_sunos',
|
||||
sources=['psutil/_psutil_sunos.c'],
|
||||
libraries=['kstat', 'nsl'],
|
||||
),
|
||||
posix_extension]
|
||||
else:
|
||||
sys.exit('platform %s is not supported' % sys.platform)
|
||||
|
||||
|
||||
def main():
|
||||
# "python setup.py clean" custom command
|
||||
if len(sys.argv) > 1 and sys.argv[1] == 'clean':
|
||||
return clean()
|
||||
|
||||
setup_args = dict(
|
||||
name='psutil',
|
||||
version=VERSION,
|
||||
@ -141,7 +106,7 @@ def main():
|
||||
'tty', 'ionice', 'uptime', 'taskmgr', 'process', 'df',
|
||||
'iotop', 'iostat', 'ifconfig', 'taskset', 'who', 'pidof',
|
||||
'pmap', 'smem', 'monitoring',],
|
||||
author='Giampaolo Rodola',
|
||||
author='Giampaolo Rodola, Jay Loden',
|
||||
author_email='psutil@googlegroups.com',
|
||||
maintainer='Giampaolo Rodola',
|
||||
maintainer_email='g.rodola <at> gmail <dot> com',
|
||||
@ -149,8 +114,6 @@ def main():
|
||||
platforms='Platform Independent',
|
||||
license='License :: OSI Approved :: BSD License',
|
||||
packages=['psutil'],
|
||||
test_suite='test.test_psutil',
|
||||
# see: python setup.py register --list-classifiers
|
||||
classifiers=[
|
||||
'Development Status :: 5 - Production/Stable',
|
||||
'Environment :: Console',
|
||||
@ -160,7 +123,6 @@ def main():
|
||||
'Operating System :: POSIX',
|
||||
'Operating System :: POSIX :: Linux',
|
||||
'Operating System :: POSIX :: BSD :: FreeBSD',
|
||||
'Operating System :: POSIX :: SunOS/Solaris',
|
||||
'Operating System :: OS Independent',
|
||||
'Programming Language :: C',
|
||||
'Programming Language :: Python',
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -16,10 +16,13 @@ import os
|
||||
import psutil
|
||||
|
||||
from psutil._compat import PY3
|
||||
from test_psutil import *
|
||||
from test_psutil import DEVNULL
|
||||
from test_psutil import (reap_children, get_test_subprocess, sh, which,
|
||||
skipUnless)
|
||||
|
||||
|
||||
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
|
||||
TOLERANCE = 200 * 1024 # 200 KB
|
||||
MUSE_AVAILABLE = which('muse')
|
||||
|
||||
|
||||
@ -53,6 +56,14 @@ class BSDSpecificTestCase(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
reap_children()
|
||||
|
||||
def assert_eq_w_tol(self, first, second, tolerance):
|
||||
difference = abs(first - second)
|
||||
if difference <= tolerance:
|
||||
return
|
||||
msg = '%r != %r within %r delta (%r difference)' \
|
||||
% (first, second, tolerance, difference)
|
||||
raise AssertionError(msg)
|
||||
|
||||
def test_BOOT_TIME(self):
|
||||
s = sysctl('sysctl kern.boottime')
|
||||
s = s[s.find(" sec = ") + 7:]
|
||||
@ -119,98 +130,69 @@ class BSDSpecificTestCase(unittest.TestCase):
|
||||
syst = sysctl("sysctl vm.stats.vm.v_page_count") * PAGESIZE
|
||||
self.assertEqual(psutil.virtual_memory().total, syst)
|
||||
|
||||
@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=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().active, syst, 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=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().inactive, syst, 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=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().wired, syst, 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=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().cached, syst, 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=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().free, syst, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_buffers(self):
|
||||
syst = sysctl("vfs.bufspace")
|
||||
self.assertAlmostEqual(psutil.virtual_memory().buffers, syst,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().buffers, syst, TOLERANCE)
|
||||
|
||||
# --- virtual_memory(); tests against muse
|
||||
|
||||
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
|
||||
@skipUnless(MUSE_AVAILABLE)
|
||||
def test_total(self):
|
||||
num = muse('Total')
|
||||
self.assertEqual(psutil.virtual_memory().total, num)
|
||||
|
||||
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
|
||||
@retry_before_failing()
|
||||
@skipUnless(MUSE_AVAILABLE)
|
||||
def test_active(self):
|
||||
num = muse('Active')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().active, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().active, num, TOLERANCE)
|
||||
|
||||
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
|
||||
@retry_before_failing()
|
||||
@skipUnless(MUSE_AVAILABLE)
|
||||
def test_inactive(self):
|
||||
num = muse('Inactive')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().inactive, num, TOLERANCE)
|
||||
|
||||
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
|
||||
@retry_before_failing()
|
||||
@skipUnless(MUSE_AVAILABLE)
|
||||
def test_wired(self):
|
||||
num = muse('Wired')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().wired, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().wired, num, TOLERANCE)
|
||||
|
||||
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
|
||||
@retry_before_failing()
|
||||
@skipUnless(MUSE_AVAILABLE)
|
||||
def test_cached(self):
|
||||
num = muse('Cache')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().cached, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().cached, num, TOLERANCE)
|
||||
|
||||
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
|
||||
@retry_before_failing()
|
||||
@skipUnless(MUSE_AVAILABLE)
|
||||
def test_free(self):
|
||||
num = muse('Free')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().free, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().free, num, TOLERANCE)
|
||||
|
||||
@unittest.skipUnless(MUSE_AVAILABLE, "muse cmdline tool is not available")
|
||||
@retry_before_failing()
|
||||
@skipUnless(MUSE_AVAILABLE)
|
||||
def test_buffers(self):
|
||||
num = muse('Buffer')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().buffers, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().buffers, num, TOLERANCE)
|
||||
|
||||
|
||||
def test_main():
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(BSDSpecificTestCase))
|
||||
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
return result.wasSuccessful()
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not test_main():
|
||||
sys.exit(1)
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(BSDSpecificTestCase))
|
||||
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -14,16 +14,24 @@ import time
|
||||
import os
|
||||
import re
|
||||
|
||||
from test_psutil import *
|
||||
from test_psutil import sh, get_test_subprocess
|
||||
from psutil._compat import PY3
|
||||
import psutil
|
||||
|
||||
|
||||
TOLERANCE = 200 * 1024 # 200 KB
|
||||
|
||||
|
||||
class LinuxSpecificTestCase(unittest.TestCase):
|
||||
|
||||
@unittest.skipIf(POSIX and not hasattr(os, 'statvfs'),
|
||||
reason="os.statvfs() function not available on this platform")
|
||||
@skip_on_not_implemented()
|
||||
def assert_eq_w_tol(self, first, second, tolerance):
|
||||
difference = abs(first - second)
|
||||
if difference <= tolerance:
|
||||
return
|
||||
msg = '%r != %r within %r delta (%r difference)' \
|
||||
% (first, second, tolerance, difference)
|
||||
raise AssertionError(msg)
|
||||
|
||||
def test_disks(self):
|
||||
# test psutil.disk_usage() and psutil.disk_partitions()
|
||||
# against "df -a"
|
||||
@ -71,52 +79,40 @@ class LinuxSpecificTestCase(unittest.TestCase):
|
||||
total = int(lines[0].split()[1]) * 1024
|
||||
self.assertEqual(total, psutil.virtual_memory().total)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_used(self):
|
||||
lines = sh('free').split('\n')[1:]
|
||||
used = int(lines[0].split()[2]) * 1024
|
||||
self.assertAlmostEqual(used, psutil.virtual_memory().used,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(used, psutil.virtual_memory().used, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_free(self):
|
||||
lines = sh('free').split('\n')[1:]
|
||||
free = int(lines[0].split()[3]) * 1024
|
||||
self.assertAlmostEqual(free, psutil.virtual_memory().free,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(free, psutil.virtual_memory().free, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_buffers(self):
|
||||
lines = sh('free').split('\n')[1:]
|
||||
buffers = int(lines[0].split()[5]) * 1024
|
||||
self.assertAlmostEqual(buffers, psutil.virtual_memory().buffers,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(buffers, psutil.virtual_memory().buffers, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_cached(self):
|
||||
lines = sh('free').split('\n')[1:]
|
||||
cached = int(lines[0].split()[6]) * 1024
|
||||
self.assertAlmostEqual(cached, psutil.virtual_memory().cached,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(cached, psutil.virtual_memory().cached, TOLERANCE)
|
||||
|
||||
def test_swapmem_total(self):
|
||||
lines = sh('free').split('\n')[1:]
|
||||
total = int(lines[2].split()[1]) * 1024
|
||||
self.assertEqual(total, psutil.swap_memory().total)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_swapmem_used(self):
|
||||
lines = sh('free').split('\n')[1:]
|
||||
used = int(lines[2].split()[2]) * 1024
|
||||
self.assertAlmostEqual(used, psutil.swap_memory().used,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(used, psutil.swap_memory().used, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_swapmem_free(self):
|
||||
lines = sh('free').split('\n')[1:]
|
||||
free = int(lines[2].split()[3]) * 1024
|
||||
self.assertAlmostEqual(free, psutil.swap_memory().free,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(free, psutil.swap_memory().free, TOLERANCE)
|
||||
|
||||
def test_cpu_times(self):
|
||||
fields = psutil.cpu_times()._fields
|
||||
@ -126,25 +122,20 @@ class LinuxSpecificTestCase(unittest.TestCase):
|
||||
# guest >= 2.6.24
|
||||
# guest_nice >= 3.2.0
|
||||
if kernel_ver_info >= (2, 6, 11):
|
||||
self.assertIn('steal', fields)
|
||||
assert 'steal' in fields, fields
|
||||
else:
|
||||
self.assertNotIn('steal', fields)
|
||||
assert 'steal' not in fields, fields
|
||||
if kernel_ver_info >= (2, 6, 24):
|
||||
self.assertIn('guest', fields)
|
||||
assert 'guest' in fields, fields
|
||||
else:
|
||||
self.assertNotIn('guest', fields)
|
||||
assert 'guest' not in fields, fields
|
||||
if kernel_ver_info >= (3, 2, 0):
|
||||
self.assertIn('guest_nice', fields)
|
||||
assert 'guest_nice' in fields, fields
|
||||
else:
|
||||
self.assertNotIn('guest_nice', fields)
|
||||
assert 'guest_nice' not in fields, fields
|
||||
|
||||
|
||||
def test_main():
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(LinuxSpecificTestCase))
|
||||
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
return result.wasSuccessful()
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not test_main():
|
||||
sys.exit(1)
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(LinuxSpecificTestCase))
|
||||
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -16,10 +16,11 @@ import re
|
||||
import psutil
|
||||
|
||||
from psutil._compat import PY3
|
||||
from test_psutil import *
|
||||
from test_psutil import reap_children, get_test_subprocess, sh
|
||||
|
||||
|
||||
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
|
||||
TOLERANCE = 500 * 1024 # 500 KB
|
||||
|
||||
|
||||
def sysctl(cmdline):
|
||||
@ -54,6 +55,14 @@ class OSXSpecificTestCase(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
reap_children()
|
||||
|
||||
def assert_eq_w_tol(self, first, second, tolerance):
|
||||
difference = abs(first - second)
|
||||
if difference <= tolerance:
|
||||
return
|
||||
msg = '%r != %r (tolerance=%r, difference=%s)' \
|
||||
% (first, second, tolerance, difference)
|
||||
raise AssertionError(msg)
|
||||
|
||||
def test_process_create_time(self):
|
||||
cmdline = "ps -o lstart -p %s" %self.pid
|
||||
p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
|
||||
@ -99,29 +108,21 @@ class OSXSpecificTestCase(unittest.TestCase):
|
||||
sysctl_hwphymem = sysctl('sysctl hw.memsize')
|
||||
self.assertEqual(sysctl_hwphymem, psutil.TOTAL_PHYMEM)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_free(self):
|
||||
num = vm_stat("free")
|
||||
self.assertAlmostEqual(psutil.virtual_memory().free, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().free, num, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_active(self):
|
||||
num = vm_stat("active")
|
||||
self.assertAlmostEqual(psutil.virtual_memory().active, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().active, num, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_inactive(self):
|
||||
num = vm_stat("inactive")
|
||||
self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().inactive, num, TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_wired(self):
|
||||
num = vm_stat("wired")
|
||||
self.assertAlmostEqual(psutil.virtual_memory().wired, num,
|
||||
delta=TOLERANCE)
|
||||
self.assert_eq_w_tol(psutil.virtual_memory().wired, num, TOLERANCE)
|
||||
|
||||
# --- swap mem
|
||||
|
||||
@ -145,12 +146,7 @@ class OSXSpecificTestCase(unittest.TestCase):
|
||||
self.assertEqual(tot1, tot2)
|
||||
|
||||
|
||||
def test_main():
|
||||
if __name__ == '__main__':
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(OSXSpecificTestCase))
|
||||
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
return result.wasSuccessful()
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not test_main():
|
||||
sys.exit(1)
|
||||
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -16,7 +16,8 @@ import datetime
|
||||
import psutil
|
||||
|
||||
from psutil._compat import PY3
|
||||
from test_psutil import *
|
||||
from test_psutil import (get_test_subprocess, reap_children, PYTHON, LINUX, OSX,
|
||||
BSD, skip_on_access_denied, sh, skipIf)
|
||||
|
||||
|
||||
def ps(cmd):
|
||||
@ -25,15 +26,12 @@ def ps(cmd):
|
||||
"""
|
||||
if not LINUX:
|
||||
cmd = cmd.replace(" --no-headers ", " ")
|
||||
if SUNOS:
|
||||
cmd = cmd.replace("-o command", "-o comm")
|
||||
cmd = cmd.replace("-o start", "-o stime")
|
||||
p = subprocess.Popen(cmd, shell=1, stdout=subprocess.PIPE)
|
||||
output = p.communicate()[0].strip()
|
||||
if PY3:
|
||||
output = str(output, sys.stdout.encoding)
|
||||
if not LINUX:
|
||||
output = output.split('\n')[1].strip()
|
||||
output = output.split('\n')[1]
|
||||
try:
|
||||
return int(output)
|
||||
except ValueError:
|
||||
@ -98,16 +96,13 @@ class PosixSpecificTestCase(unittest.TestCase):
|
||||
name_psutil = psutil.Process(self.pid).name.lower()
|
||||
self.assertEqual(name_ps, name_psutil)
|
||||
|
||||
@unittest.skipIf(OSX or BSD,
|
||||
'ps -o start not available')
|
||||
@skipIf(OSX or BSD)
|
||||
def test_process_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
|
||||
if SUNOS:
|
||||
time_psutil = round(time_psutil)
|
||||
time_psutil_tstamp = datetime.datetime.fromtimestamp(
|
||||
time_psutil = datetime.datetime.fromtimestamp(
|
||||
time_psutil).strftime("%H:%M:%S")
|
||||
self.assertEqual(time_ps, time_psutil_tstamp)
|
||||
self.assertEqual(time_ps, time_psutil)
|
||||
|
||||
def test_process_exe(self):
|
||||
ps_pathname = ps("ps --no-headers -o command -p %s" %self.pid).split(' ')[0]
|
||||
@ -127,28 +122,21 @@ class PosixSpecificTestCase(unittest.TestCase):
|
||||
def test_process_cmdline(self):
|
||||
ps_cmdline = ps("ps --no-headers -o command -p %s" %self.pid)
|
||||
psutil_cmdline = " ".join(psutil.Process(self.pid).cmdline)
|
||||
if SUNOS:
|
||||
# ps on Solaris only shows the first part of the cmdline
|
||||
psutil_cmdline = psutil_cmdline.split(" ")[0]
|
||||
self.assertEqual(ps_cmdline, psutil_cmdline)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_get_pids(self):
|
||||
# Note: this test might fail if the OS is starting/killing
|
||||
# other processes in the meantime
|
||||
if SUNOS:
|
||||
cmd = ["ps", "ax"]
|
||||
else:
|
||||
cmd = ["ps", "ax", "-o", "pid"]
|
||||
p = get_test_subprocess(cmd, stdout=subprocess.PIPE)
|
||||
p = get_test_subprocess(["ps", "ax", "-o", "pid"], stdout=subprocess.PIPE)
|
||||
output = p.communicate()[0].strip()
|
||||
if PY3:
|
||||
output = str(output, sys.stdout.encoding)
|
||||
output = output.replace('PID', '')
|
||||
p.wait()
|
||||
pids_ps = []
|
||||
for line in output.split('\n')[1:]:
|
||||
if line:
|
||||
pid = int(line.split()[0].strip())
|
||||
pids_ps.append(pid)
|
||||
for pid in output.split('\n'):
|
||||
if pid:
|
||||
pids_ps.append(int(pid.strip()))
|
||||
# remove ps subprocess pid which is supposed to be dead in meantime
|
||||
pids_ps.remove(p.pid)
|
||||
pids_psutil = psutil.get_pid_list()
|
||||
@ -164,15 +152,12 @@ class PosixSpecificTestCase(unittest.TestCase):
|
||||
[x for x in pids_ps if x not in pids_psutil]
|
||||
self.fail("difference: " + str(difference))
|
||||
|
||||
# for some reason ifconfig -a does not report differente interfaces
|
||||
# psutil does
|
||||
@unittest.skipIf(SUNOS, "test not reliable on SUNOS")
|
||||
def test_nic_names(self):
|
||||
p = subprocess.Popen("ifconfig -a", shell=1, stdout=subprocess.PIPE)
|
||||
output = p.communicate()[0].strip()
|
||||
if PY3:
|
||||
output = str(output, sys.stdout.encoding)
|
||||
for nic in psutil.net_io_counters(pernic=True).keys():
|
||||
for nic in psutil.network_io_counters(pernic=True).keys():
|
||||
for line in output.split():
|
||||
if line.startswith(nic):
|
||||
break
|
||||
@ -189,50 +174,8 @@ class PosixSpecificTestCase(unittest.TestCase):
|
||||
self.assertTrue(u.name in users, u.name)
|
||||
self.assertTrue(u.terminal in terminals, u.terminal)
|
||||
|
||||
def test_fds_open(self):
|
||||
# Note: this fails from time to time; I'm keen on thinking
|
||||
# it doesn't mean something is broken
|
||||
def call(p, attr):
|
||||
attr = getattr(p, name, None)
|
||||
if attr is not None and callable(attr):
|
||||
ret = attr()
|
||||
else:
|
||||
ret = attr
|
||||
|
||||
p = psutil.Process(os.getpid())
|
||||
attrs = []
|
||||
failures = []
|
||||
for name in dir(psutil.Process):
|
||||
if name.startswith('_') \
|
||||
or name.startswith('set_') \
|
||||
or name in ('terminate', 'kill', 'suspend', 'resume', 'nice',
|
||||
'send_signal', 'wait', 'get_children', 'as_dict'):
|
||||
continue
|
||||
else:
|
||||
try:
|
||||
num1 = p.get_num_fds()
|
||||
for x in range(2):
|
||||
call(p, name)
|
||||
num2 = p.get_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))
|
||||
|
||||
|
||||
|
||||
|
||||
def test_main():
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(PosixSpecificTestCase))
|
||||
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
return result.wasSuccessful()
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not test_main():
|
||||
sys.exit(1)
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(PosixSpecificTestCase))
|
||||
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
|
@ -1,44 +0,0 @@
|
||||
#!/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.
|
||||
|
||||
"""Sun OS specific tests. These are implicitly run by test_psutil.py."""
|
||||
|
||||
import psutil
|
||||
from test_psutil import *
|
||||
|
||||
|
||||
class SunOSSpecificTestCase(unittest.TestCase):
|
||||
|
||||
def test_swap_memory(self):
|
||||
out = sh('swap -l -k')
|
||||
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:]
|
||||
t = t.replace('K', '')
|
||||
f = f.replace('K', '')
|
||||
total += int(int(t) * 1024)
|
||||
free += int(int(f) * 1024)
|
||||
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_main():
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(SunOSSpecificTestCase))
|
||||
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
return result.wasSuccessful()
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not test_main():
|
||||
sys.exit(1)
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -11,6 +11,8 @@ import unittest
|
||||
import platform
|
||||
import signal
|
||||
import time
|
||||
import warnings
|
||||
import atexit
|
||||
import sys
|
||||
import subprocess
|
||||
import errno
|
||||
@ -19,23 +21,23 @@ import traceback
|
||||
import psutil
|
||||
import _psutil_mswindows
|
||||
from psutil._compat import PY3, callable, long
|
||||
from test_psutil import *
|
||||
|
||||
from test_psutil import reap_children, get_test_subprocess, wait_for_pid, warn
|
||||
try:
|
||||
import wmi
|
||||
except ImportError:
|
||||
err = sys.exc_info()[1]
|
||||
register_warning("Couldn't run wmi tests: %s" % str(err))
|
||||
atexit.register(warn, "Couldn't run wmi tests: %s" % str(err))
|
||||
wmi = None
|
||||
try:
|
||||
import win32api
|
||||
import win32con
|
||||
except ImportError:
|
||||
err = sys.exc_info()[1]
|
||||
register_warning("Couldn't run pywin32 tests: %s" % str(err))
|
||||
atexit.register(warn, "Couldn't run pywin32 tests: %s" % str(err))
|
||||
win32api = None
|
||||
|
||||
|
||||
|
||||
class WindowsSpecificTestCase(unittest.TestCase):
|
||||
|
||||
def setUp(self):
|
||||
@ -76,7 +78,7 @@ class WindowsSpecificTestCase(unittest.TestCase):
|
||||
out = p.communicate()[0]
|
||||
if PY3:
|
||||
out = str(out, sys.stdout.encoding)
|
||||
nics = psutil.net_io_counters(pernic=True).keys()
|
||||
nics = psutil.network_io_counters(pernic=True).keys()
|
||||
for nic in nics:
|
||||
if "pseudo-interface" in nic.replace(' ', '-').lower():
|
||||
continue
|
||||
@ -147,8 +149,6 @@ class WindowsSpecificTestCase(unittest.TestCase):
|
||||
|
||||
# --- psutil namespace functions and constants tests
|
||||
|
||||
@unittest.skipUnless(hasattr(os, 'NUMBER_OF_PROCESSORS'),
|
||||
'NUMBER_OF_PROCESSORS env var is not available')
|
||||
def test_NUM_CPUS(self):
|
||||
num_cpus = int(os.environ['NUMBER_OF_PROCESSORS'])
|
||||
self.assertEqual(num_cpus, psutil.NUM_CPUS)
|
||||
@ -294,9 +294,9 @@ class TestDualProcessImplementation(unittest.TestCase):
|
||||
def assert_ge_0(obj):
|
||||
if isinstance(obj, tuple):
|
||||
for value in obj:
|
||||
self.assertGreaterEqual(value, 0)
|
||||
assert value >= 0, value
|
||||
elif isinstance(obj, (int, long, float)):
|
||||
self.assertGreaterEqual(obj, 0)
|
||||
assert obj >= 0, obj
|
||||
else:
|
||||
assert 0 # case not handled which needs to be fixed
|
||||
|
||||
@ -306,19 +306,17 @@ class TestDualProcessImplementation(unittest.TestCase):
|
||||
else:
|
||||
if isinstance(ret2, (int, long, float)):
|
||||
diff = abs(ret1 - ret2)
|
||||
self.assertLessEqual(diff, tolerance)
|
||||
assert diff <= tolerance, diff
|
||||
elif isinstance(ret2, tuple):
|
||||
for a, b in zip(ret1, ret2):
|
||||
diff = abs(a - b)
|
||||
self.assertLessEqual(diff, tolerance)
|
||||
assert diff <= tolerance, diff
|
||||
|
||||
failures = []
|
||||
for name, tolerance in self.fun_names:
|
||||
meth1 = wrap_exceptions(getattr(_psutil_mswindows, name))
|
||||
meth2 = wrap_exceptions(getattr(_psutil_mswindows, name + '_2'))
|
||||
for p in psutil.process_iter():
|
||||
if name == 'get_process_memory_info' and p.pid == os.getpid():
|
||||
continue
|
||||
#
|
||||
try:
|
||||
ret1 = meth1(p.pid)
|
||||
@ -361,13 +359,8 @@ class TestDualProcessImplementation(unittest.TestCase):
|
||||
self.assertRaises(psutil.NoSuchProcess, meth, ZOMBIE_PID)
|
||||
|
||||
|
||||
def test_main():
|
||||
if __name__ == '__main__':
|
||||
test_suite = unittest.TestSuite()
|
||||
test_suite.addTest(unittest.makeSuite(WindowsSpecificTestCase))
|
||||
test_suite.addTest(unittest.makeSuite(TestDualProcessImplementation))
|
||||
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
return result.wasSuccessful()
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not test_main():
|
||||
sys.exit(1)
|
||||
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
|
@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Copyright (c) 2009, Jay Loden, 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.
|
||||
|
||||
@ -17,12 +17,13 @@ import time
|
||||
import socket
|
||||
import threading
|
||||
import types
|
||||
import sys
|
||||
|
||||
import psutil
|
||||
import psutil._common
|
||||
from psutil._compat import PY3, callable, xrange
|
||||
from test_psutil import *
|
||||
from test_psutil import POSIX, LINUX, WINDOWS, OSX, BSD, TESTFN
|
||||
from test_psutil import (reap_children, skipUnless, skipIf, supports_ipv6,
|
||||
safe_remove, get_test_subprocess)
|
||||
|
||||
# disable cache for Process class properties
|
||||
psutil._common.cached_property.enabled = False
|
||||
@ -92,9 +93,7 @@ class TestProcessObjectLeaks(Base):
|
||||
for attr in [x for x in dir(self) if x.startswith('test')]:
|
||||
if attr[5:] not in supported_attrs:
|
||||
meth = getattr(self, attr)
|
||||
name = meth.__func__.__name__.replace('test_', '')
|
||||
@unittest.skipIf(True,
|
||||
"%s not supported on this platform" % name)
|
||||
@skipIf(True)
|
||||
def test_(self):
|
||||
pass
|
||||
setattr(self, attr, types.MethodType(test_, self))
|
||||
@ -184,7 +183,7 @@ class TestProcessObjectLeaks(Base):
|
||||
def test_terminal(self):
|
||||
self.execute('terminal')
|
||||
|
||||
@unittest.skipIf(POSIX, "not worth being tested on POSIX (pure python)")
|
||||
@skipUnless(WINDOWS)
|
||||
def test_resume(self):
|
||||
self.execute('resume')
|
||||
|
||||
@ -207,12 +206,12 @@ class TestProcessObjectLeaks(Base):
|
||||
f.close()
|
||||
|
||||
# OSX implementation is unbelievably slow
|
||||
@unittest.skipIf(OSX, "OSX implementation is too slow")
|
||||
@skipIf(OSX)
|
||||
def test_get_memory_maps(self):
|
||||
self.execute('get_memory_maps')
|
||||
|
||||
# Linux implementation is pure python so since it's slow we skip it
|
||||
@unittest.skipIf(LINUX, "not worth being tested on Linux (pure python)")
|
||||
@skipIf(LINUX)
|
||||
def test_get_connections(self):
|
||||
def create_socket(family, type):
|
||||
sock = socket.socket(family, type)
|
||||
@ -233,14 +232,8 @@ class TestProcessObjectLeaks(Base):
|
||||
s.bind(TESTFN)
|
||||
s.listen(1)
|
||||
socks.append(s)
|
||||
kind = 'all'
|
||||
# TODO: UNIX sockets are temporarily implemented by parsing
|
||||
# 'pfiles' cmd output; we don't want that part of the code to
|
||||
# be executed.
|
||||
if SUNOS:
|
||||
kind = 'inet'
|
||||
try:
|
||||
self.execute('get_connections', kind=kind)
|
||||
self.execute('get_connections', kind='all')
|
||||
finally:
|
||||
for s in socks:
|
||||
s.close()
|
||||
@ -286,16 +279,13 @@ class TestModuleFunctionsLeaks(Base):
|
||||
if callable(obj):
|
||||
retvalue = obj(*args, **kwargs)
|
||||
|
||||
@unittest.skipIf(POSIX, "not worth being tested on POSIX (pure python)")
|
||||
@skipIf(POSIX)
|
||||
def test_pid_exists(self):
|
||||
self.execute('pid_exists', os.getpid())
|
||||
|
||||
def test_virtual_memory(self):
|
||||
self.execute('virtual_memory')
|
||||
|
||||
# TODO: remove this skip when this gets fixed
|
||||
@unittest.skipIf(SUNOS,
|
||||
"not worth being tested on SUNOS (uses a subprocess)")
|
||||
def test_swap_memory(self):
|
||||
self.execute('swap_memory')
|
||||
|
||||
@ -305,22 +295,21 @@ class TestModuleFunctionsLeaks(Base):
|
||||
def test_per_cpu_times(self):
|
||||
self.execute('cpu_times', percpu=True)
|
||||
|
||||
@unittest.skipIf(POSIX, "not worth being tested on POSIX (pure python)")
|
||||
@skipUnless(WINDOWS)
|
||||
def test_disk_usage(self):
|
||||
self.execute('disk_usage', '.')
|
||||
|
||||
def test_disk_partitions(self):
|
||||
self.execute('disk_partitions')
|
||||
|
||||
def test_net_io_counters(self):
|
||||
self.execute('net_io_counters')
|
||||
def test_network_io_counters(self):
|
||||
self.execute('network_io_counters')
|
||||
|
||||
def test_disk_io_counters(self):
|
||||
self.execute('disk_io_counters')
|
||||
|
||||
# XXX - on Windows this produces a false positive
|
||||
@unittest.skipIf(WINDOWS,
|
||||
"XXX produces a false positive on Windows")
|
||||
@skipIf(WINDOWS)
|
||||
def test_get_users(self):
|
||||
self.execute('get_users')
|
||||
|
||||
@ -332,9 +321,7 @@ def test_main():
|
||||
TestModuleFunctionsLeaks,]
|
||||
for test in tests:
|
||||
test_suite.addTest(unittest.makeSuite(test))
|
||||
result = unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
return result.wasSuccessful()
|
||||
unittest.TextTestRunner(verbosity=2).run(test_suite)
|
||||
|
||||
if __name__ == '__main__':
|
||||
if not test_main():
|
||||
sys.exit(1)
|
||||
test_main()
|
||||
|
File diff suppressed because it is too large
Load Diff
Loading…
Reference in New Issue
Block a user