зеркало из https://github.com/mozilla/gecko-dev.git
bug 1481612 - vendor an unpacked win64 wheel of psutil 5.4.3. r=gps
This change uses the previously added `--with-windows-wheel` option to vendor a win64 wheel of psutil. This patch was produced by running: `mach vendor python --with-windows-wheel psutil==5.4.3`. We vendor this wheel unpacked so that we can insert it into sys.path in mach without needing a virtualenv in which to install a wheel with pip, since we have a chicken-and-egg problem there where configure creates the virtualenv but we'd like to be able to use psutil before we run configure. Differential Revision: https://phabricator.services.mozilla.com/D3436 --HG-- extra : moz-landing-system : lando
This commit is contained in:
Родитель
71e6a3af6b
Коммит
9b25fb8826
472
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/DESCRIPTION.rst
поставляемый
Normal file
472
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/DESCRIPTION.rst
поставляемый
Normal file
|
@ -0,0 +1,472 @@
|
|||
.. image:: https://img.shields.io/travis/giampaolo/psutil/master.svg?maxAge=3600&label=Linux%20/%20OSX
|
||||
:target: https://travis-ci.org/giampaolo/psutil
|
||||
:alt: Linux tests (Travis)
|
||||
|
||||
.. image:: https://img.shields.io/appveyor/ci/giampaolo/psutil/master.svg?maxAge=3600&label=Windows
|
||||
:target: https://ci.appveyor.com/project/giampaolo/psutil
|
||||
:alt: Windows tests (Appveyor)
|
||||
|
||||
.. image:: https://coveralls.io/repos/github/giampaolo/psutil/badge.svg?branch=master
|
||||
:target: https://coveralls.io/github/giampaolo/psutil?branch=master
|
||||
:alt: Test coverage (coverall.io)
|
||||
|
||||
.. image:: https://readthedocs.org/projects/psutil/badge/?version=latest
|
||||
:target: http://psutil.readthedocs.io/en/latest/?badge=latest
|
||||
:alt: Documentation Status
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/psutil.svg?label=pypi
|
||||
:target: https://pypi.python.org/pypi/psutil/
|
||||
:alt: Latest version
|
||||
|
||||
.. image:: https://img.shields.io/github/stars/giampaolo/psutil.svg
|
||||
:target: https://github.com/giampaolo/psutil/
|
||||
:alt: Github stars
|
||||
|
||||
.. image:: https://img.shields.io/pypi/l/psutil.svg
|
||||
:target: https://pypi.python.org/pypi/psutil/
|
||||
:alt: License
|
||||
|
||||
===========
|
||||
Quick links
|
||||
===========
|
||||
|
||||
- `Home page <https://github.com/giampaolo/psutil>`_
|
||||
- `Install <https://github.com/giampaolo/psutil/blob/master/INSTALL.rst>`_
|
||||
- `Documentation <http://psutil.readthedocs.io>`_
|
||||
- `Download <https://pypi.python.org/pypi?:action=display&name=psutil#downloads>`_
|
||||
- `Forum <http://groups.google.com/group/psutil/topics>`_
|
||||
- `Blog <http://grodola.blogspot.com/search/label/psutil>`_
|
||||
- `Development guide <https://github.com/giampaolo/psutil/blob/master/DEVGUIDE.rst>`_
|
||||
- `What's new <https://github.com/giampaolo/psutil/blob/master/HISTORY.rst>`_
|
||||
|
||||
=======
|
||||
Summary
|
||||
=======
|
||||
|
||||
psutil (process and system utilities) is a cross-platform library for
|
||||
retrieving information on **running processes** and **system utilization**
|
||||
(CPU, memory, disks, network, sensors) in Python.
|
||||
It is useful mainly for **system monitoring**, **profiling and limiting process
|
||||
resources** and **management of running processes**.
|
||||
It implements many functionalities offered by UNIX command line tools such as:
|
||||
ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat,
|
||||
iotop, uptime, pidof, tty, taskset, pmap.
|
||||
psutil currently supports the following platforms:
|
||||
|
||||
- **Linux**
|
||||
- **Windows**
|
||||
- **OSX**,
|
||||
- **FreeBSD, OpenBSD**, **NetBSD**
|
||||
- **Sun Solaris**
|
||||
- **AIX**
|
||||
|
||||
...both **32-bit** and **64-bit** architectures, with Python
|
||||
versions from **2.6 to 3.6**.
|
||||
`PyPy <http://pypy.org/>`__ is also known to work.
|
||||
|
||||
====================
|
||||
Example applications
|
||||
====================
|
||||
|
||||
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+
|
||||
| .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/procinfo-small.png | .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/top-small.png |
|
||||
| :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/procinfo.png | :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/top.png |
|
||||
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+
|
||||
| .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/procsmem-small.png | .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/pmap-small.png |
|
||||
| :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/procsmem.png | :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/pmap.png |
|
||||
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+
|
||||
|
||||
Also see `scripts directory <https://github.com/giampaolo/psutil/tree/master/scripts>`__
|
||||
and `doc recipes <http://psutil.readthedocs.io/#recipes/>`__.
|
||||
|
||||
=====================
|
||||
Projects using psutil
|
||||
=====================
|
||||
|
||||
At the time of writing psutil has roughly
|
||||
`2.9 milion downloads <https://github.com/giampaolo/psutil/issues/1053#issuecomment-340166262>`__
|
||||
per month and there are over
|
||||
`6000 open source projects <https://libraries.io/pypi/psutil/dependent_repositories?page=1>`__
|
||||
on github which depend from psutil.
|
||||
Here's some I find particularly interesting:
|
||||
|
||||
- https://github.com/facebook/osquery/
|
||||
- https://github.com/nicolargo/glances
|
||||
- https://github.com/google/grr
|
||||
- https://github.com/Jahaja/psdash
|
||||
- https://github.com/ajenti/ajenti
|
||||
- https://github.com/home-assistant/home-assistant/
|
||||
|
||||
========
|
||||
Portings
|
||||
========
|
||||
|
||||
- Go: https://github.com/shirou/gopsutil
|
||||
- C: https://github.com/hamon-in/cpslib
|
||||
- Node: https://github.com/christkv/node-psutil
|
||||
- Rust: https://github.com/borntyping/rust-psutil
|
||||
- Ruby: https://github.com/spacewander/posixpsutil
|
||||
- Nim: https://github.com/johnscillieri/psutil-nim
|
||||
|
||||
==============
|
||||
Example usages
|
||||
==============
|
||||
|
||||
CPU
|
||||
===
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.cpu_times()
|
||||
scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_percent(interval=1)
|
||||
...
|
||||
4.0
|
||||
5.9
|
||||
3.8
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_percent(interval=1, percpu=True)
|
||||
...
|
||||
[4.0, 6.9, 3.7, 9.2]
|
||||
[7.0, 8.5, 2.4, 2.1]
|
||||
[1.2, 9.0, 9.9, 7.2]
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_times_percent(interval=1, percpu=False)
|
||||
...
|
||||
scputimes(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)
|
||||
scputimes(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)
|
||||
scputimes(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)
|
||||
>>>
|
||||
>>> psutil.cpu_count()
|
||||
4
|
||||
>>> psutil.cpu_count(logical=False)
|
||||
2
|
||||
>>>
|
||||
>>> psutil.cpu_stats()
|
||||
scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0)
|
||||
>>>
|
||||
>>> psutil.cpu_freq()
|
||||
scpufreq(current=931.42925, min=800.0, max=3500.0)
|
||||
>>>
|
||||
|
||||
Memory
|
||||
======
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.virtual_memory()
|
||||
svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
|
||||
>>> psutil.swap_memory()
|
||||
sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)
|
||||
>>>
|
||||
|
||||
Disks
|
||||
=====
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.disk_partitions()
|
||||
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
|
||||
sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw')]
|
||||
>>>
|
||||
>>> psutil.disk_usage('/')
|
||||
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
|
||||
>>>
|
||||
>>> psutil.disk_io_counters(perdisk=False)
|
||||
sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568, read_merged_count=619166, write_merged_count=812396, busy_time=4523412)
|
||||
>>>
|
||||
|
||||
Network
|
||||
=======
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.net_io_counters(pernic=True)
|
||||
{'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0),
|
||||
'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}
|
||||
>>>
|
||||
>>> psutil.net_connections()
|
||||
[sconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254),
|
||||
sconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987),
|
||||
sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED', pid=None),
|
||||
sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT', pid=None)
|
||||
...]
|
||||
>>>
|
||||
>>> psutil.net_if_addrs()
|
||||
{'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
|
||||
snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
|
||||
snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
|
||||
'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
|
||||
snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
|
||||
snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
|
||||
>>>
|
||||
>>> psutil.net_if_stats()
|
||||
{'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
|
||||
'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536)}
|
||||
>>>
|
||||
|
||||
Sensors
|
||||
=======
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.sensors_temperatures()
|
||||
{'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)],
|
||||
'asus': [shwtemp(label='', current=47.0, high=None, critical=None)],
|
||||
'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 1', current=52.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 2', current=45.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 3', current=47.0, high=100.0, critical=100.0)]}
|
||||
>>>
|
||||
>>> psutil.sensors_fans()
|
||||
{'asus': [sfan(label='cpu_fan', current=3200)]}
|
||||
>>>
|
||||
>>> psutil.sensors_battery()
|
||||
sbattery(percent=93, secsleft=16628, power_plugged=False)
|
||||
>>>
|
||||
|
||||
Other system info
|
||||
=================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.users()
|
||||
[suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352),
|
||||
suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]
|
||||
>>>
|
||||
>>> psutil.boot_time()
|
||||
1365519115.0
|
||||
>>>
|
||||
|
||||
Process management
|
||||
==================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.pids()
|
||||
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215, 1216, 1220, 1221, 1243, 1244,
|
||||
1301, 1601, 2237, 2355, 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282,
|
||||
4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446,
|
||||
5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
|
||||
>>>
|
||||
>>> p = psutil.Process(7055)
|
||||
>>> p.name()
|
||||
'python'
|
||||
>>> p.exe()
|
||||
'/usr/bin/python'
|
||||
>>> p.cwd()
|
||||
'/home/giampaolo'
|
||||
>>> p.cmdline()
|
||||
['/usr/bin/python', 'main.py']
|
||||
>>>
|
||||
>>> p.pid
|
||||
7055
|
||||
>>> p.ppid()
|
||||
7054
|
||||
>>> p.parent()
|
||||
<psutil.Process(pid=7054, name='bash') at 140008329539408>
|
||||
>>> p.children()
|
||||
[<psutil.Process(pid=8031, name='python') at 14020832451977>,
|
||||
<psutil.Process(pid=8044, name='python') at 19229444921932>]
|
||||
>>>
|
||||
>>> p.status()
|
||||
'running'
|
||||
>>> p.username()
|
||||
'giampaolo'
|
||||
>>> p.create_time()
|
||||
1267551141.5019531
|
||||
>>> p.terminal()
|
||||
'/dev/pts/0'
|
||||
>>>
|
||||
>>> p.uids()
|
||||
puids(real=1000, effective=1000, saved=1000)
|
||||
>>> p.gids()
|
||||
pgids(real=1000, effective=1000, saved=1000)
|
||||
>>>
|
||||
>>> p.cpu_times()
|
||||
pcputimes(user=1.02, system=0.31, children_user=0.32, children_system=0.1)
|
||||
>>> p.cpu_percent(interval=1.0)
|
||||
12.1
|
||||
>>> p.cpu_affinity()
|
||||
[0, 1, 2, 3]
|
||||
>>> p.cpu_affinity([0, 1]) # set
|
||||
>>> p.cpu_num()
|
||||
1
|
||||
>>>
|
||||
>>> p.memory_info()
|
||||
pmem(rss=10915840, vms=67608576, shared=3313664, text=2310144, lib=0, data=7262208, dirty=0)
|
||||
>>> p.memory_full_info() # "real" USS memory usage (Linux, OSX, Win only)
|
||||
pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0)
|
||||
>>> p.memory_percent()
|
||||
0.7823
|
||||
>>> p.memory_maps()
|
||||
[pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0),
|
||||
pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0),
|
||||
pmmap_grouped(path='/lib/x8664-linux-gnu/libcrypto.so.0.1', rss=34124, rss=32768, size=2134016, pss=15360, shared_clean=24576, shared_dirty=0, private_clean=0, private_dirty=8192, referenced=24576, anonymous=8192, swap=0),
|
||||
pmmap_grouped(path='[heap]', rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0),
|
||||
pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0),
|
||||
...]
|
||||
>>>
|
||||
>>> p.io_counters()
|
||||
pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632, read_chars=456232, write_chars=517543)
|
||||
>>>
|
||||
>>> p.open_files()
|
||||
[popenfile(path='/home/giampaolo/svn/psutil/setup.py', fd=3, position=0, mode='r', flags=32768),
|
||||
popenfile(path='/var/log/monitd', fd=4, position=235542, mode='a', flags=33793)]
|
||||
>>>
|
||||
>>> p.connections()
|
||||
[pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'),
|
||||
pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING'),
|
||||
pconn(fd=119, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED'),
|
||||
pconn(fd=123, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT')]
|
||||
>>>
|
||||
>>> p.num_threads()
|
||||
4
|
||||
>>> p.num_fds()
|
||||
8
|
||||
>>> p.threads()
|
||||
[pthread(id=5234, user_time=22.5, system_time=9.2891),
|
||||
pthread(id=5235, user_time=0.0, system_time=0.0),
|
||||
pthread(id=5236, user_time=0.0, system_time=0.0),
|
||||
pthread(id=5237, user_time=0.0707, system_time=1.1)]
|
||||
>>>
|
||||
>>> p.num_ctx_switches()
|
||||
pctxsw(voluntary=78, involuntary=19)
|
||||
>>>
|
||||
>>> p.nice()
|
||||
0
|
||||
>>> p.nice(10) # set
|
||||
>>>
|
||||
>>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only)
|
||||
>>> p.ionice()
|
||||
pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: 3>, value=0)
|
||||
>>>
|
||||
>>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) # set resource limits (Linux only)
|
||||
>>> p.rlimit(psutil.RLIMIT_NOFILE)
|
||||
(5, 5)
|
||||
>>>
|
||||
>>> p.environ()
|
||||
{'LC_PAPER': 'it_IT.UTF-8', 'SHELL': '/bin/bash', 'GREP_OPTIONS': '--color=auto',
|
||||
'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg', 'COLORTERM': 'gnome-terminal',
|
||||
...}
|
||||
>>>
|
||||
>>> p.as_dict()
|
||||
{'status': 'running', 'num_ctx_switches': pctxsw(voluntary=63, involuntary=1), 'pid': 5457, ...}
|
||||
>>> p.is_running()
|
||||
True
|
||||
>>> p.suspend()
|
||||
>>> p.resume()
|
||||
>>>
|
||||
>>> p.terminate()
|
||||
>>> p.wait(timeout=3)
|
||||
0
|
||||
>>>
|
||||
>>> psutil.test()
|
||||
USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
|
||||
root 1 0.0 0.0 24584 2240 Jun17 00:00 init
|
||||
root 2 0.0 0.0 0 0 Jun17 00:00 kthreadd
|
||||
root 3 0.0 0.0 0 0 Jun17 00:05 ksoftirqd/0
|
||||
...
|
||||
giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4
|
||||
giampaolo 31721 0.0 2.2 773060 181896 00:04 10:30 chrome
|
||||
root 31763 0.0 0.0 0 0 00:05 00:00 kworker/0:1
|
||||
>>>
|
||||
|
||||
Further process APIs
|
||||
====================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> for proc in psutil.process_iter(attrs=['pid', 'name']):
|
||||
... print(proc.info)
|
||||
...
|
||||
{'pid': 1, 'name': 'systemd'}
|
||||
{'pid': 2, 'name': 'kthreadd'}
|
||||
{'pid': 3, 'name': 'ksoftirqd/0'}
|
||||
...
|
||||
>>>
|
||||
>>> psutil.pid_exists(3)
|
||||
True
|
||||
>>>
|
||||
>>> def on_terminate(proc):
|
||||
... print("process {} terminated".format(proc))
|
||||
...
|
||||
>>> # waits for multiple processes to terminate
|
||||
>>> gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
|
||||
>>>
|
||||
|
||||
Popen wrapper:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> from subprocess import PIPE
|
||||
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)
|
||||
>>> p.name()
|
||||
'python'
|
||||
>>> p.username()
|
||||
'giampaolo'
|
||||
>>> p.communicate()
|
||||
('hello\n', None)
|
||||
>>> p.wait(timeout=2)
|
||||
0
|
||||
>>>
|
||||
|
||||
Windows services
|
||||
================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> list(psutil.win_service_iter())
|
||||
[<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>,
|
||||
<WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>,
|
||||
<WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>,
|
||||
<WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>,
|
||||
...]
|
||||
>>> s = psutil.win_service_get('alg')
|
||||
>>> s.as_dict()
|
||||
{'binpath': 'C:\\Windows\\System32\\alg.exe',
|
||||
'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
|
||||
'display_name': 'Application Layer Gateway Service',
|
||||
'name': 'alg',
|
||||
'pid': None,
|
||||
'start_type': 'manual',
|
||||
'status': 'stopped',
|
||||
'username': 'NT AUTHORITY\\LocalService'}
|
||||
|
||||
Other samples
|
||||
=============
|
||||
|
||||
See `doc recipes <http://psutil.readthedocs.io/#recipes>`__.
|
||||
|
||||
======
|
||||
Author
|
||||
======
|
||||
|
||||
psutil was created and is maintained by
|
||||
`Giampaolo Rodola' <http://grodola.blogspot.com/p/about.html>`__.
|
||||
A lot of time and effort went into making psutil as it is right now.
|
||||
If you feel psutil is useful to you or your business and want to support its
|
||||
future development please consider donating me
|
||||
(`Giampaolo <http://grodola.blogspot.com/p/about.html>`__) some money.
|
||||
|
||||
.. image:: http://www.paypal.com/en_US/i/btn/x-click-but04.gif
|
||||
:target: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=A9ZS7PKKRM3S8
|
||||
:alt: Donate via PayPal
|
||||
|
||||
Don't want to donate money? Then maybe you could `write me a recommendation on Linkedin <https://www.linkedin.com/in/grodola>`_.
|
||||
|
||||
|
524
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/METADATA
поставляемый
Normal file
524
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/METADATA
поставляемый
Normal file
|
@ -0,0 +1,524 @@
|
|||
Metadata-Version: 2.0
|
||||
Name: psutil
|
||||
Version: 5.4.3
|
||||
Summary: Cross-platform lib for process and system monitoring in Python.
|
||||
Home-page: https://github.com/giampaolo/psutil
|
||||
Author: Giampaolo Rodola
|
||||
Author-email: g.rodola@gmail.com
|
||||
License: BSD
|
||||
Keywords: ps,top,kill,free,lsof,netstat,nice,tty,ionice,uptime,taskmgr,process,df,iotop,iostat,ifconfig,taskset,who,pidof,pmap,smem,pstree,monitoring,ulimit,prlimit,smem
|
||||
Platform: Platform Independent
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Environment :: Console
|
||||
Classifier: Environment :: Win32 (MS Windows)
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Intended Audience :: Information Technology
|
||||
Classifier: Intended Audience :: System Administrators
|
||||
Classifier: License :: OSI Approved :: BSD License
|
||||
Classifier: Operating System :: MacOS :: MacOS X
|
||||
Classifier: Operating System :: Microsoft :: Windows :: Windows NT/2000
|
||||
Classifier: Operating System :: Microsoft
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Operating System :: POSIX :: BSD :: FreeBSD
|
||||
Classifier: Operating System :: POSIX :: BSD :: NetBSD
|
||||
Classifier: Operating System :: POSIX :: BSD :: OpenBSD
|
||||
Classifier: Operating System :: POSIX :: BSD
|
||||
Classifier: Operating System :: POSIX :: Linux
|
||||
Classifier: Operating System :: POSIX :: SunOS/Solaris
|
||||
Classifier: Operating System :: POSIX
|
||||
Classifier: Programming Language :: C
|
||||
Classifier: Programming Language :: Python :: 2
|
||||
Classifier: Programming Language :: Python :: 2.6
|
||||
Classifier: Programming Language :: Python :: 2.7
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.4
|
||||
Classifier: Programming Language :: Python :: 3.5
|
||||
Classifier: Programming Language :: Python :: 3.6
|
||||
Classifier: Programming Language :: Python :: Implementation :: CPython
|
||||
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
||||
Classifier: Programming Language :: Python
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Classifier: Topic :: Software Development :: Libraries
|
||||
Classifier: Topic :: System :: Benchmark
|
||||
Classifier: Topic :: System :: Hardware
|
||||
Classifier: Topic :: System :: Monitoring
|
||||
Classifier: Topic :: System :: Networking :: Monitoring
|
||||
Classifier: Topic :: System :: Networking
|
||||
Classifier: Topic :: System :: Operating System
|
||||
Classifier: Topic :: System :: Systems Administration
|
||||
Classifier: Topic :: Utilities
|
||||
Provides-Extra: enum
|
||||
Requires-Dist: enum34; extra == 'enum'
|
||||
|
||||
.. image:: https://img.shields.io/travis/giampaolo/psutil/master.svg?maxAge=3600&label=Linux%20/%20OSX
|
||||
:target: https://travis-ci.org/giampaolo/psutil
|
||||
:alt: Linux tests (Travis)
|
||||
|
||||
.. image:: https://img.shields.io/appveyor/ci/giampaolo/psutil/master.svg?maxAge=3600&label=Windows
|
||||
:target: https://ci.appveyor.com/project/giampaolo/psutil
|
||||
:alt: Windows tests (Appveyor)
|
||||
|
||||
.. image:: https://coveralls.io/repos/github/giampaolo/psutil/badge.svg?branch=master
|
||||
:target: https://coveralls.io/github/giampaolo/psutil?branch=master
|
||||
:alt: Test coverage (coverall.io)
|
||||
|
||||
.. image:: https://readthedocs.org/projects/psutil/badge/?version=latest
|
||||
:target: http://psutil.readthedocs.io/en/latest/?badge=latest
|
||||
:alt: Documentation Status
|
||||
|
||||
.. image:: https://img.shields.io/pypi/v/psutil.svg?label=pypi
|
||||
:target: https://pypi.python.org/pypi/psutil/
|
||||
:alt: Latest version
|
||||
|
||||
.. image:: https://img.shields.io/github/stars/giampaolo/psutil.svg
|
||||
:target: https://github.com/giampaolo/psutil/
|
||||
:alt: Github stars
|
||||
|
||||
.. image:: https://img.shields.io/pypi/l/psutil.svg
|
||||
:target: https://pypi.python.org/pypi/psutil/
|
||||
:alt: License
|
||||
|
||||
===========
|
||||
Quick links
|
||||
===========
|
||||
|
||||
- `Home page <https://github.com/giampaolo/psutil>`_
|
||||
- `Install <https://github.com/giampaolo/psutil/blob/master/INSTALL.rst>`_
|
||||
- `Documentation <http://psutil.readthedocs.io>`_
|
||||
- `Download <https://pypi.python.org/pypi?:action=display&name=psutil#downloads>`_
|
||||
- `Forum <http://groups.google.com/group/psutil/topics>`_
|
||||
- `Blog <http://grodola.blogspot.com/search/label/psutil>`_
|
||||
- `Development guide <https://github.com/giampaolo/psutil/blob/master/DEVGUIDE.rst>`_
|
||||
- `What's new <https://github.com/giampaolo/psutil/blob/master/HISTORY.rst>`_
|
||||
|
||||
=======
|
||||
Summary
|
||||
=======
|
||||
|
||||
psutil (process and system utilities) is a cross-platform library for
|
||||
retrieving information on **running processes** and **system utilization**
|
||||
(CPU, memory, disks, network, sensors) in Python.
|
||||
It is useful mainly for **system monitoring**, **profiling and limiting process
|
||||
resources** and **management of running processes**.
|
||||
It implements many functionalities offered by UNIX command line tools such as:
|
||||
ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat,
|
||||
iotop, uptime, pidof, tty, taskset, pmap.
|
||||
psutil currently supports the following platforms:
|
||||
|
||||
- **Linux**
|
||||
- **Windows**
|
||||
- **OSX**,
|
||||
- **FreeBSD, OpenBSD**, **NetBSD**
|
||||
- **Sun Solaris**
|
||||
- **AIX**
|
||||
|
||||
...both **32-bit** and **64-bit** architectures, with Python
|
||||
versions from **2.6 to 3.6**.
|
||||
`PyPy <http://pypy.org/>`__ is also known to work.
|
||||
|
||||
====================
|
||||
Example applications
|
||||
====================
|
||||
|
||||
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+
|
||||
| .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/procinfo-small.png | .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/top-small.png |
|
||||
| :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/procinfo.png | :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/top.png |
|
||||
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+
|
||||
| .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/procsmem-small.png | .. image:: https://github.com/giampaolo/psutil/blob/master/docs/_static/pmap-small.png |
|
||||
| :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/procsmem.png | :target: https://github.com/giampaolo/psutil/blob/master/docs/_static/pmap.png |
|
||||
+------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------+
|
||||
|
||||
Also see `scripts directory <https://github.com/giampaolo/psutil/tree/master/scripts>`__
|
||||
and `doc recipes <http://psutil.readthedocs.io/#recipes/>`__.
|
||||
|
||||
=====================
|
||||
Projects using psutil
|
||||
=====================
|
||||
|
||||
At the time of writing psutil has roughly
|
||||
`2.9 milion downloads <https://github.com/giampaolo/psutil/issues/1053#issuecomment-340166262>`__
|
||||
per month and there are over
|
||||
`6000 open source projects <https://libraries.io/pypi/psutil/dependent_repositories?page=1>`__
|
||||
on github which depend from psutil.
|
||||
Here's some I find particularly interesting:
|
||||
|
||||
- https://github.com/facebook/osquery/
|
||||
- https://github.com/nicolargo/glances
|
||||
- https://github.com/google/grr
|
||||
- https://github.com/Jahaja/psdash
|
||||
- https://github.com/ajenti/ajenti
|
||||
- https://github.com/home-assistant/home-assistant/
|
||||
|
||||
========
|
||||
Portings
|
||||
========
|
||||
|
||||
- Go: https://github.com/shirou/gopsutil
|
||||
- C: https://github.com/hamon-in/cpslib
|
||||
- Node: https://github.com/christkv/node-psutil
|
||||
- Rust: https://github.com/borntyping/rust-psutil
|
||||
- Ruby: https://github.com/spacewander/posixpsutil
|
||||
- Nim: https://github.com/johnscillieri/psutil-nim
|
||||
|
||||
==============
|
||||
Example usages
|
||||
==============
|
||||
|
||||
CPU
|
||||
===
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.cpu_times()
|
||||
scputimes(user=3961.46, nice=169.729, system=2150.659, idle=16900.540, iowait=629.59, irq=0.0, softirq=19.42, steal=0.0, guest=0, nice=0.0)
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_percent(interval=1)
|
||||
...
|
||||
4.0
|
||||
5.9
|
||||
3.8
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_percent(interval=1, percpu=True)
|
||||
...
|
||||
[4.0, 6.9, 3.7, 9.2]
|
||||
[7.0, 8.5, 2.4, 2.1]
|
||||
[1.2, 9.0, 9.9, 7.2]
|
||||
>>>
|
||||
>>> for x in range(3):
|
||||
... psutil.cpu_times_percent(interval=1, percpu=False)
|
||||
...
|
||||
scputimes(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)
|
||||
scputimes(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)
|
||||
scputimes(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)
|
||||
>>>
|
||||
>>> psutil.cpu_count()
|
||||
4
|
||||
>>> psutil.cpu_count(logical=False)
|
||||
2
|
||||
>>>
|
||||
>>> psutil.cpu_stats()
|
||||
scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0)
|
||||
>>>
|
||||
>>> psutil.cpu_freq()
|
||||
scpufreq(current=931.42925, min=800.0, max=3500.0)
|
||||
>>>
|
||||
|
||||
Memory
|
||||
======
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.virtual_memory()
|
||||
svmem(total=10367352832, available=6472179712, percent=37.6, used=8186245120, free=2181107712, active=4748992512, inactive=2758115328, buffers=790724608, cached=3500347392, shared=787554304)
|
||||
>>> psutil.swap_memory()
|
||||
sswap(total=2097147904, used=296128512, free=1801019392, percent=14.1, sin=304193536, sout=677842944)
|
||||
>>>
|
||||
|
||||
Disks
|
||||
=====
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.disk_partitions()
|
||||
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
|
||||
sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext, opts='rw')]
|
||||
>>>
|
||||
>>> psutil.disk_usage('/')
|
||||
sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
|
||||
>>>
|
||||
>>> psutil.disk_io_counters(perdisk=False)
|
||||
sdiskio(read_count=719566, write_count=1082197, read_bytes=18626220032, write_bytes=24081764352, read_time=5023392, write_time=63199568, read_merged_count=619166, write_merged_count=812396, busy_time=4523412)
|
||||
>>>
|
||||
|
||||
Network
|
||||
=======
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.net_io_counters(pernic=True)
|
||||
{'eth0': netio(bytes_sent=485291293, bytes_recv=6004858642, packets_sent=3251564, packets_recv=4787798, errin=0, errout=0, dropin=0, dropout=0),
|
||||
'lo': netio(bytes_sent=2838627, bytes_recv=2838627, packets_sent=30567, packets_recv=30567, errin=0, errout=0, dropin=0, dropout=0)}
|
||||
>>>
|
||||
>>> psutil.net_connections()
|
||||
[sconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED', pid=1254),
|
||||
sconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING', pid=2987),
|
||||
sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED', pid=None),
|
||||
sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT', pid=None)
|
||||
...]
|
||||
>>>
|
||||
>>> psutil.net_if_addrs()
|
||||
{'lo': [snic(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast='127.0.0.1', ptp=None),
|
||||
snic(family=<AddressFamily.AF_INET6: 10>, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None),
|
||||
snic(family=<AddressFamily.AF_LINK: 17>, address='00:00:00:00:00:00', netmask=None, broadcast='00:00:00:00:00:00', ptp=None)],
|
||||
'wlan0': [snic(family=<AddressFamily.AF_INET: 2>, address='192.168.1.3', netmask='255.255.255.0', broadcast='192.168.1.255', ptp=None),
|
||||
snic(family=<AddressFamily.AF_INET6: 10>, address='fe80::c685:8ff:fe45:641%wlan0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None),
|
||||
snic(family=<AddressFamily.AF_LINK: 17>, address='c4:85:08:45:06:41', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
|
||||
>>>
|
||||
>>> psutil.net_if_stats()
|
||||
{'eth0': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
|
||||
'lo': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=65536)}
|
||||
>>>
|
||||
|
||||
Sensors
|
||||
=======
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.sensors_temperatures()
|
||||
{'acpitz': [shwtemp(label='', current=47.0, high=103.0, critical=103.0)],
|
||||
'asus': [shwtemp(label='', current=47.0, high=None, critical=None)],
|
||||
'coretemp': [shwtemp(label='Physical id 0', current=52.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 0', current=45.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 1', current=52.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 2', current=45.0, high=100.0, critical=100.0),
|
||||
shwtemp(label='Core 3', current=47.0, high=100.0, critical=100.0)]}
|
||||
>>>
|
||||
>>> psutil.sensors_fans()
|
||||
{'asus': [sfan(label='cpu_fan', current=3200)]}
|
||||
>>>
|
||||
>>> psutil.sensors_battery()
|
||||
sbattery(percent=93, secsleft=16628, power_plugged=False)
|
||||
>>>
|
||||
|
||||
Other system info
|
||||
=================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.users()
|
||||
[suser(name='giampaolo', terminal='pts/2', host='localhost', started=1340737536.0, pid=1352),
|
||||
suser(name='giampaolo', terminal='pts/3', host='localhost', started=1340737792.0, pid=1788)]
|
||||
>>>
|
||||
>>> psutil.boot_time()
|
||||
1365519115.0
|
||||
>>>
|
||||
|
||||
Process management
|
||||
==================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> psutil.pids()
|
||||
[1, 2, 3, 4, 5, 6, 7, 46, 48, 50, 51, 178, 182, 222, 223, 224, 268, 1215, 1216, 1220, 1221, 1243, 1244,
|
||||
1301, 1601, 2237, 2355, 2637, 2774, 3932, 4176, 4177, 4185, 4187, 4189, 4225, 4243, 4245, 4263, 4282,
|
||||
4306, 4311, 4312, 4313, 4314, 4337, 4339, 4357, 4358, 4363, 4383, 4395, 4408, 4433, 4443, 4445, 4446,
|
||||
5167, 5234, 5235, 5252, 5318, 5424, 5644, 6987, 7054, 7055, 7071]
|
||||
>>>
|
||||
>>> p = psutil.Process(7055)
|
||||
>>> p.name()
|
||||
'python'
|
||||
>>> p.exe()
|
||||
'/usr/bin/python'
|
||||
>>> p.cwd()
|
||||
'/home/giampaolo'
|
||||
>>> p.cmdline()
|
||||
['/usr/bin/python', 'main.py']
|
||||
>>>
|
||||
>>> p.pid
|
||||
7055
|
||||
>>> p.ppid()
|
||||
7054
|
||||
>>> p.parent()
|
||||
<psutil.Process(pid=7054, name='bash') at 140008329539408>
|
||||
>>> p.children()
|
||||
[<psutil.Process(pid=8031, name='python') at 14020832451977>,
|
||||
<psutil.Process(pid=8044, name='python') at 19229444921932>]
|
||||
>>>
|
||||
>>> p.status()
|
||||
'running'
|
||||
>>> p.username()
|
||||
'giampaolo'
|
||||
>>> p.create_time()
|
||||
1267551141.5019531
|
||||
>>> p.terminal()
|
||||
'/dev/pts/0'
|
||||
>>>
|
||||
>>> p.uids()
|
||||
puids(real=1000, effective=1000, saved=1000)
|
||||
>>> p.gids()
|
||||
pgids(real=1000, effective=1000, saved=1000)
|
||||
>>>
|
||||
>>> p.cpu_times()
|
||||
pcputimes(user=1.02, system=0.31, children_user=0.32, children_system=0.1)
|
||||
>>> p.cpu_percent(interval=1.0)
|
||||
12.1
|
||||
>>> p.cpu_affinity()
|
||||
[0, 1, 2, 3]
|
||||
>>> p.cpu_affinity([0, 1]) # set
|
||||
>>> p.cpu_num()
|
||||
1
|
||||
>>>
|
||||
>>> p.memory_info()
|
||||
pmem(rss=10915840, vms=67608576, shared=3313664, text=2310144, lib=0, data=7262208, dirty=0)
|
||||
>>> p.memory_full_info() # "real" USS memory usage (Linux, OSX, Win only)
|
||||
pfullmem(rss=10199040, vms=52133888, shared=3887104, text=2867200, lib=0, data=5967872, dirty=0, uss=6545408, pss=6872064, swap=0)
|
||||
>>> p.memory_percent()
|
||||
0.7823
|
||||
>>> p.memory_maps()
|
||||
[pmmap_grouped(path='/lib/x8664-linux-gnu/libutil-2.15.so', rss=32768, size=2125824, pss=32768, shared_clean=0, shared_dirty=0, private_clean=20480, private_dirty=12288, referenced=32768, anonymous=12288, swap=0),
|
||||
pmmap_grouped(path='/lib/x8664-linux-gnu/libc-2.15.so', rss=3821568, size=3842048, pss=3821568, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=3821568, referenced=3575808, anonymous=3821568, swap=0),
|
||||
pmmap_grouped(path='/lib/x8664-linux-gnu/libcrypto.so.0.1', rss=34124, rss=32768, size=2134016, pss=15360, shared_clean=24576, shared_dirty=0, private_clean=0, private_dirty=8192, referenced=24576, anonymous=8192, swap=0),
|
||||
pmmap_grouped(path='[heap]', rss=32768, size=139264, pss=32768, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=32768, referenced=32768, anonymous=32768, swap=0),
|
||||
pmmap_grouped(path='[stack]', rss=2465792, size=2494464, pss=2465792, shared_clean=0, shared_dirty=0, private_clean=0, private_dirty=2465792, referenced=2277376, anonymous=2465792, swap=0),
|
||||
...]
|
||||
>>>
|
||||
>>> p.io_counters()
|
||||
pio(read_count=478001, write_count=59371, read_bytes=700416, write_bytes=69632, read_chars=456232, write_chars=517543)
|
||||
>>>
|
||||
>>> p.open_files()
|
||||
[popenfile(path='/home/giampaolo/svn/psutil/setup.py', fd=3, position=0, mode='r', flags=32768),
|
||||
popenfile(path='/var/log/monitd', fd=4, position=235542, mode='a', flags=33793)]
|
||||
>>>
|
||||
>>> p.connections()
|
||||
[pconn(fd=115, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=48776), raddr=addr(ip='93.186.135.91', port=80), status='ESTABLISHED'),
|
||||
pconn(fd=117, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=43761), raddr=addr(ip='72.14.234.100', port=80), status='CLOSING'),
|
||||
pconn(fd=119, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=60759), raddr=addr(ip='72.14.234.104', port=80), status='ESTABLISHED'),
|
||||
pconn(fd=123, family=<AddressFamily.AF_INET: 2>, type=<SocketType.SOCK_STREAM: 1>, laddr=addr(ip='10.0.0.1', port=51314), raddr=addr(ip='72.14.234.83', port=443), status='SYN_SENT')]
|
||||
>>>
|
||||
>>> p.num_threads()
|
||||
4
|
||||
>>> p.num_fds()
|
||||
8
|
||||
>>> p.threads()
|
||||
[pthread(id=5234, user_time=22.5, system_time=9.2891),
|
||||
pthread(id=5235, user_time=0.0, system_time=0.0),
|
||||
pthread(id=5236, user_time=0.0, system_time=0.0),
|
||||
pthread(id=5237, user_time=0.0707, system_time=1.1)]
|
||||
>>>
|
||||
>>> p.num_ctx_switches()
|
||||
pctxsw(voluntary=78, involuntary=19)
|
||||
>>>
|
||||
>>> p.nice()
|
||||
0
|
||||
>>> p.nice(10) # set
|
||||
>>>
|
||||
>>> p.ionice(psutil.IOPRIO_CLASS_IDLE) # IO priority (Win and Linux only)
|
||||
>>> p.ionice()
|
||||
pionice(ioclass=<IOPriority.IOPRIO_CLASS_IDLE: 3>, value=0)
|
||||
>>>
|
||||
>>> p.rlimit(psutil.RLIMIT_NOFILE, (5, 5)) # set resource limits (Linux only)
|
||||
>>> p.rlimit(psutil.RLIMIT_NOFILE)
|
||||
(5, 5)
|
||||
>>>
|
||||
>>> p.environ()
|
||||
{'LC_PAPER': 'it_IT.UTF-8', 'SHELL': '/bin/bash', 'GREP_OPTIONS': '--color=auto',
|
||||
'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/usr/share/upstart/xdg:/etc/xdg', 'COLORTERM': 'gnome-terminal',
|
||||
...}
|
||||
>>>
|
||||
>>> p.as_dict()
|
||||
{'status': 'running', 'num_ctx_switches': pctxsw(voluntary=63, involuntary=1), 'pid': 5457, ...}
|
||||
>>> p.is_running()
|
||||
True
|
||||
>>> p.suspend()
|
||||
>>> p.resume()
|
||||
>>>
|
||||
>>> p.terminate()
|
||||
>>> p.wait(timeout=3)
|
||||
0
|
||||
>>>
|
||||
>>> psutil.test()
|
||||
USER PID %CPU %MEM VSZ RSS TTY START TIME COMMAND
|
||||
root 1 0.0 0.0 24584 2240 Jun17 00:00 init
|
||||
root 2 0.0 0.0 0 0 Jun17 00:00 kthreadd
|
||||
root 3 0.0 0.0 0 0 Jun17 00:05 ksoftirqd/0
|
||||
...
|
||||
giampaolo 31475 0.0 0.0 20760 3024 /dev/pts/0 Jun19 00:00 python2.4
|
||||
giampaolo 31721 0.0 2.2 773060 181896 00:04 10:30 chrome
|
||||
root 31763 0.0 0.0 0 0 00:05 00:00 kworker/0:1
|
||||
>>>
|
||||
|
||||
Further process APIs
|
||||
====================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> for proc in psutil.process_iter(attrs=['pid', 'name']):
|
||||
... print(proc.info)
|
||||
...
|
||||
{'pid': 1, 'name': 'systemd'}
|
||||
{'pid': 2, 'name': 'kthreadd'}
|
||||
{'pid': 3, 'name': 'ksoftirqd/0'}
|
||||
...
|
||||
>>>
|
||||
>>> psutil.pid_exists(3)
|
||||
True
|
||||
>>>
|
||||
>>> def on_terminate(proc):
|
||||
... print("process {} terminated".format(proc))
|
||||
...
|
||||
>>> # waits for multiple processes to terminate
|
||||
>>> gone, alive = psutil.wait_procs(procs_list, timeout=3, callback=on_terminate)
|
||||
>>>
|
||||
|
||||
Popen wrapper:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> import psutil
|
||||
>>> from subprocess import PIPE
|
||||
>>> p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"], stdout=PIPE)
|
||||
>>> p.name()
|
||||
'python'
|
||||
>>> p.username()
|
||||
'giampaolo'
|
||||
>>> p.communicate()
|
||||
('hello\n', None)
|
||||
>>> p.wait(timeout=2)
|
||||
0
|
||||
>>>
|
||||
|
||||
Windows services
|
||||
================
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
>>> list(psutil.win_service_iter())
|
||||
[<WindowsService(name='AeLookupSvc', display_name='Application Experience') at 38850096>,
|
||||
<WindowsService(name='ALG', display_name='Application Layer Gateway Service') at 38850128>,
|
||||
<WindowsService(name='APNMCP', display_name='Ask Update Service') at 38850160>,
|
||||
<WindowsService(name='AppIDSvc', display_name='Application Identity') at 38850192>,
|
||||
...]
|
||||
>>> s = psutil.win_service_get('alg')
|
||||
>>> s.as_dict()
|
||||
{'binpath': 'C:\\Windows\\System32\\alg.exe',
|
||||
'description': 'Provides support for 3rd party protocol plug-ins for Internet Connection Sharing',
|
||||
'display_name': 'Application Layer Gateway Service',
|
||||
'name': 'alg',
|
||||
'pid': None,
|
||||
'start_type': 'manual',
|
||||
'status': 'stopped',
|
||||
'username': 'NT AUTHORITY\\LocalService'}
|
||||
|
||||
Other samples
|
||||
=============
|
||||
|
||||
See `doc recipes <http://psutil.readthedocs.io/#recipes>`__.
|
||||
|
||||
======
|
||||
Author
|
||||
======
|
||||
|
||||
psutil was created and is maintained by
|
||||
`Giampaolo Rodola' <http://grodola.blogspot.com/p/about.html>`__.
|
||||
A lot of time and effort went into making psutil as it is right now.
|
||||
If you feel psutil is useful to you or your business and want to support its
|
||||
future development please consider donating me
|
||||
(`Giampaolo <http://grodola.blogspot.com/p/about.html>`__) some money.
|
||||
|
||||
.. image:: http://www.paypal.com/en_US/i/btn/x-click-but04.gif
|
||||
:target: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=A9ZS7PKKRM3S8
|
||||
:alt: Donate via PayPal
|
||||
|
||||
Don't want to donate money? Then maybe you could `write me a recommendation on Linkedin <https://www.linkedin.com/in/grodola>`_.
|
||||
|
||||
|
34
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/RECORD
поставляемый
Normal file
34
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/RECORD
поставляемый
Normal file
|
@ -0,0 +1,34 @@
|
|||
psutil/__init__.py,sha256=220_B4k7vC9eoVP_OW8SFcaXCSBGpj_nacxvfBQ5O2o,84989
|
||||
psutil/_common.py,sha256=df5J2HqrWvGoFdumxDL1q9fgJOOYyiCmV0EFxb4ghuY,17852
|
||||
psutil/_compat.py,sha256=0VqlfcCGD5tZRBW-mFroguS0J7YNw6y3LjEcX5ChXDc,8170
|
||||
psutil/_exceptions.py,sha256=37eRgLuwTy7X4tjovePfZfYif-veW6LFeRlPqsgnNBU,3009
|
||||
psutil/_psaix.py,sha256=uAqwhQHS0upGc8OIk8Qa5PScCwXNvaMkoIdltZZ0n8A,19376
|
||||
psutil/_psbsd.py,sha256=ewmj2_DfzZpQZEcRvo1xvjVFhQqJidnENLgS8jrBb68,30244
|
||||
psutil/_pslinux.py,sha256=ME3wEgxfOWSFxgKXpTKbFw29ur1toMT4DdkKLJGkaD4,74850
|
||||
psutil/_psosx.py,sha256=X2WzhpuGjffjzFt3B3hphX7piPRCrPsjJrk6p6vu96w,17213
|
||||
psutil/_psposix.py,sha256=AmpZmKnvzCFcf7RpYypiUxOxKoRdXHRy2p9hFEIAJVc,6345
|
||||
psutil/_pssunos.py,sha256=uEsntvZPXplCuP9ER2W1QaGXjOqUZx_qFx2iLeyc5V8,25650
|
||||
psutil/_psutil_windows.pyd,sha256=wbQ_dSXTvdmCyQV02P7uCk95MwDkZ_D1g5r4G7IiYr8,59904
|
||||
psutil/_pswindows.py,sha256=_KYB-Vyhnz2A3l8I7tuXvFSrBPqKIb9slcwh5Azj0QU,33121
|
||||
psutil/tests/__init__.py,sha256=hkGHtLQNHjKrqhuV3Sk0kkHir17Mlam-amZBkLdfGwA,37656
|
||||
psutil/tests/__main__.py,sha256=dssAzXI-sAHkObtruDvc1cYUFNWOi-ZXETQgwaLKJS0,2784
|
||||
psutil/tests/test_aix.py,sha256=_ItFqb-CmYHlnlcduSKbgsPBw_xEIfE5v_pOr_YD8gw,4483
|
||||
psutil/tests/test_bsd.py,sha256=aif308A3TRnPZGY1tmNlH25YCweeSMpwbkah2K13wZs,17785
|
||||
psutil/tests/test_connections.py,sha256=eXOPOkusHO6Xc8gNrDxPBhq1Ni2fYYe0AAzeGU4gijQ,20676
|
||||
psutil/tests/test_contracts.py,sha256=ryPd7QDkQKxh8Mjcl-iPflXw5OTi8TWWLzQjIJ4EW2w,24136
|
||||
psutil/tests/test_linux.py,sha256=_gQBxUSiRSygoGfFXn-2m5XpXJQMQSiurVobrwkaAgc,78746
|
||||
psutil/tests/test_memory_leaks.py,sha256=v-RmU0BAzH05pkQ1dUV1hUXxlMva7943GFvT9Erl6J4,18259
|
||||
psutil/tests/test_misc.py,sha256=4qu61Sdmvzbaz2heOXKlg_PveYrzamBIUJ5QlLIYmSQ,37821
|
||||
psutil/tests/test_osx.py,sha256=UL3sovPp-5f0LIjNqjHu12NnpXF2uuv8Z62wbeAJj2c,9652
|
||||
psutil/tests/test_posix.py,sha256=4gm2VeCYoPYnstn_2GMG18c6xvMV7APXA26W5Dcm99s,16397
|
||||
psutil/tests/test_process.py,sha256=IE-v3DHKIje6Kwnas8kzfsbz15L4-0dpI555lXg7-NE,60495
|
||||
psutil/tests/test_sunos.py,sha256=UNywEx_qlSOyUHV48lMKqmnu8RKPBDCQrO0llulCUHY,1322
|
||||
psutil/tests/test_system.py,sha256=fv3otFKJVOn3VpRrD5IMivbI-hfajL6wmzVQF_JJqDI,34885
|
||||
psutil/tests/test_unicode.py,sha256=M0VTr_kGgmDKiNq6nSvraaw-711pRXe_6R948qHAr8I,12913
|
||||
psutil/tests/test_windows.py,sha256=AG2Feks59VOahEW_hJs_o4f5wt20vS1jxxaUCijcwAQ,32609
|
||||
psutil-5.4.3.dist-info/DESCRIPTION.rst,sha256=oATWrkVX56oC_b77TIXQsrm1CxSgD93PM71km6ud5G4,19853
|
||||
psutil-5.4.3.dist-info/METADATA,sha256=neLhT7NMfWptGzaSxueDDYqVDOR0C9cNvE8pAK14C2c,22835
|
||||
psutil-5.4.3.dist-info/RECORD,,
|
||||
psutil-5.4.3.dist-info/WHEEL,sha256=oT-jJdPOIfRdvpqTJO9X6OjCsyUImH2THoT54KREdwI,106
|
||||
psutil-5.4.3.dist-info/metadata.json,sha256=RqO1wxtF8F5B2HqYztzUkdKh5XmF8Wq_PxB9l571GM0,2492
|
||||
psutil-5.4.3.dist-info/top_level.txt,sha256=gCNhn57wzksDjSAISmgMJ0aiXzQulk0GJhb2-BAyYgw,7
|
5
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/WHEEL
поставляемый
Normal file
5
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/WHEEL
поставляемый
Normal file
|
@ -0,0 +1,5 @@
|
|||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.30.0)
|
||||
Root-Is-Purelib: false
|
||||
Tag: cp27-cp27m-win_amd64
|
||||
|
1
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/metadata.json
поставляемый
Normal file
1
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/metadata.json
поставляемый
Normal file
|
@ -0,0 +1 @@
|
|||
{"classifiers": ["Development Status :: 5 - Production/Stable", "Environment :: Console", "Environment :: Win32 (MS Windows)", "Intended Audience :: Developers", "Intended Audience :: Information Technology", "Intended Audience :: System Administrators", "License :: OSI Approved :: BSD License", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows :: Windows NT/2000", "Operating System :: Microsoft", "Operating System :: OS Independent", "Operating System :: POSIX :: BSD :: FreeBSD", "Operating System :: POSIX :: BSD :: NetBSD", "Operating System :: POSIX :: BSD :: OpenBSD", "Operating System :: POSIX :: BSD", "Operating System :: POSIX :: Linux", "Operating System :: POSIX :: SunOS/Solaris", "Operating System :: POSIX", "Programming Language :: C", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Software Development :: Libraries", "Topic :: System :: Benchmark", "Topic :: System :: Hardware", "Topic :: System :: Monitoring", "Topic :: System :: Networking :: Monitoring", "Topic :: System :: Networking", "Topic :: System :: Operating System", "Topic :: System :: Systems Administration", "Topic :: Utilities"], "extensions": {"python.details": {"contacts": [{"email": "g.rodola@gmail.com", "name": "Giampaolo Rodola", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "https://github.com/giampaolo/psutil"}}}, "extras": ["enum"], "generator": "bdist_wheel (0.30.0)", "keywords": ["ps", "top", "kill", "free", "lsof", "netstat", "nice", "tty", "ionice", "uptime", "taskmgr", "process", "df", "iotop", "iostat", "ifconfig", "taskset", "who", "pidof", "pmap", "smem", "pstree", "monitoring", "ulimit", "prlimit", "smem"], "license": "BSD", "metadata_version": "2.0", "name": "psutil", "platform": "Platform Independent", "run_requires": [{"extra": "enum", "requires": ["enum34"]}], "summary": "Cross-platform lib for process and system monitoring in Python.", "test_requires": [{"requires": ["ipaddress", "mock"]}], "version": "5.4.3"}
|
1
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/top_level.txt
поставляемый
Normal file
1
third_party/python/psutil-cp27-none-win_amd64/psutil-5.4.3.dist-info/top_level.txt
поставляемый
Normal file
|
@ -0,0 +1 @@
|
|||
psutil
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,575 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Common objects shared by __init__.py and _ps*.py modules."""
|
||||
|
||||
# Note: this module is imported by setup.py so it should not import
|
||||
# psutil or third-party modules.
|
||||
|
||||
from __future__ import division
|
||||
|
||||
import contextlib
|
||||
import errno
|
||||
import functools
|
||||
import os
|
||||
import socket
|
||||
import stat
|
||||
import sys
|
||||
import threading
|
||||
import warnings
|
||||
from collections import defaultdict
|
||||
from collections import namedtuple
|
||||
from socket import AF_INET
|
||||
from socket import SOCK_DGRAM
|
||||
from socket import SOCK_STREAM
|
||||
try:
|
||||
from socket import AF_INET6
|
||||
except ImportError:
|
||||
AF_INET6 = None
|
||||
try:
|
||||
from socket import AF_UNIX
|
||||
except ImportError:
|
||||
AF_UNIX = None
|
||||
|
||||
if sys.version_info >= (3, 4):
|
||||
import enum
|
||||
else:
|
||||
enum = None
|
||||
|
||||
# can't take it from _common.py as this script is imported by setup.py
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
__all__ = [
|
||||
# constants
|
||||
'FREEBSD', 'BSD', 'LINUX', 'NETBSD', 'OPENBSD', 'OSX', 'POSIX', 'SUNOS',
|
||||
'WINDOWS',
|
||||
'ENCODING', 'ENCODING_ERRS', 'AF_INET6',
|
||||
# connection constants
|
||||
'CONN_CLOSE', 'CONN_CLOSE_WAIT', 'CONN_CLOSING', 'CONN_ESTABLISHED',
|
||||
'CONN_FIN_WAIT1', 'CONN_FIN_WAIT2', 'CONN_LAST_ACK', 'CONN_LISTEN',
|
||||
'CONN_NONE', 'CONN_SYN_RECV', 'CONN_SYN_SENT', 'CONN_TIME_WAIT',
|
||||
# net constants
|
||||
'NIC_DUPLEX_FULL', 'NIC_DUPLEX_HALF', 'NIC_DUPLEX_UNKNOWN',
|
||||
# process status constants
|
||||
'STATUS_DEAD', 'STATUS_DISK_SLEEP', 'STATUS_IDLE', 'STATUS_LOCKED',
|
||||
'STATUS_RUNNING', 'STATUS_SLEEPING', 'STATUS_STOPPED', 'STATUS_SUSPENDED',
|
||||
'STATUS_TRACING_STOP', 'STATUS_WAITING', 'STATUS_WAKE_KILL',
|
||||
'STATUS_WAKING', 'STATUS_ZOMBIE',
|
||||
# named tuples
|
||||
'pconn', 'pcputimes', 'pctxsw', 'pgids', 'pio', 'pionice', 'popenfile',
|
||||
'pthread', 'puids', 'sconn', 'scpustats', 'sdiskio', 'sdiskpart',
|
||||
'sdiskusage', 'snetio', 'snic', 'snicstats', 'sswap', 'suser',
|
||||
# utility functions
|
||||
'conn_tmap', 'deprecated_method', 'isfile_strict', 'memoize',
|
||||
'parse_environ_block', 'path_exists_strict', 'usage_percent',
|
||||
'supports_ipv6', 'sockfam_to_enum', 'socktype_to_enum', "wrap_numbers",
|
||||
]
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- OS constants
|
||||
# ===================================================================
|
||||
|
||||
|
||||
POSIX = os.name == "posix"
|
||||
WINDOWS = os.name == "nt"
|
||||
LINUX = sys.platform.startswith("linux")
|
||||
OSX = sys.platform.startswith("darwin")
|
||||
FREEBSD = sys.platform.startswith("freebsd")
|
||||
OPENBSD = sys.platform.startswith("openbsd")
|
||||
NETBSD = sys.platform.startswith("netbsd")
|
||||
BSD = FREEBSD or OPENBSD or NETBSD
|
||||
SUNOS = sys.platform.startswith("sunos") or sys.platform.startswith("solaris")
|
||||
AIX = sys.platform.startswith("aix")
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- API constants
|
||||
# ===================================================================
|
||||
|
||||
|
||||
# Process.status()
|
||||
STATUS_RUNNING = "running"
|
||||
STATUS_SLEEPING = "sleeping"
|
||||
STATUS_DISK_SLEEP = "disk-sleep"
|
||||
STATUS_STOPPED = "stopped"
|
||||
STATUS_TRACING_STOP = "tracing-stop"
|
||||
STATUS_ZOMBIE = "zombie"
|
||||
STATUS_DEAD = "dead"
|
||||
STATUS_WAKE_KILL = "wake-kill"
|
||||
STATUS_WAKING = "waking"
|
||||
STATUS_IDLE = "idle" # FreeBSD, OSX
|
||||
STATUS_LOCKED = "locked" # FreeBSD
|
||||
STATUS_WAITING = "waiting" # FreeBSD
|
||||
STATUS_SUSPENDED = "suspended" # NetBSD
|
||||
|
||||
# Process.connections() and psutil.net_connections()
|
||||
CONN_ESTABLISHED = "ESTABLISHED"
|
||||
CONN_SYN_SENT = "SYN_SENT"
|
||||
CONN_SYN_RECV = "SYN_RECV"
|
||||
CONN_FIN_WAIT1 = "FIN_WAIT1"
|
||||
CONN_FIN_WAIT2 = "FIN_WAIT2"
|
||||
CONN_TIME_WAIT = "TIME_WAIT"
|
||||
CONN_CLOSE = "CLOSE"
|
||||
CONN_CLOSE_WAIT = "CLOSE_WAIT"
|
||||
CONN_LAST_ACK = "LAST_ACK"
|
||||
CONN_LISTEN = "LISTEN"
|
||||
CONN_CLOSING = "CLOSING"
|
||||
CONN_NONE = "NONE"
|
||||
|
||||
# net_if_stats()
|
||||
if enum is None:
|
||||
NIC_DUPLEX_FULL = 2
|
||||
NIC_DUPLEX_HALF = 1
|
||||
NIC_DUPLEX_UNKNOWN = 0
|
||||
else:
|
||||
class NicDuplex(enum.IntEnum):
|
||||
NIC_DUPLEX_FULL = 2
|
||||
NIC_DUPLEX_HALF = 1
|
||||
NIC_DUPLEX_UNKNOWN = 0
|
||||
|
||||
globals().update(NicDuplex.__members__)
|
||||
|
||||
# sensors_battery()
|
||||
if enum is None:
|
||||
POWER_TIME_UNKNOWN = -1
|
||||
POWER_TIME_UNLIMITED = -2
|
||||
else:
|
||||
class BatteryTime(enum.IntEnum):
|
||||
POWER_TIME_UNKNOWN = -1
|
||||
POWER_TIME_UNLIMITED = -2
|
||||
|
||||
globals().update(BatteryTime.__members__)
|
||||
|
||||
# --- others
|
||||
|
||||
ENCODING = sys.getfilesystemencoding()
|
||||
if not PY3:
|
||||
ENCODING_ERRS = "replace"
|
||||
else:
|
||||
try:
|
||||
ENCODING_ERRS = sys.getfilesystemencodeerrors() # py 3.6
|
||||
except AttributeError:
|
||||
ENCODING_ERRS = "surrogateescape" if POSIX else "replace"
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- namedtuples
|
||||
# ===================================================================
|
||||
|
||||
# --- for system functions
|
||||
|
||||
# psutil.swap_memory()
|
||||
sswap = namedtuple('sswap', ['total', 'used', 'free', 'percent', 'sin',
|
||||
'sout'])
|
||||
# psutil.disk_usage()
|
||||
sdiskusage = namedtuple('sdiskusage', ['total', 'used', 'free', 'percent'])
|
||||
# psutil.disk_io_counters()
|
||||
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
||||
'read_bytes', 'write_bytes',
|
||||
'read_time', 'write_time'])
|
||||
# psutil.disk_partitions()
|
||||
sdiskpart = namedtuple('sdiskpart', ['device', 'mountpoint', 'fstype', 'opts'])
|
||||
# psutil.net_io_counters()
|
||||
snetio = namedtuple('snetio', ['bytes_sent', 'bytes_recv',
|
||||
'packets_sent', 'packets_recv',
|
||||
'errin', 'errout',
|
||||
'dropin', 'dropout'])
|
||||
# psutil.users()
|
||||
suser = namedtuple('suser', ['name', 'terminal', 'host', 'started', 'pid'])
|
||||
# psutil.net_connections()
|
||||
sconn = namedtuple('sconn', ['fd', 'family', 'type', 'laddr', 'raddr',
|
||||
'status', 'pid'])
|
||||
# psutil.net_if_addrs()
|
||||
snic = namedtuple('snic', ['family', 'address', 'netmask', 'broadcast', 'ptp'])
|
||||
# psutil.net_if_stats()
|
||||
snicstats = namedtuple('snicstats', ['isup', 'duplex', 'speed', 'mtu'])
|
||||
# psutil.cpu_stats()
|
||||
scpustats = namedtuple(
|
||||
'scpustats', ['ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'])
|
||||
# psutil.cpu_freq()
|
||||
scpufreq = namedtuple('scpufreq', ['current', 'min', 'max'])
|
||||
# psutil.sensors_temperatures()
|
||||
shwtemp = namedtuple(
|
||||
'shwtemp', ['label', 'current', 'high', 'critical'])
|
||||
# psutil.sensors_battery()
|
||||
sbattery = namedtuple('sbattery', ['percent', 'secsleft', 'power_plugged'])
|
||||
# psutil.sensors_battery()
|
||||
sfan = namedtuple('sfan', ['label', 'current'])
|
||||
|
||||
# --- for Process methods
|
||||
|
||||
# psutil.Process.cpu_times()
|
||||
pcputimes = namedtuple('pcputimes',
|
||||
['user', 'system', 'children_user', 'children_system'])
|
||||
# psutil.Process.open_files()
|
||||
popenfile = namedtuple('popenfile', ['path', 'fd'])
|
||||
# psutil.Process.threads()
|
||||
pthread = namedtuple('pthread', ['id', 'user_time', 'system_time'])
|
||||
# psutil.Process.uids()
|
||||
puids = namedtuple('puids', ['real', 'effective', 'saved'])
|
||||
# psutil.Process.gids()
|
||||
pgids = namedtuple('pgids', ['real', 'effective', 'saved'])
|
||||
# psutil.Process.io_counters()
|
||||
pio = namedtuple('pio', ['read_count', 'write_count',
|
||||
'read_bytes', 'write_bytes'])
|
||||
# psutil.Process.ionice()
|
||||
pionice = namedtuple('pionice', ['ioclass', 'value'])
|
||||
# psutil.Process.ctx_switches()
|
||||
pctxsw = namedtuple('pctxsw', ['voluntary', 'involuntary'])
|
||||
# psutil.Process.connections()
|
||||
pconn = namedtuple('pconn', ['fd', 'family', 'type', 'laddr', 'raddr',
|
||||
'status'])
|
||||
|
||||
# psutil.connections() and psutil.Process.connections()
|
||||
addr = namedtuple('addr', ['ip', 'port'])
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- Process.connections() 'kind' parameter mapping
|
||||
# ===================================================================
|
||||
|
||||
|
||||
conn_tmap = {
|
||||
"all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
|
||||
"tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]),
|
||||
"tcp4": ([AF_INET], [SOCK_STREAM]),
|
||||
"udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]),
|
||||
"udp4": ([AF_INET], [SOCK_DGRAM]),
|
||||
"inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
|
||||
"inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]),
|
||||
"inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]),
|
||||
}
|
||||
|
||||
if AF_INET6 is not None:
|
||||
conn_tmap.update({
|
||||
"tcp6": ([AF_INET6], [SOCK_STREAM]),
|
||||
"udp6": ([AF_INET6], [SOCK_DGRAM]),
|
||||
})
|
||||
|
||||
if AF_UNIX is not None:
|
||||
conn_tmap.update({
|
||||
"unix": ([AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]),
|
||||
})
|
||||
|
||||
del AF_INET, AF_UNIX, SOCK_STREAM, SOCK_DGRAM
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- utils
|
||||
# ===================================================================
|
||||
|
||||
|
||||
def usage_percent(used, total, _round=None):
|
||||
"""Calculate percentage usage of 'used' against 'total'."""
|
||||
try:
|
||||
ret = (used / total) * 100
|
||||
except ZeroDivisionError:
|
||||
ret = 0.0 if isinstance(used, float) or isinstance(total, float) else 0
|
||||
if _round is not None:
|
||||
return round(ret, _round)
|
||||
else:
|
||||
return ret
|
||||
|
||||
|
||||
def memoize(fun):
|
||||
"""A simple memoize decorator for functions supporting (hashable)
|
||||
positional arguments.
|
||||
It also provides a cache_clear() function for clearing the cache:
|
||||
|
||||
>>> @memoize
|
||||
... def foo()
|
||||
... return 1
|
||||
...
|
||||
>>> foo()
|
||||
1
|
||||
>>> foo.cache_clear()
|
||||
>>>
|
||||
"""
|
||||
@functools.wraps(fun)
|
||||
def wrapper(*args, **kwargs):
|
||||
key = (args, frozenset(sorted(kwargs.items())))
|
||||
try:
|
||||
return cache[key]
|
||||
except KeyError:
|
||||
ret = cache[key] = fun(*args, **kwargs)
|
||||
return ret
|
||||
|
||||
def cache_clear():
|
||||
"""Clear cache."""
|
||||
cache.clear()
|
||||
|
||||
cache = {}
|
||||
wrapper.cache_clear = cache_clear
|
||||
return wrapper
|
||||
|
||||
|
||||
def memoize_when_activated(fun):
|
||||
"""A memoize decorator which is disabled by default. It can be
|
||||
activated and deactivated on request.
|
||||
For efficiency reasons it can be used only against class methods
|
||||
accepting no arguments.
|
||||
|
||||
>>> class Foo:
|
||||
... @memoize
|
||||
... def foo()
|
||||
... print(1)
|
||||
...
|
||||
>>> f = Foo()
|
||||
>>> # deactivated (default)
|
||||
>>> foo()
|
||||
1
|
||||
>>> foo()
|
||||
1
|
||||
>>>
|
||||
>>> # activated
|
||||
>>> foo.cache_activate()
|
||||
>>> foo()
|
||||
1
|
||||
>>> foo()
|
||||
>>> foo()
|
||||
>>>
|
||||
"""
|
||||
@functools.wraps(fun)
|
||||
def wrapper(self):
|
||||
if not wrapper.cache_activated:
|
||||
return fun(self)
|
||||
else:
|
||||
try:
|
||||
ret = cache[fun]
|
||||
except KeyError:
|
||||
ret = cache[fun] = fun(self)
|
||||
return ret
|
||||
|
||||
def cache_activate():
|
||||
"""Activate cache."""
|
||||
wrapper.cache_activated = True
|
||||
|
||||
def cache_deactivate():
|
||||
"""Deactivate and clear cache."""
|
||||
wrapper.cache_activated = False
|
||||
cache.clear()
|
||||
|
||||
cache = {}
|
||||
wrapper.cache_activated = False
|
||||
wrapper.cache_activate = cache_activate
|
||||
wrapper.cache_deactivate = cache_deactivate
|
||||
return wrapper
|
||||
|
||||
|
||||
def isfile_strict(path):
|
||||
"""Same as os.path.isfile() but does not swallow EACCES / EPERM
|
||||
exceptions, see:
|
||||
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
|
||||
"""
|
||||
try:
|
||||
st = os.stat(path)
|
||||
except OSError as err:
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise
|
||||
return False
|
||||
else:
|
||||
return stat.S_ISREG(st.st_mode)
|
||||
|
||||
|
||||
def path_exists_strict(path):
|
||||
"""Same as os.path.exists() but does not swallow EACCES / EPERM
|
||||
exceptions, see:
|
||||
http://mail.python.org/pipermail/python-dev/2012-June/120787.html
|
||||
"""
|
||||
try:
|
||||
os.stat(path)
|
||||
except OSError as err:
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
@memoize
|
||||
def supports_ipv6():
|
||||
"""Return True if IPv6 is supported on this platform."""
|
||||
if not socket.has_ipv6 or AF_INET6 is None:
|
||||
return False
|
||||
try:
|
||||
sock = socket.socket(AF_INET6, socket.SOCK_STREAM)
|
||||
with contextlib.closing(sock):
|
||||
sock.bind(("::1", 0))
|
||||
return True
|
||||
except socket.error:
|
||||
return False
|
||||
|
||||
|
||||
def parse_environ_block(data):
|
||||
"""Parse a C environ block of environment variables into a dictionary."""
|
||||
# The block is usually raw data from the target process. It might contain
|
||||
# trailing garbage and lines that do not look like assignments.
|
||||
ret = {}
|
||||
pos = 0
|
||||
|
||||
# localize global variable to speed up access.
|
||||
WINDOWS_ = WINDOWS
|
||||
while True:
|
||||
next_pos = data.find("\0", pos)
|
||||
# nul byte at the beginning or double nul byte means finish
|
||||
if next_pos <= pos:
|
||||
break
|
||||
# there might not be an equals sign
|
||||
equal_pos = data.find("=", pos, next_pos)
|
||||
if equal_pos > pos:
|
||||
key = data[pos:equal_pos]
|
||||
value = data[equal_pos + 1:next_pos]
|
||||
# Windows expects environment variables to be uppercase only
|
||||
if WINDOWS_:
|
||||
key = key.upper()
|
||||
ret[key] = value
|
||||
pos = next_pos + 1
|
||||
|
||||
return ret
|
||||
|
||||
|
||||
def sockfam_to_enum(num):
|
||||
"""Convert a numeric socket family value to an IntEnum member.
|
||||
If it's not a known member, return the numeric value itself.
|
||||
"""
|
||||
if enum is None:
|
||||
return num
|
||||
else: # pragma: no cover
|
||||
try:
|
||||
return socket.AddressFamily(num)
|
||||
except (ValueError, AttributeError):
|
||||
return num
|
||||
|
||||
|
||||
def socktype_to_enum(num):
|
||||
"""Convert a numeric socket type value to an IntEnum member.
|
||||
If it's not a known member, return the numeric value itself.
|
||||
"""
|
||||
if enum is None:
|
||||
return num
|
||||
else: # pragma: no cover
|
||||
try:
|
||||
return socket.AddressType(num)
|
||||
except (ValueError, AttributeError):
|
||||
return num
|
||||
|
||||
|
||||
def deprecated_method(replacement):
|
||||
"""A decorator which can be used to mark a method as deprecated
|
||||
'replcement' is the method name which will be called instead.
|
||||
"""
|
||||
def outer(fun):
|
||||
msg = "%s() is deprecated and will be removed; use %s() instead" % (
|
||||
fun.__name__, replacement)
|
||||
if fun.__doc__ is None:
|
||||
fun.__doc__ = msg
|
||||
|
||||
@functools.wraps(fun)
|
||||
def inner(self, *args, **kwargs):
|
||||
warnings.warn(msg, category=FutureWarning, stacklevel=2)
|
||||
return getattr(self, replacement)(*args, **kwargs)
|
||||
return inner
|
||||
return outer
|
||||
|
||||
|
||||
class _WrapNumbers:
|
||||
"""Watches numbers so that they don't overflow and wrap
|
||||
(reset to zero).
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.lock = threading.Lock()
|
||||
self.cache = {}
|
||||
self.reminders = {}
|
||||
self.reminder_keys = {}
|
||||
|
||||
def _add_dict(self, input_dict, name):
|
||||
assert name not in self.cache
|
||||
assert name not in self.reminders
|
||||
assert name not in self.reminder_keys
|
||||
self.cache[name] = input_dict
|
||||
self.reminders[name] = defaultdict(int)
|
||||
self.reminder_keys[name] = defaultdict(set)
|
||||
|
||||
def _remove_dead_reminders(self, input_dict, name):
|
||||
"""In case the number of keys changed between calls (e.g. a
|
||||
disk disappears) this removes the entry from self.reminders.
|
||||
"""
|
||||
old_dict = self.cache[name]
|
||||
gone_keys = set(old_dict.keys()) - set(input_dict.keys())
|
||||
for gone_key in gone_keys:
|
||||
for remkey in self.reminder_keys[name][gone_key]:
|
||||
del self.reminders[name][remkey]
|
||||
del self.reminder_keys[name][gone_key]
|
||||
|
||||
def run(self, input_dict, name):
|
||||
"""Cache dict and sum numbers which overflow and wrap.
|
||||
Return an updated copy of `input_dict`
|
||||
"""
|
||||
if name not in self.cache:
|
||||
# This was the first call.
|
||||
self._add_dict(input_dict, name)
|
||||
return input_dict
|
||||
|
||||
self._remove_dead_reminders(input_dict, name)
|
||||
|
||||
old_dict = self.cache[name]
|
||||
new_dict = {}
|
||||
for key in input_dict.keys():
|
||||
input_tuple = input_dict[key]
|
||||
try:
|
||||
old_tuple = old_dict[key]
|
||||
except KeyError:
|
||||
# The input dict has a new key (e.g. a new disk or NIC)
|
||||
# which didn't exist in the previous call.
|
||||
new_dict[key] = input_tuple
|
||||
continue
|
||||
|
||||
bits = []
|
||||
for i in range(len(input_tuple)):
|
||||
input_value = input_tuple[i]
|
||||
old_value = old_tuple[i]
|
||||
remkey = (key, i)
|
||||
if input_value < old_value:
|
||||
# it wrapped!
|
||||
self.reminders[name][remkey] += old_value
|
||||
self.reminder_keys[name][key].add(remkey)
|
||||
bits.append(input_value + self.reminders[name][remkey])
|
||||
|
||||
new_dict[key] = tuple(bits)
|
||||
|
||||
self.cache[name] = input_dict
|
||||
return new_dict
|
||||
|
||||
def cache_clear(self, name=None):
|
||||
"""Clear the internal cache, optionally only for function 'name'."""
|
||||
with self.lock:
|
||||
if name is None:
|
||||
self.cache.clear()
|
||||
self.reminders.clear()
|
||||
self.reminder_keys.clear()
|
||||
else:
|
||||
self.cache.pop(name, None)
|
||||
self.reminders.pop(name, None)
|
||||
self.reminder_keys.pop(name, None)
|
||||
|
||||
def cache_info(self):
|
||||
"""Return internal cache dicts as a tuple of 3 elements."""
|
||||
with self.lock:
|
||||
return (self.cache, self.reminders, self.reminder_keys)
|
||||
|
||||
|
||||
def wrap_numbers(input_dict, name):
|
||||
"""Given an `input_dict` and a function `name`, adjust the numbers
|
||||
which "wrap" (restart from zero) across different calls by adding
|
||||
"old value" to "new value" and return an updated dict.
|
||||
"""
|
||||
with _wn.lock:
|
||||
return _wn.run(input_dict, name)
|
||||
|
||||
|
||||
_wn = _WrapNumbers()
|
||||
wrap_numbers.cache_clear = _wn.cache_clear
|
||||
wrap_numbers.cache_info = _wn.cache_info
|
|
@ -0,0 +1,249 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Module which provides compatibility with older Python versions."""
|
||||
|
||||
import collections
|
||||
import functools
|
||||
import os
|
||||
import sys
|
||||
|
||||
__all__ = ["PY3", "long", "xrange", "unicode", "basestring", "u", "b",
|
||||
"callable", "lru_cache", "which"]
|
||||
|
||||
PY3 = sys.version_info[0] == 3
|
||||
|
||||
if PY3:
|
||||
long = int
|
||||
xrange = range
|
||||
unicode = str
|
||||
basestring = str
|
||||
|
||||
def u(s):
|
||||
return s
|
||||
|
||||
def b(s):
|
||||
return s.encode("latin-1")
|
||||
else:
|
||||
long = long
|
||||
xrange = xrange
|
||||
unicode = unicode
|
||||
basestring = basestring
|
||||
|
||||
def u(s):
|
||||
return unicode(s, "unicode_escape")
|
||||
|
||||
def b(s):
|
||||
return s
|
||||
|
||||
|
||||
# removed in 3.0, reintroduced in 3.2
|
||||
try:
|
||||
callable = callable
|
||||
except NameError:
|
||||
def callable(obj):
|
||||
return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
|
||||
|
||||
|
||||
# --- stdlib additions
|
||||
|
||||
|
||||
# py 3.2 functools.lru_cache
|
||||
# Taken from: http://code.activestate.com/recipes/578078
|
||||
# Credit: Raymond Hettinger
|
||||
try:
|
||||
from functools import lru_cache
|
||||
except ImportError:
|
||||
try:
|
||||
from threading import RLock
|
||||
except ImportError:
|
||||
from dummy_threading import RLock
|
||||
|
||||
_CacheInfo = collections.namedtuple(
|
||||
"CacheInfo", ["hits", "misses", "maxsize", "currsize"])
|
||||
|
||||
class _HashedSeq(list):
|
||||
__slots__ = 'hashvalue'
|
||||
|
||||
def __init__(self, tup, hash=hash):
|
||||
self[:] = tup
|
||||
self.hashvalue = hash(tup)
|
||||
|
||||
def __hash__(self):
|
||||
return self.hashvalue
|
||||
|
||||
def _make_key(args, kwds, typed,
|
||||
kwd_mark=(object(), ),
|
||||
fasttypes=set((int, str, frozenset, type(None))),
|
||||
sorted=sorted, tuple=tuple, type=type, len=len):
|
||||
key = args
|
||||
if kwds:
|
||||
sorted_items = sorted(kwds.items())
|
||||
key += kwd_mark
|
||||
for item in sorted_items:
|
||||
key += item
|
||||
if typed:
|
||||
key += tuple(type(v) for v in args)
|
||||
if kwds:
|
||||
key += tuple(type(v) for k, v in sorted_items)
|
||||
elif len(key) == 1 and type(key[0]) in fasttypes:
|
||||
return key[0]
|
||||
return _HashedSeq(key)
|
||||
|
||||
def lru_cache(maxsize=100, typed=False):
|
||||
"""Least-recently-used cache decorator, see:
|
||||
http://docs.python.org/3/library/functools.html#functools.lru_cache
|
||||
"""
|
||||
def decorating_function(user_function):
|
||||
cache = dict()
|
||||
stats = [0, 0]
|
||||
HITS, MISSES = 0, 1
|
||||
make_key = _make_key
|
||||
cache_get = cache.get
|
||||
_len = len
|
||||
lock = RLock()
|
||||
root = []
|
||||
root[:] = [root, root, None, None]
|
||||
nonlocal_root = [root]
|
||||
PREV, NEXT, KEY, RESULT = 0, 1, 2, 3
|
||||
if maxsize == 0:
|
||||
def wrapper(*args, **kwds):
|
||||
result = user_function(*args, **kwds)
|
||||
stats[MISSES] += 1
|
||||
return result
|
||||
elif maxsize is None:
|
||||
def wrapper(*args, **kwds):
|
||||
key = make_key(args, kwds, typed)
|
||||
result = cache_get(key, root)
|
||||
if result is not root:
|
||||
stats[HITS] += 1
|
||||
return result
|
||||
result = user_function(*args, **kwds)
|
||||
cache[key] = result
|
||||
stats[MISSES] += 1
|
||||
return result
|
||||
else:
|
||||
def wrapper(*args, **kwds):
|
||||
if kwds or typed:
|
||||
key = make_key(args, kwds, typed)
|
||||
else:
|
||||
key = args
|
||||
lock.acquire()
|
||||
try:
|
||||
link = cache_get(key)
|
||||
if link is not None:
|
||||
root, = nonlocal_root
|
||||
link_prev, link_next, key, result = link
|
||||
link_prev[NEXT] = link_next
|
||||
link_next[PREV] = link_prev
|
||||
last = root[PREV]
|
||||
last[NEXT] = root[PREV] = link
|
||||
link[PREV] = last
|
||||
link[NEXT] = root
|
||||
stats[HITS] += 1
|
||||
return result
|
||||
finally:
|
||||
lock.release()
|
||||
result = user_function(*args, **kwds)
|
||||
lock.acquire()
|
||||
try:
|
||||
root, = nonlocal_root
|
||||
if key in cache:
|
||||
pass
|
||||
elif _len(cache) >= maxsize:
|
||||
oldroot = root
|
||||
oldroot[KEY] = key
|
||||
oldroot[RESULT] = result
|
||||
root = nonlocal_root[0] = oldroot[NEXT]
|
||||
oldkey = root[KEY]
|
||||
root[KEY] = root[RESULT] = None
|
||||
del cache[oldkey]
|
||||
cache[key] = oldroot
|
||||
else:
|
||||
last = root[PREV]
|
||||
link = [last, root, key, result]
|
||||
last[NEXT] = root[PREV] = cache[key] = link
|
||||
stats[MISSES] += 1
|
||||
finally:
|
||||
lock.release()
|
||||
return result
|
||||
|
||||
def cache_info():
|
||||
"""Report cache statistics"""
|
||||
lock.acquire()
|
||||
try:
|
||||
return _CacheInfo(stats[HITS], stats[MISSES], maxsize,
|
||||
len(cache))
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
def cache_clear():
|
||||
"""Clear the cache and cache statistics"""
|
||||
lock.acquire()
|
||||
try:
|
||||
cache.clear()
|
||||
root = nonlocal_root[0]
|
||||
root[:] = [root, root, None, None]
|
||||
stats[:] = [0, 0]
|
||||
finally:
|
||||
lock.release()
|
||||
|
||||
wrapper.__wrapped__ = user_function
|
||||
wrapper.cache_info = cache_info
|
||||
wrapper.cache_clear = cache_clear
|
||||
return functools.update_wrapper(wrapper, user_function)
|
||||
|
||||
return decorating_function
|
||||
|
||||
|
||||
# python 3.3
|
||||
try:
|
||||
from shutil import which
|
||||
except ImportError:
|
||||
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
|
||||
"""Given a command, mode, and a PATH string, return the path which
|
||||
conforms to the given mode on the PATH, or None if there is no such
|
||||
file.
|
||||
|
||||
`mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
|
||||
of os.environ.get("PATH"), or can be overridden with a custom search
|
||||
path.
|
||||
"""
|
||||
def _access_check(fn, mode):
|
||||
return (os.path.exists(fn) and os.access(fn, mode) and
|
||||
not os.path.isdir(fn))
|
||||
|
||||
if os.path.dirname(cmd):
|
||||
if _access_check(cmd, mode):
|
||||
return cmd
|
||||
return None
|
||||
|
||||
if path is None:
|
||||
path = os.environ.get("PATH", os.defpath)
|
||||
if not path:
|
||||
return None
|
||||
path = path.split(os.pathsep)
|
||||
|
||||
if sys.platform == "win32":
|
||||
if os.curdir not in path:
|
||||
path.insert(0, os.curdir)
|
||||
|
||||
pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
|
||||
if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
|
||||
files = [cmd]
|
||||
else:
|
||||
files = [cmd + ext for ext in pathext]
|
||||
else:
|
||||
files = [cmd]
|
||||
|
||||
seen = set()
|
||||
for dir in path:
|
||||
normdir = os.path.normcase(dir)
|
||||
if normdir not in seen:
|
||||
seen.add(normdir)
|
||||
for thefile in files:
|
||||
name = os.path.join(dir, thefile)
|
||||
if _access_check(name, mode):
|
||||
return name
|
||||
return None
|
|
@ -0,0 +1,94 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
|
||||
class Error(Exception):
|
||||
"""Base exception class. All other psutil exceptions inherit
|
||||
from this one.
|
||||
"""
|
||||
|
||||
def __init__(self, msg=""):
|
||||
Exception.__init__(self, msg)
|
||||
self.msg = msg
|
||||
|
||||
def __repr__(self):
|
||||
ret = "psutil.%s %s" % (self.__class__.__name__, self.msg)
|
||||
return ret.strip()
|
||||
|
||||
__str__ = __repr__
|
||||
|
||||
|
||||
class NoSuchProcess(Error):
|
||||
"""Exception raised when a process with a certain PID doesn't
|
||||
or no longer exists.
|
||||
"""
|
||||
|
||||
def __init__(self, pid, name=None, msg=None):
|
||||
Error.__init__(self, msg)
|
||||
self.pid = pid
|
||||
self.name = name
|
||||
self.msg = msg
|
||||
if msg is None:
|
||||
if name:
|
||||
details = "(pid=%s, name=%s)" % (self.pid, repr(self.name))
|
||||
else:
|
||||
details = "(pid=%s)" % self.pid
|
||||
self.msg = "process no longer exists " + details
|
||||
|
||||
|
||||
class ZombieProcess(NoSuchProcess):
|
||||
"""Exception raised when querying a zombie process. This is
|
||||
raised on OSX, BSD and Solaris only, and not always: depending
|
||||
on the query the OS may be able to succeed anyway.
|
||||
On Linux all zombie processes are querable (hence this is never
|
||||
raised). Windows doesn't have zombie processes.
|
||||
"""
|
||||
|
||||
def __init__(self, pid, name=None, ppid=None, msg=None):
|
||||
NoSuchProcess.__init__(self, msg)
|
||||
self.pid = pid
|
||||
self.ppid = ppid
|
||||
self.name = name
|
||||
self.msg = msg
|
||||
if msg is None:
|
||||
args = ["pid=%s" % pid]
|
||||
if name:
|
||||
args.append("name=%s" % repr(self.name))
|
||||
if ppid:
|
||||
args.append("ppid=%s" % self.ppid)
|
||||
details = "(%s)" % ", ".join(args)
|
||||
self.msg = "process still exists but it's a zombie " + details
|
||||
|
||||
|
||||
class AccessDenied(Error):
|
||||
"""Exception raised when permission to perform an action is denied."""
|
||||
|
||||
def __init__(self, pid=None, name=None, msg=None):
|
||||
Error.__init__(self, msg)
|
||||
self.pid = pid
|
||||
self.name = name
|
||||
self.msg = msg
|
||||
if msg is None:
|
||||
if (pid is not None) and (name is not None):
|
||||
self.msg = "(pid=%s, name=%s)" % (pid, repr(name))
|
||||
elif (pid is not None):
|
||||
self.msg = "(pid=%s)" % self.pid
|
||||
else:
|
||||
self.msg = ""
|
||||
|
||||
|
||||
class TimeoutExpired(Error):
|
||||
"""Raised on Process.wait(timeout) if timeout expires and process
|
||||
is still alive.
|
||||
"""
|
||||
|
||||
def __init__(self, seconds, pid=None, name=None):
|
||||
Error.__init__(self, "timeout after %s seconds" % seconds)
|
||||
self.seconds = seconds
|
||||
self.pid = pid
|
||||
self.name = name
|
||||
if (pid is not None) and (name is not None):
|
||||
self.msg += " (pid=%s, name=%s)" % (pid, repr(name))
|
||||
elif (pid is not None):
|
||||
self.msg += " (pid=%s)" % self.pid
|
|
@ -0,0 +1,573 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'
|
||||
# Copyright (c) 2017, Arnon Yaari
|
||||
# All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""AIX platform implementation."""
|
||||
|
||||
import errno
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import namedtuple
|
||||
from socket import AF_INET
|
||||
|
||||
from . import _common
|
||||
from . import _psposix
|
||||
from . import _psutil_aix as cext
|
||||
from . import _psutil_posix as cext_posix
|
||||
from ._common import AF_INET6
|
||||
from ._common import memoize_when_activated
|
||||
from ._common import NIC_DUPLEX_FULL
|
||||
from ._common import NIC_DUPLEX_HALF
|
||||
from ._common import NIC_DUPLEX_UNKNOWN
|
||||
from ._common import sockfam_to_enum
|
||||
from ._common import socktype_to_enum
|
||||
from ._common import usage_percent
|
||||
from ._compat import PY3
|
||||
from ._exceptions import AccessDenied
|
||||
from ._exceptions import NoSuchProcess
|
||||
from ._exceptions import ZombieProcess
|
||||
|
||||
|
||||
__extra__all__ = ["PROCFS_PATH"]
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- globals
|
||||
# =====================================================================
|
||||
|
||||
|
||||
HAS_THREADS = hasattr(cext, "proc_threads")
|
||||
|
||||
PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
|
||||
AF_LINK = cext_posix.AF_LINK
|
||||
|
||||
PROC_STATUSES = {
|
||||
cext.SIDL: _common.STATUS_IDLE,
|
||||
cext.SZOMB: _common.STATUS_ZOMBIE,
|
||||
cext.SACTIVE: _common.STATUS_RUNNING,
|
||||
cext.SSWAP: _common.STATUS_RUNNING, # TODO what status is this?
|
||||
cext.SSTOP: _common.STATUS_STOPPED,
|
||||
}
|
||||
|
||||
TCP_STATUSES = {
|
||||
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
||||
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
||||
cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
|
||||
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
||||
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
||||
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
||||
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
||||
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
||||
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
||||
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
||||
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
||||
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
||||
}
|
||||
|
||||
proc_info_map = dict(
|
||||
ppid=0,
|
||||
rss=1,
|
||||
vms=2,
|
||||
create_time=3,
|
||||
nice=4,
|
||||
num_threads=5,
|
||||
status=6,
|
||||
ttynr=7)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- named tuples
|
||||
# =====================================================================
|
||||
|
||||
|
||||
# psutil.Process.memory_info()
|
||||
pmem = namedtuple('pmem', ['rss', 'vms'])
|
||||
# psutil.Process.memory_full_info()
|
||||
pfullmem = pmem
|
||||
# psutil.Process.cpu_times()
|
||||
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
|
||||
# psutil.virtual_memory()
|
||||
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
|
||||
# psutil.Process.memory_maps(grouped=True)
|
||||
pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss', 'anon', 'locked'])
|
||||
# psutil.Process.memory_maps(grouped=False)
|
||||
pmmap_ext = namedtuple(
|
||||
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- utils
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def get_procfs_path():
|
||||
"""Return updated psutil.PROCFS_PATH constant."""
|
||||
return sys.modules['psutil'].PROCFS_PATH
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- memory
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def virtual_memory():
|
||||
total, avail, free, pinned, inuse = cext.virtual_mem()
|
||||
percent = usage_percent((total - avail), total, _round=1)
|
||||
return svmem(total, avail, percent, inuse, free)
|
||||
|
||||
|
||||
def swap_memory():
|
||||
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
|
||||
total, free, sin, sout = cext.swap_mem()
|
||||
used = total - free
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return _common.sswap(total, used, free, percent, sin, sout)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- CPU
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def cpu_times():
|
||||
"""Return system-wide CPU times as a named tuple"""
|
||||
ret = cext.per_cpu_times()
|
||||
return scputimes(*[sum(x) for x in zip(*ret)])
|
||||
|
||||
|
||||
def per_cpu_times():
|
||||
"""Return system per-CPU times as a list of named tuples"""
|
||||
ret = cext.per_cpu_times()
|
||||
return [scputimes(*x) for x in ret]
|
||||
|
||||
|
||||
def cpu_count_logical():
|
||||
"""Return the number of logical CPUs in the system."""
|
||||
try:
|
||||
return os.sysconf("SC_NPROCESSORS_ONLN")
|
||||
except ValueError:
|
||||
# mimic os.cpu_count() behavior
|
||||
return None
|
||||
|
||||
|
||||
def cpu_count_physical():
|
||||
cmd = "lsdev -Cc processor"
|
||||
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
if PY3:
|
||||
stdout, stderr = [x.decode(sys.stdout.encoding)
|
||||
for x in (stdout, stderr)]
|
||||
if p.returncode != 0:
|
||||
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
|
||||
processors = stdout.strip().splitlines()
|
||||
return len(processors) or None
|
||||
|
||||
|
||||
def cpu_stats():
|
||||
"""Return various CPU stats as a named tuple."""
|
||||
ctx_switches, interrupts, soft_interrupts, syscalls = cext.cpu_stats()
|
||||
return _common.scpustats(
|
||||
ctx_switches, interrupts, soft_interrupts, syscalls)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- disks
|
||||
# =====================================================================
|
||||
|
||||
|
||||
disk_io_counters = cext.disk_io_counters
|
||||
disk_usage = _psposix.disk_usage
|
||||
|
||||
|
||||
def disk_partitions(all=False):
|
||||
"""Return system disk partitions."""
|
||||
# TODO - the filtering logic should be better checked so that
|
||||
# it tries to reflect 'df' as much as possible
|
||||
retlist = []
|
||||
partitions = cext.disk_partitions()
|
||||
for partition in partitions:
|
||||
device, mountpoint, fstype, opts = partition
|
||||
if device == 'none':
|
||||
device = ''
|
||||
if not all:
|
||||
# Differently from, say, Linux, we don't have a list of
|
||||
# common fs types so the best we can do, AFAIK, is to
|
||||
# filter by filesystem having a total size > 0.
|
||||
if not disk_usage(mountpoint).total:
|
||||
continue
|
||||
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
|
||||
retlist.append(ntuple)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- network
|
||||
# =====================================================================
|
||||
|
||||
|
||||
net_if_addrs = cext_posix.net_if_addrs
|
||||
net_io_counters = cext.net_io_counters
|
||||
|
||||
|
||||
def net_connections(kind, _pid=-1):
|
||||
"""Return socket connections. If pid == -1 return system-wide
|
||||
connections (as opposed to connections opened by one process only).
|
||||
"""
|
||||
cmap = _common.conn_tmap
|
||||
if kind not in cmap:
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in cmap])))
|
||||
families, types = _common.conn_tmap[kind]
|
||||
rawlist = cext.net_connections(_pid)
|
||||
ret = set()
|
||||
for item in rawlist:
|
||||
fd, fam, type_, laddr, raddr, status, pid = item
|
||||
if fam not in families:
|
||||
continue
|
||||
if type_ not in types:
|
||||
continue
|
||||
status = TCP_STATUSES[status]
|
||||
if fam in (AF_INET, AF_INET6):
|
||||
if laddr:
|
||||
laddr = _common.addr(*laddr)
|
||||
if raddr:
|
||||
raddr = _common.addr(*raddr)
|
||||
fam = sockfam_to_enum(fam)
|
||||
type_ = socktype_to_enum(type_)
|
||||
if _pid == -1:
|
||||
nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid)
|
||||
else:
|
||||
nt = _common.pconn(fd, fam, type_, laddr, raddr, status)
|
||||
ret.add(nt)
|
||||
return list(ret)
|
||||
|
||||
|
||||
def net_if_stats():
|
||||
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
||||
duplex_map = {"Full": NIC_DUPLEX_FULL,
|
||||
"Half": NIC_DUPLEX_HALF}
|
||||
names = set([x[0] for x in net_if_addrs()])
|
||||
ret = {}
|
||||
for name in names:
|
||||
isup, mtu = cext.net_if_stats(name)
|
||||
|
||||
# try to get speed and duplex
|
||||
# TODO: rewrite this in C (entstat forks, so use truss -f to follow.
|
||||
# looks like it is using an undocumented ioctl?)
|
||||
duplex = ""
|
||||
speed = 0
|
||||
p = subprocess.Popen(["/usr/bin/entstat", "-d", name],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
if PY3:
|
||||
stdout, stderr = [x.decode(sys.stdout.encoding)
|
||||
for x in (stdout, stderr)]
|
||||
if p.returncode == 0:
|
||||
re_result = re.search("Running: (\d+) Mbps.*?(\w+) Duplex", stdout)
|
||||
if re_result is not None:
|
||||
speed = int(re_result.group(1))
|
||||
duplex = re_result.group(2)
|
||||
|
||||
duplex = duplex_map.get(duplex, NIC_DUPLEX_UNKNOWN)
|
||||
ret[name] = _common.snicstats(isup, duplex, speed, mtu)
|
||||
return ret
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- other system functions
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def boot_time():
|
||||
"""The system boot time expressed in seconds since the epoch."""
|
||||
return cext.boot_time()
|
||||
|
||||
|
||||
def users():
|
||||
"""Return currently connected users as a list of namedtuples."""
|
||||
retlist = []
|
||||
rawlist = cext.users()
|
||||
localhost = (':0.0', ':0')
|
||||
for item in rawlist:
|
||||
user, tty, hostname, tstamp, user_process, pid = item
|
||||
# note: the underlying C function includes entries about
|
||||
# system boot, run level and others. We might want
|
||||
# to use them in the future.
|
||||
if not user_process:
|
||||
continue
|
||||
if hostname in localhost:
|
||||
hostname = 'localhost'
|
||||
nt = _common.suser(user, tty, hostname, tstamp, pid)
|
||||
retlist.append(nt)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- processes
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def pids():
|
||||
"""Returns a list of PIDs currently running on the system."""
|
||||
return [int(x) for x in os.listdir(get_procfs_path()) if x.isdigit()]
|
||||
|
||||
|
||||
def pid_exists(pid):
|
||||
"""Check for the existence of a unix pid."""
|
||||
return os.path.exists(os.path.join(get_procfs_path(), str(pid), "psinfo"))
|
||||
|
||||
|
||||
def wrap_exceptions(fun):
|
||||
"""Call callable into a try/except clause and translate ENOENT,
|
||||
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
|
||||
"""
|
||||
|
||||
def wrapper(self, *args, **kwargs):
|
||||
try:
|
||||
return fun(self, *args, **kwargs)
|
||||
except EnvironmentError as err:
|
||||
# support for private module import
|
||||
if (NoSuchProcess is None or AccessDenied is None or
|
||||
ZombieProcess is None):
|
||||
raise
|
||||
# ENOENT (no such file or directory) gets raised on open().
|
||||
# ESRCH (no such process) can get raised on read() if
|
||||
# process is gone in meantime.
|
||||
if err.errno in (errno.ENOENT, errno.ESRCH):
|
||||
if not pid_exists(self.pid):
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
else:
|
||||
raise ZombieProcess(self.pid, self._name, self._ppid)
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
class Process(object):
|
||||
"""Wrapper class around underlying C implementation."""
|
||||
|
||||
__slots__ = ["pid", "_name", "_ppid", "_procfs_path"]
|
||||
|
||||
def __init__(self, pid):
|
||||
self.pid = pid
|
||||
self._name = None
|
||||
self._ppid = None
|
||||
self._procfs_path = get_procfs_path()
|
||||
|
||||
def oneshot_enter(self):
|
||||
self._proc_name_and_args.cache_activate()
|
||||
self._proc_basic_info.cache_activate()
|
||||
self._proc_cred.cache_activate()
|
||||
|
||||
def oneshot_exit(self):
|
||||
self._proc_name_and_args.cache_deactivate()
|
||||
self._proc_basic_info.cache_deactivate()
|
||||
self._proc_cred.cache_deactivate()
|
||||
|
||||
@memoize_when_activated
|
||||
def _proc_name_and_args(self):
|
||||
return cext.proc_name_and_args(self.pid, self._procfs_path)
|
||||
|
||||
@memoize_when_activated
|
||||
def _proc_basic_info(self):
|
||||
return cext.proc_basic_info(self.pid, self._procfs_path)
|
||||
|
||||
@memoize_when_activated
|
||||
def _proc_cred(self):
|
||||
return cext.proc_cred(self.pid, self._procfs_path)
|
||||
|
||||
@wrap_exceptions
|
||||
def name(self):
|
||||
if self.pid == 0:
|
||||
return "swapper"
|
||||
# note: this is limited to 15 characters
|
||||
return self._proc_name_and_args()[0].rstrip("\x00")
|
||||
|
||||
@wrap_exceptions
|
||||
def exe(self):
|
||||
# there is no way to get executable path in AIX other than to guess,
|
||||
# and guessing is more complex than what's in the wrapping class
|
||||
exe = self.cmdline()[0]
|
||||
if os.path.sep in exe:
|
||||
# relative or absolute path
|
||||
if not os.path.isabs(exe):
|
||||
# if cwd has changed, we're out of luck - this may be wrong!
|
||||
exe = os.path.abspath(os.path.join(self.cwd(), exe))
|
||||
if (os.path.isabs(exe) and
|
||||
os.path.isfile(exe) and
|
||||
os.access(exe, os.X_OK)):
|
||||
return exe
|
||||
# not found, move to search in PATH using basename only
|
||||
exe = os.path.basename(exe)
|
||||
# search for exe name PATH
|
||||
for path in os.environ["PATH"].split(":"):
|
||||
possible_exe = os.path.abspath(os.path.join(path, exe))
|
||||
if (os.path.isfile(possible_exe) and
|
||||
os.access(possible_exe, os.X_OK)):
|
||||
return possible_exe
|
||||
return ''
|
||||
|
||||
@wrap_exceptions
|
||||
def cmdline(self):
|
||||
return self._proc_name_and_args()[1].split(' ')
|
||||
|
||||
@wrap_exceptions
|
||||
def create_time(self):
|
||||
return self._proc_basic_info()[proc_info_map['create_time']]
|
||||
|
||||
@wrap_exceptions
|
||||
def num_threads(self):
|
||||
return self._proc_basic_info()[proc_info_map['num_threads']]
|
||||
|
||||
if HAS_THREADS:
|
||||
@wrap_exceptions
|
||||
def threads(self):
|
||||
rawlist = cext.proc_threads(self.pid)
|
||||
retlist = []
|
||||
for thread_id, utime, stime in rawlist:
|
||||
ntuple = _common.pthread(thread_id, utime, stime)
|
||||
retlist.append(ntuple)
|
||||
# The underlying C implementation retrieves all OS threads
|
||||
# and filters them by PID. At this point we can't tell whether
|
||||
# an empty list means there were no connections for process or
|
||||
# process is no longer active so we force NSP in case the PID
|
||||
# is no longer there.
|
||||
if not retlist:
|
||||
# will raise NSP if process is gone
|
||||
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
||||
return retlist
|
||||
|
||||
@wrap_exceptions
|
||||
def connections(self, kind='inet'):
|
||||
ret = net_connections(kind, _pid=self.pid)
|
||||
# The underlying C implementation retrieves all OS connections
|
||||
# and filters them by PID. At this point we can't tell whether
|
||||
# an empty list means there were no connections for process or
|
||||
# process is no longer active so we force NSP in case the PID
|
||||
# is no longer there.
|
||||
if not ret:
|
||||
# will raise NSP if process is gone
|
||||
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
||||
return ret
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_get(self):
|
||||
return cext_posix.getpriority(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_set(self, value):
|
||||
return cext_posix.setpriority(self.pid, value)
|
||||
|
||||
@wrap_exceptions
|
||||
def ppid(self):
|
||||
self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
|
||||
return self._ppid
|
||||
|
||||
@wrap_exceptions
|
||||
def uids(self):
|
||||
real, effective, saved, _, _, _ = self._proc_cred()
|
||||
return _common.puids(real, effective, saved)
|
||||
|
||||
@wrap_exceptions
|
||||
def gids(self):
|
||||
_, _, _, real, effective, saved = self._proc_cred()
|
||||
return _common.puids(real, effective, saved)
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_times(self):
|
||||
cpu_times = cext.proc_cpu_times(self.pid, self._procfs_path)
|
||||
return _common.pcputimes(*cpu_times)
|
||||
|
||||
@wrap_exceptions
|
||||
def terminal(self):
|
||||
ttydev = self._proc_basic_info()[proc_info_map['ttynr']]
|
||||
# convert from 64-bit dev_t to 32-bit dev_t and then map the device
|
||||
ttydev = (((ttydev & 0x0000FFFF00000000) >> 16) | (ttydev & 0xFFFF))
|
||||
# try to match rdev of /dev/pts/* files ttydev
|
||||
for dev in glob.glob("/dev/**/*"):
|
||||
if os.stat(dev).st_rdev == ttydev:
|
||||
return dev
|
||||
return None
|
||||
|
||||
@wrap_exceptions
|
||||
def cwd(self):
|
||||
procfs_path = self._procfs_path
|
||||
try:
|
||||
result = os.readlink("%s/%s/cwd" % (procfs_path, self.pid))
|
||||
return result.rstrip('/')
|
||||
except OSError as err:
|
||||
if err.errno == errno.ENOENT:
|
||||
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
|
||||
return None
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_info(self):
|
||||
ret = self._proc_basic_info()
|
||||
rss = ret[proc_info_map['rss']] * 1024
|
||||
vms = ret[proc_info_map['vms']] * 1024
|
||||
return pmem(rss, vms)
|
||||
|
||||
memory_full_info = memory_info
|
||||
|
||||
@wrap_exceptions
|
||||
def status(self):
|
||||
code = self._proc_basic_info()[proc_info_map['status']]
|
||||
# XXX is '?' legit? (we're not supposed to return it anyway)
|
||||
return PROC_STATUSES.get(code, '?')
|
||||
|
||||
def open_files(self):
|
||||
# TODO rewrite without using procfiles (stat /proc/pid/fd/* and then
|
||||
# find matching name of the inode)
|
||||
p = subprocess.Popen(["/usr/bin/procfiles", "-n", str(self.pid)],
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
if PY3:
|
||||
stdout, stderr = [x.decode(sys.stdout.encoding)
|
||||
for x in (stdout, stderr)]
|
||||
if "no such process" in stderr.lower():
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
procfiles = re.findall("(\d+): S_IFREG.*\s*.*name:(.*)\n", stdout)
|
||||
retlist = []
|
||||
for fd, path in procfiles:
|
||||
path = path.strip()
|
||||
if path.startswith("//"):
|
||||
path = path[1:]
|
||||
if path.lower() == "cannot be retrieved":
|
||||
continue
|
||||
retlist.append(_common.popenfile(path, int(fd)))
|
||||
return retlist
|
||||
|
||||
@wrap_exceptions
|
||||
def num_fds(self):
|
||||
if self.pid == 0: # no /proc/0/fd
|
||||
return 0
|
||||
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
|
||||
|
||||
@wrap_exceptions
|
||||
def num_ctx_switches(self):
|
||||
return _common.pctxsw(
|
||||
*cext.proc_num_ctx_switches(self.pid))
|
||||
|
||||
@wrap_exceptions
|
||||
def wait(self, timeout=None):
|
||||
return _psposix.wait_pid(self.pid, timeout, self._name)
|
||||
|
||||
@wrap_exceptions
|
||||
def io_counters(self):
|
||||
try:
|
||||
rc, wc, rb, wb = cext.proc_io_counters(self.pid)
|
||||
except OSError:
|
||||
# if process is terminated, proc_io_counters returns OSError
|
||||
# instead of NSP
|
||||
if not pid_exists(self.pid):
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
raise
|
||||
return _common.pio(rc, wc, rb, wb)
|
|
@ -0,0 +1,873 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""FreeBSD, OpenBSD and NetBSD platforms implementation."""
|
||||
|
||||
import contextlib
|
||||
import errno
|
||||
import functools
|
||||
import os
|
||||
import xml.etree.ElementTree as ET
|
||||
from collections import namedtuple
|
||||
from socket import AF_INET
|
||||
|
||||
from . import _common
|
||||
from . import _psposix
|
||||
from . import _psutil_bsd as cext
|
||||
from . import _psutil_posix as cext_posix
|
||||
from ._common import AF_INET6
|
||||
from ._common import conn_tmap
|
||||
from ._common import FREEBSD
|
||||
from ._common import memoize
|
||||
from ._common import memoize_when_activated
|
||||
from ._common import NETBSD
|
||||
from ._common import OPENBSD
|
||||
from ._common import sockfam_to_enum
|
||||
from ._common import socktype_to_enum
|
||||
from ._common import usage_percent
|
||||
from ._compat import which
|
||||
from ._exceptions import AccessDenied
|
||||
from ._exceptions import NoSuchProcess
|
||||
from ._exceptions import ZombieProcess
|
||||
|
||||
__extra__all__ = []
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- globals
|
||||
# =====================================================================
|
||||
|
||||
|
||||
if FREEBSD:
|
||||
PROC_STATUSES = {
|
||||
cext.SIDL: _common.STATUS_IDLE,
|
||||
cext.SRUN: _common.STATUS_RUNNING,
|
||||
cext.SSLEEP: _common.STATUS_SLEEPING,
|
||||
cext.SSTOP: _common.STATUS_STOPPED,
|
||||
cext.SZOMB: _common.STATUS_ZOMBIE,
|
||||
cext.SWAIT: _common.STATUS_WAITING,
|
||||
cext.SLOCK: _common.STATUS_LOCKED,
|
||||
}
|
||||
elif OPENBSD or NETBSD:
|
||||
PROC_STATUSES = {
|
||||
cext.SIDL: _common.STATUS_IDLE,
|
||||
cext.SSLEEP: _common.STATUS_SLEEPING,
|
||||
cext.SSTOP: _common.STATUS_STOPPED,
|
||||
# According to /usr/include/sys/proc.h SZOMB is unused.
|
||||
# test_zombie_process() shows that SDEAD is the right
|
||||
# equivalent. Also it appears there's no equivalent of
|
||||
# psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE.
|
||||
# cext.SZOMB: _common.STATUS_ZOMBIE,
|
||||
cext.SDEAD: _common.STATUS_ZOMBIE,
|
||||
cext.SZOMB: _common.STATUS_ZOMBIE,
|
||||
# From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt
|
||||
# OpenBSD has SRUN and SONPROC: SRUN indicates that a process
|
||||
# is runnable but *not* yet running, i.e. is on a run queue.
|
||||
# SONPROC indicates that the process is actually executing on
|
||||
# a CPU, i.e. it is no longer on a run queue.
|
||||
# As such we'll map SRUN to STATUS_WAKING and SONPROC to
|
||||
# STATUS_RUNNING
|
||||
cext.SRUN: _common.STATUS_WAKING,
|
||||
cext.SONPROC: _common.STATUS_RUNNING,
|
||||
}
|
||||
elif NETBSD:
|
||||
PROC_STATUSES = {
|
||||
cext.SIDL: _common.STATUS_IDLE,
|
||||
cext.SACTIVE: _common.STATUS_RUNNING,
|
||||
cext.SDYING: _common.STATUS_ZOMBIE,
|
||||
cext.SSTOP: _common.STATUS_STOPPED,
|
||||
cext.SZOMB: _common.STATUS_ZOMBIE,
|
||||
cext.SDEAD: _common.STATUS_DEAD,
|
||||
cext.SSUSPENDED: _common.STATUS_SUSPENDED, # unique to NetBSD
|
||||
}
|
||||
|
||||
TCP_STATUSES = {
|
||||
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
||||
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
||||
cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
|
||||
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
||||
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
||||
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
||||
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
||||
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
||||
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
||||
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
||||
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
||||
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
||||
}
|
||||
|
||||
if NETBSD:
|
||||
PAGESIZE = os.sysconf("SC_PAGESIZE")
|
||||
else:
|
||||
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
|
||||
AF_LINK = cext_posix.AF_LINK
|
||||
|
||||
kinfo_proc_map = dict(
|
||||
ppid=0,
|
||||
status=1,
|
||||
real_uid=2,
|
||||
effective_uid=3,
|
||||
saved_uid=4,
|
||||
real_gid=5,
|
||||
effective_gid=6,
|
||||
saved_gid=7,
|
||||
ttynr=8,
|
||||
create_time=9,
|
||||
ctx_switches_vol=10,
|
||||
ctx_switches_unvol=11,
|
||||
read_io_count=12,
|
||||
write_io_count=13,
|
||||
user_time=14,
|
||||
sys_time=15,
|
||||
ch_user_time=16,
|
||||
ch_sys_time=17,
|
||||
rss=18,
|
||||
vms=19,
|
||||
memtext=20,
|
||||
memdata=21,
|
||||
memstack=22,
|
||||
cpunum=23,
|
||||
name=24,
|
||||
)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- named tuples
|
||||
# =====================================================================
|
||||
|
||||
|
||||
# psutil.virtual_memory()
|
||||
svmem = namedtuple(
|
||||
'svmem', ['total', 'available', 'percent', 'used', 'free',
|
||||
'active', 'inactive', 'buffers', 'cached', 'shared', 'wired'])
|
||||
# psutil.cpu_times()
|
||||
scputimes = namedtuple(
|
||||
'scputimes', ['user', 'nice', 'system', 'idle', 'irq'])
|
||||
# psutil.Process.memory_info()
|
||||
pmem = namedtuple('pmem', ['rss', 'vms', 'text', 'data', 'stack'])
|
||||
# psutil.Process.memory_full_info()
|
||||
pfullmem = pmem
|
||||
# psutil.Process.cpu_times()
|
||||
pcputimes = namedtuple('pcputimes',
|
||||
['user', 'system', 'children_user', 'children_system'])
|
||||
# psutil.Process.memory_maps(grouped=True)
|
||||
pmmap_grouped = namedtuple(
|
||||
'pmmap_grouped', 'path rss, private, ref_count, shadow_count')
|
||||
# psutil.Process.memory_maps(grouped=False)
|
||||
pmmap_ext = namedtuple(
|
||||
'pmmap_ext', 'addr, perms path rss, private, ref_count, shadow_count')
|
||||
# psutil.disk_io_counters()
|
||||
if FREEBSD:
|
||||
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
||||
'read_bytes', 'write_bytes',
|
||||
'read_time', 'write_time',
|
||||
'busy_time'])
|
||||
else:
|
||||
sdiskio = namedtuple('sdiskio', ['read_count', 'write_count',
|
||||
'read_bytes', 'write_bytes'])
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- memory
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def virtual_memory():
|
||||
"""System virtual memory as a namedtuple."""
|
||||
mem = cext.virtual_mem()
|
||||
total, free, active, inactive, wired, cached, buffers, shared = mem
|
||||
if NETBSD:
|
||||
# On NetBSD buffers and shared mem is determined via /proc.
|
||||
# The C ext set them to 0.
|
||||
with open('/proc/meminfo', 'rb') as f:
|
||||
for line in f:
|
||||
if line.startswith(b'Buffers:'):
|
||||
buffers = int(line.split()[1]) * 1024
|
||||
elif line.startswith(b'MemShared:'):
|
||||
shared = int(line.split()[1]) * 1024
|
||||
avail = inactive + cached + free
|
||||
used = active + wired + cached
|
||||
percent = usage_percent((total - avail), total, _round=1)
|
||||
return svmem(total, avail, percent, used, free,
|
||||
active, inactive, buffers, cached, shared, wired)
|
||||
|
||||
|
||||
def swap_memory():
|
||||
"""System swap memory as (total, used, free, sin, sout) namedtuple."""
|
||||
total, used, free, sin, sout = cext.swap_mem()
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return _common.sswap(total, used, free, percent, sin, sout)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- CPU
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def cpu_times():
|
||||
"""Return system per-CPU times as a namedtuple"""
|
||||
user, nice, system, idle, irq = cext.cpu_times()
|
||||
return scputimes(user, nice, system, idle, irq)
|
||||
|
||||
|
||||
if hasattr(cext, "per_cpu_times"):
|
||||
def per_cpu_times():
|
||||
"""Return system CPU times as a namedtuple"""
|
||||
ret = []
|
||||
for cpu_t in cext.per_cpu_times():
|
||||
user, nice, system, idle, irq = cpu_t
|
||||
item = scputimes(user, nice, system, idle, irq)
|
||||
ret.append(item)
|
||||
return ret
|
||||
else:
|
||||
# XXX
|
||||
# Ok, this is very dirty.
|
||||
# On FreeBSD < 8 we cannot gather per-cpu information, see:
|
||||
# https://github.com/giampaolo/psutil/issues/226
|
||||
# If num cpus > 1, on first call we return single cpu times to avoid a
|
||||
# crash at psutil import time.
|
||||
# Next calls will fail with NotImplementedError
|
||||
def per_cpu_times():
|
||||
"""Return system CPU times as a namedtuple"""
|
||||
if cpu_count_logical() == 1:
|
||||
return [cpu_times()]
|
||||
if per_cpu_times.__called__:
|
||||
raise NotImplementedError("supported only starting from FreeBSD 8")
|
||||
per_cpu_times.__called__ = True
|
||||
return [cpu_times()]
|
||||
|
||||
per_cpu_times.__called__ = False
|
||||
|
||||
|
||||
def cpu_count_logical():
|
||||
"""Return the number of logical CPUs in the system."""
|
||||
return cext.cpu_count_logical()
|
||||
|
||||
|
||||
if OPENBSD or NETBSD:
|
||||
def cpu_count_physical():
|
||||
# OpenBSD and NetBSD do not implement this.
|
||||
return 1 if cpu_count_logical() == 1 else None
|
||||
else:
|
||||
def cpu_count_physical():
|
||||
"""Return the number of physical CPUs in the system."""
|
||||
# From the C module we'll get an XML string similar to this:
|
||||
# http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html
|
||||
# We may get None in case "sysctl kern.sched.topology_spec"
|
||||
# is not supported on this BSD version, in which case we'll mimic
|
||||
# os.cpu_count() and return None.
|
||||
ret = None
|
||||
s = cext.cpu_count_phys()
|
||||
if s is not None:
|
||||
# get rid of padding chars appended at the end of the string
|
||||
index = s.rfind("</groups>")
|
||||
if index != -1:
|
||||
s = s[:index + 9]
|
||||
root = ET.fromstring(s)
|
||||
try:
|
||||
ret = len(root.findall('group/children/group/cpu')) or None
|
||||
finally:
|
||||
# needed otherwise it will memleak
|
||||
root.clear()
|
||||
if not ret:
|
||||
# If logical CPUs are 1 it's obvious we'll have only 1
|
||||
# physical CPU.
|
||||
if cpu_count_logical() == 1:
|
||||
return 1
|
||||
return ret
|
||||
|
||||
|
||||
def cpu_stats():
|
||||
"""Return various CPU stats as a named tuple."""
|
||||
if FREEBSD:
|
||||
# Note: the C ext is returning some metrics we are not exposing:
|
||||
# traps.
|
||||
ctxsw, intrs, soft_intrs, syscalls, traps = cext.cpu_stats()
|
||||
elif NETBSD:
|
||||
# XXX
|
||||
# Note about intrs: the C extension returns 0. intrs
|
||||
# can be determined via /proc/stat; it has the same value as
|
||||
# soft_intrs thought so the kernel is faking it (?).
|
||||
#
|
||||
# Note about syscalls: the C extension always sets it to 0 (?).
|
||||
#
|
||||
# Note: the C ext is returning some metrics we are not exposing:
|
||||
# traps, faults and forks.
|
||||
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \
|
||||
cext.cpu_stats()
|
||||
with open('/proc/stat', 'rb') as f:
|
||||
for line in f:
|
||||
if line.startswith(b'intr'):
|
||||
intrs = int(line.split()[1])
|
||||
elif OPENBSD:
|
||||
# Note: the C ext is returning some metrics we are not exposing:
|
||||
# traps, faults and forks.
|
||||
ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \
|
||||
cext.cpu_stats()
|
||||
return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- disks
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def disk_partitions(all=False):
|
||||
"""Return mounted disk partitions as a list of namedtuples.
|
||||
'all' argument is ignored, see:
|
||||
https://github.com/giampaolo/psutil/issues/906
|
||||
"""
|
||||
retlist = []
|
||||
partitions = cext.disk_partitions()
|
||||
for partition in partitions:
|
||||
device, mountpoint, fstype, opts = partition
|
||||
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
|
||||
retlist.append(ntuple)
|
||||
return retlist
|
||||
|
||||
|
||||
disk_usage = _psposix.disk_usage
|
||||
disk_io_counters = cext.disk_io_counters
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- network
|
||||
# =====================================================================
|
||||
|
||||
|
||||
net_io_counters = cext.net_io_counters
|
||||
net_if_addrs = cext_posix.net_if_addrs
|
||||
|
||||
|
||||
def net_if_stats():
|
||||
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
||||
names = net_io_counters().keys()
|
||||
ret = {}
|
||||
for name in names:
|
||||
mtu = cext_posix.net_if_mtu(name)
|
||||
isup = cext_posix.net_if_flags(name)
|
||||
duplex, speed = cext_posix.net_if_duplex_speed(name)
|
||||
if hasattr(_common, 'NicDuplex'):
|
||||
duplex = _common.NicDuplex(duplex)
|
||||
ret[name] = _common.snicstats(isup, duplex, speed, mtu)
|
||||
return ret
|
||||
|
||||
|
||||
def net_connections(kind):
|
||||
"""System-wide network connections."""
|
||||
if OPENBSD:
|
||||
ret = []
|
||||
for pid in pids():
|
||||
try:
|
||||
cons = Process(pid).connections(kind)
|
||||
except (NoSuchProcess, ZombieProcess):
|
||||
continue
|
||||
else:
|
||||
for conn in cons:
|
||||
conn = list(conn)
|
||||
conn.append(pid)
|
||||
ret.append(_common.sconn(*conn))
|
||||
return ret
|
||||
|
||||
if kind not in _common.conn_tmap:
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in conn_tmap])))
|
||||
families, types = conn_tmap[kind]
|
||||
ret = set()
|
||||
if NETBSD:
|
||||
rawlist = cext.net_connections(-1)
|
||||
else:
|
||||
rawlist = cext.net_connections()
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status, pid = item
|
||||
# TODO: apply filter at C level
|
||||
if fam in families and type in types:
|
||||
try:
|
||||
status = TCP_STATUSES[status]
|
||||
except KeyError:
|
||||
# XXX: Not sure why this happens. I saw this occurring
|
||||
# with IPv6 sockets opened by 'vim'. Those sockets
|
||||
# have a very short lifetime so maybe the kernel
|
||||
# can't initialize their status?
|
||||
status = TCP_STATUSES[cext.PSUTIL_CONN_NONE]
|
||||
if fam in (AF_INET, AF_INET6):
|
||||
if laddr:
|
||||
laddr = _common.addr(*laddr)
|
||||
if raddr:
|
||||
raddr = _common.addr(*raddr)
|
||||
fam = sockfam_to_enum(fam)
|
||||
type = socktype_to_enum(type)
|
||||
nt = _common.sconn(fd, fam, type, laddr, raddr, status, pid)
|
||||
ret.add(nt)
|
||||
return list(ret)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- sensors
|
||||
# =====================================================================
|
||||
|
||||
|
||||
if FREEBSD:
|
||||
|
||||
def sensors_battery():
|
||||
"""Return battery info."""
|
||||
try:
|
||||
percent, minsleft, power_plugged = cext.sensors_battery()
|
||||
except NotImplementedError:
|
||||
# See: https://github.com/giampaolo/psutil/issues/1074
|
||||
return None
|
||||
power_plugged = power_plugged == 1
|
||||
if power_plugged:
|
||||
secsleft = _common.POWER_TIME_UNLIMITED
|
||||
elif minsleft == -1:
|
||||
secsleft = _common.POWER_TIME_UNKNOWN
|
||||
else:
|
||||
secsleft = minsleft * 60
|
||||
return _common.sbattery(percent, secsleft, power_plugged)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- other system functions
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def boot_time():
|
||||
"""The system boot time expressed in seconds since the epoch."""
|
||||
return cext.boot_time()
|
||||
|
||||
|
||||
def users():
|
||||
"""Return currently connected users as a list of namedtuples."""
|
||||
retlist = []
|
||||
rawlist = cext.users()
|
||||
for item in rawlist:
|
||||
user, tty, hostname, tstamp, pid = item
|
||||
if pid == -1:
|
||||
assert OPENBSD
|
||||
pid = None
|
||||
if tty == '~':
|
||||
continue # reboot or shutdown
|
||||
nt = _common.suser(user, tty or None, hostname, tstamp, pid)
|
||||
retlist.append(nt)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- processes
|
||||
# =====================================================================
|
||||
|
||||
|
||||
@memoize
|
||||
def _pid_0_exists():
|
||||
try:
|
||||
Process(0).name()
|
||||
except NoSuchProcess:
|
||||
return False
|
||||
except AccessDenied:
|
||||
return True
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
def pids():
|
||||
"""Returns a list of PIDs currently running on the system."""
|
||||
ret = cext.pids()
|
||||
if OPENBSD and (0 not in ret) and _pid_0_exists():
|
||||
# On OpenBSD the kernel does not return PID 0 (neither does
|
||||
# ps) but it's actually querable (Process(0) will succeed).
|
||||
ret.insert(0, 0)
|
||||
return ret
|
||||
|
||||
|
||||
if OPENBSD or NETBSD:
|
||||
def pid_exists(pid):
|
||||
"""Return True if pid exists."""
|
||||
exists = _psposix.pid_exists(pid)
|
||||
if not exists:
|
||||
# We do this because _psposix.pid_exists() lies in case of
|
||||
# zombie processes.
|
||||
return pid in pids()
|
||||
else:
|
||||
return True
|
||||
else:
|
||||
pid_exists = _psposix.pid_exists
|
||||
|
||||
|
||||
def wrap_exceptions(fun):
|
||||
"""Decorator which translates bare OSError exceptions into
|
||||
NoSuchProcess and AccessDenied.
|
||||
"""
|
||||
@functools.wraps(fun)
|
||||
def wrapper(self, *args, **kwargs):
|
||||
try:
|
||||
return fun(self, *args, **kwargs)
|
||||
except OSError as err:
|
||||
if self.pid == 0:
|
||||
if 0 in pids():
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
else:
|
||||
raise
|
||||
if err.errno == errno.ESRCH:
|
||||
if not pid_exists(self.pid):
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
else:
|
||||
raise ZombieProcess(self.pid, self._name, self._ppid)
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def wrap_exceptions_procfs(inst):
|
||||
"""Same as above, for routines relying on reading /proc fs."""
|
||||
try:
|
||||
yield
|
||||
except EnvironmentError as err:
|
||||
# ENOENT (no such file or directory) gets raised on open().
|
||||
# ESRCH (no such process) can get raised on read() if
|
||||
# process is gone in meantime.
|
||||
if err.errno in (errno.ENOENT, errno.ESRCH):
|
||||
if not pid_exists(inst.pid):
|
||||
raise NoSuchProcess(inst.pid, inst._name)
|
||||
else:
|
||||
raise ZombieProcess(inst.pid, inst._name, inst._ppid)
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise AccessDenied(inst.pid, inst._name)
|
||||
raise
|
||||
|
||||
|
||||
class Process(object):
|
||||
"""Wrapper class around underlying C implementation."""
|
||||
|
||||
__slots__ = ["pid", "_name", "_ppid"]
|
||||
|
||||
def __init__(self, pid):
|
||||
self.pid = pid
|
||||
self._name = None
|
||||
self._ppid = None
|
||||
|
||||
@memoize_when_activated
|
||||
def oneshot(self):
|
||||
"""Retrieves multiple process info in one shot as a raw tuple."""
|
||||
ret = cext.proc_oneshot_info(self.pid)
|
||||
assert len(ret) == len(kinfo_proc_map)
|
||||
return ret
|
||||
|
||||
def oneshot_enter(self):
|
||||
self.oneshot.cache_activate()
|
||||
|
||||
def oneshot_exit(self):
|
||||
self.oneshot.cache_deactivate()
|
||||
|
||||
@wrap_exceptions
|
||||
def name(self):
|
||||
name = self.oneshot()[kinfo_proc_map['name']]
|
||||
return name if name is not None else cext.proc_name(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def exe(self):
|
||||
if FREEBSD:
|
||||
return cext.proc_exe(self.pid)
|
||||
elif NETBSD:
|
||||
if self.pid == 0:
|
||||
# /proc/0 dir exists but /proc/0/exe doesn't
|
||||
return ""
|
||||
with wrap_exceptions_procfs(self):
|
||||
return os.readlink("/proc/%s/exe" % self.pid)
|
||||
else:
|
||||
# OpenBSD: exe cannot be determined; references:
|
||||
# https://chromium.googlesource.com/chromium/src/base/+/
|
||||
# master/base_paths_posix.cc
|
||||
# We try our best guess by using which against the first
|
||||
# cmdline arg (may return None).
|
||||
cmdline = self.cmdline()
|
||||
if cmdline:
|
||||
return which(cmdline[0])
|
||||
else:
|
||||
return ""
|
||||
|
||||
@wrap_exceptions
|
||||
def cmdline(self):
|
||||
if OPENBSD and self.pid == 0:
|
||||
return [] # ...else it crashes
|
||||
elif NETBSD:
|
||||
# XXX - most of the times the underlying sysctl() call on Net
|
||||
# and Open BSD returns a truncated string.
|
||||
# Also /proc/pid/cmdline behaves the same so it looks
|
||||
# like this is a kernel bug.
|
||||
try:
|
||||
return cext.proc_cmdline(self.pid)
|
||||
except OSError as err:
|
||||
if err.errno == errno.EINVAL:
|
||||
if not pid_exists(self.pid):
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
else:
|
||||
raise ZombieProcess(self.pid, self._name, self._ppid)
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
return cext.proc_cmdline(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def terminal(self):
|
||||
tty_nr = self.oneshot()[kinfo_proc_map['ttynr']]
|
||||
tmap = _psposix.get_terminal_map()
|
||||
try:
|
||||
return tmap[tty_nr]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
@wrap_exceptions
|
||||
def ppid(self):
|
||||
self._ppid = self.oneshot()[kinfo_proc_map['ppid']]
|
||||
return self._ppid
|
||||
|
||||
@wrap_exceptions
|
||||
def uids(self):
|
||||
rawtuple = self.oneshot()
|
||||
return _common.puids(
|
||||
rawtuple[kinfo_proc_map['real_uid']],
|
||||
rawtuple[kinfo_proc_map['effective_uid']],
|
||||
rawtuple[kinfo_proc_map['saved_uid']])
|
||||
|
||||
@wrap_exceptions
|
||||
def gids(self):
|
||||
rawtuple = self.oneshot()
|
||||
return _common.pgids(
|
||||
rawtuple[kinfo_proc_map['real_gid']],
|
||||
rawtuple[kinfo_proc_map['effective_gid']],
|
||||
rawtuple[kinfo_proc_map['saved_gid']])
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_times(self):
|
||||
rawtuple = self.oneshot()
|
||||
return _common.pcputimes(
|
||||
rawtuple[kinfo_proc_map['user_time']],
|
||||
rawtuple[kinfo_proc_map['sys_time']],
|
||||
rawtuple[kinfo_proc_map['ch_user_time']],
|
||||
rawtuple[kinfo_proc_map['ch_sys_time']])
|
||||
|
||||
if FREEBSD:
|
||||
@wrap_exceptions
|
||||
def cpu_num(self):
|
||||
return self.oneshot()[kinfo_proc_map['cpunum']]
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_info(self):
|
||||
rawtuple = self.oneshot()
|
||||
return pmem(
|
||||
rawtuple[kinfo_proc_map['rss']],
|
||||
rawtuple[kinfo_proc_map['vms']],
|
||||
rawtuple[kinfo_proc_map['memtext']],
|
||||
rawtuple[kinfo_proc_map['memdata']],
|
||||
rawtuple[kinfo_proc_map['memstack']])
|
||||
|
||||
memory_full_info = memory_info
|
||||
|
||||
@wrap_exceptions
|
||||
def create_time(self):
|
||||
return self.oneshot()[kinfo_proc_map['create_time']]
|
||||
|
||||
@wrap_exceptions
|
||||
def num_threads(self):
|
||||
if hasattr(cext, "proc_num_threads"):
|
||||
# FreeBSD
|
||||
return cext.proc_num_threads(self.pid)
|
||||
else:
|
||||
return len(self.threads())
|
||||
|
||||
@wrap_exceptions
|
||||
def num_ctx_switches(self):
|
||||
rawtuple = self.oneshot()
|
||||
return _common.pctxsw(
|
||||
rawtuple[kinfo_proc_map['ctx_switches_vol']],
|
||||
rawtuple[kinfo_proc_map['ctx_switches_unvol']])
|
||||
|
||||
@wrap_exceptions
|
||||
def threads(self):
|
||||
# Note: on OpenSBD this (/dev/mem) requires root access.
|
||||
rawlist = cext.proc_threads(self.pid)
|
||||
retlist = []
|
||||
for thread_id, utime, stime in rawlist:
|
||||
ntuple = _common.pthread(thread_id, utime, stime)
|
||||
retlist.append(ntuple)
|
||||
if OPENBSD:
|
||||
# On OpenBSD the underlying C function does not raise NSP
|
||||
# in case the process is gone (and the returned list may
|
||||
# incomplete).
|
||||
self.name() # raise NSP if the process disappeared on us
|
||||
return retlist
|
||||
|
||||
@wrap_exceptions
|
||||
def connections(self, kind='inet'):
|
||||
if kind not in conn_tmap:
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in conn_tmap])))
|
||||
|
||||
if NETBSD:
|
||||
families, types = conn_tmap[kind]
|
||||
ret = set()
|
||||
rawlist = cext.net_connections(self.pid)
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status, pid = item
|
||||
assert pid == self.pid
|
||||
if fam in families and type in types:
|
||||
try:
|
||||
status = TCP_STATUSES[status]
|
||||
except KeyError:
|
||||
status = TCP_STATUSES[cext.PSUTIL_CONN_NONE]
|
||||
if fam in (AF_INET, AF_INET6):
|
||||
if laddr:
|
||||
laddr = _common.addr(*laddr)
|
||||
if raddr:
|
||||
raddr = _common.addr(*raddr)
|
||||
fam = sockfam_to_enum(fam)
|
||||
type = socktype_to_enum(type)
|
||||
nt = _common.pconn(fd, fam, type, laddr, raddr, status)
|
||||
ret.add(nt)
|
||||
# On NetBSD the underlying C function does not raise NSP
|
||||
# in case the process is gone (and the returned list may
|
||||
# incomplete).
|
||||
self.name() # raise NSP if the process disappeared on us
|
||||
return list(ret)
|
||||
|
||||
families, types = conn_tmap[kind]
|
||||
rawlist = cext.proc_connections(self.pid, families, types)
|
||||
ret = []
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status = item
|
||||
if fam in (AF_INET, AF_INET6):
|
||||
if laddr:
|
||||
laddr = _common.addr(*laddr)
|
||||
if raddr:
|
||||
raddr = _common.addr(*raddr)
|
||||
fam = sockfam_to_enum(fam)
|
||||
type = socktype_to_enum(type)
|
||||
status = TCP_STATUSES[status]
|
||||
nt = _common.pconn(fd, fam, type, laddr, raddr, status)
|
||||
ret.append(nt)
|
||||
if OPENBSD:
|
||||
# On OpenBSD the underlying C function does not raise NSP
|
||||
# in case the process is gone (and the returned list may
|
||||
# incomplete).
|
||||
self.name() # raise NSP if the process disappeared on us
|
||||
return ret
|
||||
|
||||
@wrap_exceptions
|
||||
def wait(self, timeout=None):
|
||||
return _psposix.wait_pid(self.pid, timeout, self._name)
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_get(self):
|
||||
return cext_posix.getpriority(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_set(self, value):
|
||||
return cext_posix.setpriority(self.pid, value)
|
||||
|
||||
@wrap_exceptions
|
||||
def status(self):
|
||||
code = self.oneshot()[kinfo_proc_map['status']]
|
||||
# XXX is '?' legit? (we're not supposed to return it anyway)
|
||||
return PROC_STATUSES.get(code, '?')
|
||||
|
||||
@wrap_exceptions
|
||||
def io_counters(self):
|
||||
rawtuple = self.oneshot()
|
||||
return _common.pio(
|
||||
rawtuple[kinfo_proc_map['read_io_count']],
|
||||
rawtuple[kinfo_proc_map['write_io_count']],
|
||||
-1,
|
||||
-1)
|
||||
|
||||
@wrap_exceptions
|
||||
def cwd(self):
|
||||
"""Return process current working directory."""
|
||||
# sometimes we get an empty string, in which case we turn
|
||||
# it into None
|
||||
if OPENBSD and self.pid == 0:
|
||||
return None # ...else it would raise EINVAL
|
||||
elif NETBSD:
|
||||
with wrap_exceptions_procfs(self):
|
||||
return os.readlink("/proc/%s/cwd" % self.pid)
|
||||
elif hasattr(cext, 'proc_open_files'):
|
||||
# FreeBSD < 8 does not support functions based on
|
||||
# kinfo_getfile() and kinfo_getvmmap()
|
||||
return cext.proc_cwd(self.pid) or None
|
||||
else:
|
||||
raise NotImplementedError(
|
||||
"supported only starting from FreeBSD 8" if
|
||||
FREEBSD else "")
|
||||
|
||||
nt_mmap_grouped = namedtuple(
|
||||
'mmap', 'path rss, private, ref_count, shadow_count')
|
||||
nt_mmap_ext = namedtuple(
|
||||
'mmap', 'addr, perms path rss, private, ref_count, shadow_count')
|
||||
|
||||
def _not_implemented(self):
|
||||
raise NotImplementedError
|
||||
|
||||
# FreeBSD < 8 does not support functions based on kinfo_getfile()
|
||||
# and kinfo_getvmmap()
|
||||
if hasattr(cext, 'proc_open_files'):
|
||||
@wrap_exceptions
|
||||
def open_files(self):
|
||||
"""Return files opened by process as a list of namedtuples."""
|
||||
rawlist = cext.proc_open_files(self.pid)
|
||||
return [_common.popenfile(path, fd) for path, fd in rawlist]
|
||||
else:
|
||||
open_files = _not_implemented
|
||||
|
||||
# FreeBSD < 8 does not support functions based on kinfo_getfile()
|
||||
# and kinfo_getvmmap()
|
||||
if hasattr(cext, 'proc_num_fds'):
|
||||
@wrap_exceptions
|
||||
def num_fds(self):
|
||||
"""Return the number of file descriptors opened by this process."""
|
||||
ret = cext.proc_num_fds(self.pid)
|
||||
if NETBSD:
|
||||
# On NetBSD the underlying C function does not raise NSP
|
||||
# in case the process is gone.
|
||||
self.name() # raise NSP if the process disappeared on us
|
||||
return ret
|
||||
else:
|
||||
num_fds = _not_implemented
|
||||
|
||||
# --- FreeBSD only APIs
|
||||
|
||||
if FREEBSD:
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_affinity_get(self):
|
||||
return cext.proc_cpu_affinity_get(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_affinity_set(self, cpus):
|
||||
# Pre-emptively check if CPUs are valid because the C
|
||||
# function has a weird behavior in case of invalid CPUs,
|
||||
# see: https://github.com/giampaolo/psutil/issues/586
|
||||
allcpus = tuple(range(len(per_cpu_times())))
|
||||
for cpu in cpus:
|
||||
if cpu not in allcpus:
|
||||
raise ValueError("invalid CPU #%i (choose between %s)"
|
||||
% (cpu, allcpus))
|
||||
try:
|
||||
cext.proc_cpu_affinity_set(self.pid, cpus)
|
||||
except OSError as err:
|
||||
# 'man cpuset_setaffinity' about EDEADLK:
|
||||
# <<the call would leave a thread without a valid CPU to run
|
||||
# on because the set does not overlap with the thread's
|
||||
# anonymous mask>>
|
||||
if err.errno in (errno.EINVAL, errno.EDEADLK):
|
||||
for cpu in cpus:
|
||||
if cpu not in allcpus:
|
||||
raise ValueError(
|
||||
"invalid CPU #%i (choose between %s)" % (
|
||||
cpu, allcpus))
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_maps(self):
|
||||
return cext.proc_memory_maps(self.pid)
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,571 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""OSX platform implementation."""
|
||||
|
||||
import contextlib
|
||||
import errno
|
||||
import functools
|
||||
import os
|
||||
from socket import AF_INET
|
||||
from collections import namedtuple
|
||||
|
||||
from . import _common
|
||||
from . import _psposix
|
||||
from . import _psutil_osx as cext
|
||||
from . import _psutil_posix as cext_posix
|
||||
from ._common import AF_INET6
|
||||
from ._common import conn_tmap
|
||||
from ._common import isfile_strict
|
||||
from ._common import memoize_when_activated
|
||||
from ._common import parse_environ_block
|
||||
from ._common import sockfam_to_enum
|
||||
from ._common import socktype_to_enum
|
||||
from ._common import usage_percent
|
||||
from ._exceptions import AccessDenied
|
||||
from ._exceptions import NoSuchProcess
|
||||
from ._exceptions import ZombieProcess
|
||||
|
||||
|
||||
__extra__all__ = []
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- globals
|
||||
# =====================================================================
|
||||
|
||||
|
||||
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
|
||||
AF_LINK = cext_posix.AF_LINK
|
||||
|
||||
TCP_STATUSES = {
|
||||
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
||||
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
||||
cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV,
|
||||
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
||||
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
||||
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
||||
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
||||
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
||||
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
||||
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
||||
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
||||
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
||||
}
|
||||
|
||||
PROC_STATUSES = {
|
||||
cext.SIDL: _common.STATUS_IDLE,
|
||||
cext.SRUN: _common.STATUS_RUNNING,
|
||||
cext.SSLEEP: _common.STATUS_SLEEPING,
|
||||
cext.SSTOP: _common.STATUS_STOPPED,
|
||||
cext.SZOMB: _common.STATUS_ZOMBIE,
|
||||
}
|
||||
|
||||
kinfo_proc_map = dict(
|
||||
ppid=0,
|
||||
ruid=1,
|
||||
euid=2,
|
||||
suid=3,
|
||||
rgid=4,
|
||||
egid=5,
|
||||
sgid=6,
|
||||
ttynr=7,
|
||||
ctime=8,
|
||||
status=9,
|
||||
name=10,
|
||||
)
|
||||
|
||||
pidtaskinfo_map = dict(
|
||||
cpuutime=0,
|
||||
cpustime=1,
|
||||
rss=2,
|
||||
vms=3,
|
||||
pfaults=4,
|
||||
pageins=5,
|
||||
numthreads=6,
|
||||
volctxsw=7,
|
||||
)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- named tuples
|
||||
# =====================================================================
|
||||
|
||||
|
||||
# psutil.cpu_times()
|
||||
scputimes = namedtuple('scputimes', ['user', 'nice', 'system', 'idle'])
|
||||
# psutil.virtual_memory()
|
||||
svmem = namedtuple(
|
||||
'svmem', ['total', 'available', 'percent', 'used', 'free',
|
||||
'active', 'inactive', 'wired'])
|
||||
# psutil.Process.memory_info()
|
||||
pmem = namedtuple('pmem', ['rss', 'vms', 'pfaults', 'pageins'])
|
||||
# psutil.Process.memory_full_info()
|
||||
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
|
||||
# psutil.Process.memory_maps(grouped=True)
|
||||
pmmap_grouped = namedtuple(
|
||||
'pmmap_grouped',
|
||||
'path rss private swapped dirtied ref_count shadow_depth')
|
||||
# psutil.Process.memory_maps(grouped=False)
|
||||
pmmap_ext = namedtuple(
|
||||
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- memory
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def virtual_memory():
|
||||
"""System virtual memory as a namedtuple."""
|
||||
total, active, inactive, wired, free = cext.virtual_mem()
|
||||
avail = inactive + free
|
||||
used = active + inactive + wired
|
||||
percent = usage_percent((total - avail), total, _round=1)
|
||||
return svmem(total, avail, percent, used, free,
|
||||
active, inactive, wired)
|
||||
|
||||
|
||||
def swap_memory():
|
||||
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
|
||||
total, used, free, sin, sout = cext.swap_mem()
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return _common.sswap(total, used, free, percent, sin, sout)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- CPU
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def cpu_times():
|
||||
"""Return system CPU times as a namedtuple."""
|
||||
user, nice, system, idle = cext.cpu_times()
|
||||
return scputimes(user, nice, system, idle)
|
||||
|
||||
|
||||
def per_cpu_times():
|
||||
"""Return system CPU times as a named tuple"""
|
||||
ret = []
|
||||
for cpu_t in cext.per_cpu_times():
|
||||
user, nice, system, idle = cpu_t
|
||||
item = scputimes(user, nice, system, idle)
|
||||
ret.append(item)
|
||||
return ret
|
||||
|
||||
|
||||
def cpu_count_logical():
|
||||
"""Return the number of logical CPUs in the system."""
|
||||
return cext.cpu_count_logical()
|
||||
|
||||
|
||||
def cpu_count_physical():
|
||||
"""Return the number of physical CPUs in the system."""
|
||||
return cext.cpu_count_phys()
|
||||
|
||||
|
||||
def cpu_stats():
|
||||
ctx_switches, interrupts, soft_interrupts, syscalls, traps = \
|
||||
cext.cpu_stats()
|
||||
return _common.scpustats(
|
||||
ctx_switches, interrupts, soft_interrupts, syscalls)
|
||||
|
||||
|
||||
def cpu_freq():
|
||||
"""Return CPU frequency.
|
||||
On OSX per-cpu frequency is not supported.
|
||||
Also, the returned frequency never changes, see:
|
||||
https://arstechnica.com/civis/viewtopic.php?f=19&t=465002
|
||||
"""
|
||||
curr, min_, max_ = cext.cpu_freq()
|
||||
return [_common.scpufreq(curr, min_, max_)]
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- disks
|
||||
# =====================================================================
|
||||
|
||||
|
||||
disk_usage = _psposix.disk_usage
|
||||
disk_io_counters = cext.disk_io_counters
|
||||
|
||||
|
||||
def disk_partitions(all=False):
|
||||
"""Return mounted disk partitions as a list of namedtuples."""
|
||||
retlist = []
|
||||
partitions = cext.disk_partitions()
|
||||
for partition in partitions:
|
||||
device, mountpoint, fstype, opts = partition
|
||||
if device == 'none':
|
||||
device = ''
|
||||
if not all:
|
||||
if not os.path.isabs(device) or not os.path.exists(device):
|
||||
continue
|
||||
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
|
||||
retlist.append(ntuple)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- sensors
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def sensors_battery():
|
||||
"""Return battery information.
|
||||
"""
|
||||
try:
|
||||
percent, minsleft, power_plugged = cext.sensors_battery()
|
||||
except NotImplementedError:
|
||||
# no power source - return None according to interface
|
||||
return None
|
||||
power_plugged = power_plugged == 1
|
||||
if power_plugged:
|
||||
secsleft = _common.POWER_TIME_UNLIMITED
|
||||
elif minsleft == -1:
|
||||
secsleft = _common.POWER_TIME_UNKNOWN
|
||||
else:
|
||||
secsleft = minsleft * 60
|
||||
return _common.sbattery(percent, secsleft, power_plugged)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- network
|
||||
# =====================================================================
|
||||
|
||||
|
||||
net_io_counters = cext.net_io_counters
|
||||
net_if_addrs = cext_posix.net_if_addrs
|
||||
|
||||
|
||||
def net_connections(kind='inet'):
|
||||
"""System-wide network connections."""
|
||||
# Note: on OSX this will fail with AccessDenied unless
|
||||
# the process is owned by root.
|
||||
ret = []
|
||||
for pid in pids():
|
||||
try:
|
||||
cons = Process(pid).connections(kind)
|
||||
except NoSuchProcess:
|
||||
continue
|
||||
else:
|
||||
if cons:
|
||||
for c in cons:
|
||||
c = list(c) + [pid]
|
||||
ret.append(_common.sconn(*c))
|
||||
return ret
|
||||
|
||||
|
||||
def net_if_stats():
|
||||
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
||||
names = net_io_counters().keys()
|
||||
ret = {}
|
||||
for name in names:
|
||||
mtu = cext_posix.net_if_mtu(name)
|
||||
isup = cext_posix.net_if_flags(name)
|
||||
duplex, speed = cext_posix.net_if_duplex_speed(name)
|
||||
if hasattr(_common, 'NicDuplex'):
|
||||
duplex = _common.NicDuplex(duplex)
|
||||
ret[name] = _common.snicstats(isup, duplex, speed, mtu)
|
||||
return ret
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- other system functions
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def boot_time():
|
||||
"""The system boot time expressed in seconds since the epoch."""
|
||||
return cext.boot_time()
|
||||
|
||||
|
||||
def users():
|
||||
"""Return currently connected users as a list of namedtuples."""
|
||||
retlist = []
|
||||
rawlist = cext.users()
|
||||
for item in rawlist:
|
||||
user, tty, hostname, tstamp, pid = item
|
||||
if tty == '~':
|
||||
continue # reboot or shutdown
|
||||
if not tstamp:
|
||||
continue
|
||||
nt = _common.suser(user, tty or None, hostname or None, tstamp, pid)
|
||||
retlist.append(nt)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- processes
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def pids():
|
||||
ls = cext.pids()
|
||||
if 0 not in ls:
|
||||
# On certain OSX versions pids() C doesn't return PID 0 but
|
||||
# "ps" does and the process is querable via sysctl():
|
||||
# https://travis-ci.org/giampaolo/psutil/jobs/309619941
|
||||
try:
|
||||
Process(0).create_time()
|
||||
ls.append(0)
|
||||
except NoSuchProcess:
|
||||
pass
|
||||
except AccessDenied:
|
||||
ls.append(0)
|
||||
return ls
|
||||
|
||||
|
||||
pid_exists = _psposix.pid_exists
|
||||
|
||||
|
||||
def wrap_exceptions(fun):
|
||||
"""Decorator which translates bare OSError exceptions into
|
||||
NoSuchProcess and AccessDenied.
|
||||
"""
|
||||
@functools.wraps(fun)
|
||||
def wrapper(self, *args, **kwargs):
|
||||
try:
|
||||
return fun(self, *args, **kwargs)
|
||||
except OSError as err:
|
||||
if err.errno == errno.ESRCH:
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def catch_zombie(proc):
|
||||
"""There are some poor C APIs which incorrectly raise ESRCH when
|
||||
the process is still alive or it's a zombie, or even RuntimeError
|
||||
(those who don't set errno). This is here in order to solve:
|
||||
https://github.com/giampaolo/psutil/issues/1044
|
||||
"""
|
||||
try:
|
||||
yield
|
||||
except (OSError, RuntimeError) as err:
|
||||
if isinstance(err, RuntimeError) or err.errno == errno.ESRCH:
|
||||
try:
|
||||
# status() is not supposed to lie and correctly detect
|
||||
# zombies so if it raises ESRCH it's true.
|
||||
status = proc.status()
|
||||
except NoSuchProcess:
|
||||
raise err
|
||||
else:
|
||||
if status == _common.STATUS_ZOMBIE:
|
||||
raise ZombieProcess(proc.pid, proc._name, proc._ppid)
|
||||
else:
|
||||
raise AccessDenied(proc.pid, proc._name)
|
||||
else:
|
||||
raise
|
||||
|
||||
|
||||
class Process(object):
|
||||
"""Wrapper class around underlying C implementation."""
|
||||
|
||||
__slots__ = ["pid", "_name", "_ppid"]
|
||||
|
||||
def __init__(self, pid):
|
||||
self.pid = pid
|
||||
self._name = None
|
||||
self._ppid = None
|
||||
|
||||
@memoize_when_activated
|
||||
def _get_kinfo_proc(self):
|
||||
# Note: should work with all PIDs without permission issues.
|
||||
ret = cext.proc_kinfo_oneshot(self.pid)
|
||||
assert len(ret) == len(kinfo_proc_map)
|
||||
return ret
|
||||
|
||||
@memoize_when_activated
|
||||
def _get_pidtaskinfo(self):
|
||||
# Note: should work for PIDs owned by user only.
|
||||
with catch_zombie(self):
|
||||
ret = cext.proc_pidtaskinfo_oneshot(self.pid)
|
||||
assert len(ret) == len(pidtaskinfo_map)
|
||||
return ret
|
||||
|
||||
def oneshot_enter(self):
|
||||
self._get_kinfo_proc.cache_activate()
|
||||
self._get_pidtaskinfo.cache_activate()
|
||||
|
||||
def oneshot_exit(self):
|
||||
self._get_kinfo_proc.cache_deactivate()
|
||||
self._get_pidtaskinfo.cache_deactivate()
|
||||
|
||||
@wrap_exceptions
|
||||
def name(self):
|
||||
name = self._get_kinfo_proc()[kinfo_proc_map['name']]
|
||||
return name if name is not None else cext.proc_name(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def exe(self):
|
||||
with catch_zombie(self):
|
||||
return cext.proc_exe(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def cmdline(self):
|
||||
with catch_zombie(self):
|
||||
return cext.proc_cmdline(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def environ(self):
|
||||
with catch_zombie(self):
|
||||
return parse_environ_block(cext.proc_environ(self.pid))
|
||||
|
||||
@wrap_exceptions
|
||||
def ppid(self):
|
||||
self._ppid = self._get_kinfo_proc()[kinfo_proc_map['ppid']]
|
||||
return self._ppid
|
||||
|
||||
@wrap_exceptions
|
||||
def cwd(self):
|
||||
with catch_zombie(self):
|
||||
return cext.proc_cwd(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def uids(self):
|
||||
rawtuple = self._get_kinfo_proc()
|
||||
return _common.puids(
|
||||
rawtuple[kinfo_proc_map['ruid']],
|
||||
rawtuple[kinfo_proc_map['euid']],
|
||||
rawtuple[kinfo_proc_map['suid']])
|
||||
|
||||
@wrap_exceptions
|
||||
def gids(self):
|
||||
rawtuple = self._get_kinfo_proc()
|
||||
return _common.puids(
|
||||
rawtuple[kinfo_proc_map['rgid']],
|
||||
rawtuple[kinfo_proc_map['egid']],
|
||||
rawtuple[kinfo_proc_map['sgid']])
|
||||
|
||||
@wrap_exceptions
|
||||
def terminal(self):
|
||||
tty_nr = self._get_kinfo_proc()[kinfo_proc_map['ttynr']]
|
||||
tmap = _psposix.get_terminal_map()
|
||||
try:
|
||||
return tmap[tty_nr]
|
||||
except KeyError:
|
||||
return None
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_info(self):
|
||||
rawtuple = self._get_pidtaskinfo()
|
||||
return pmem(
|
||||
rawtuple[pidtaskinfo_map['rss']],
|
||||
rawtuple[pidtaskinfo_map['vms']],
|
||||
rawtuple[pidtaskinfo_map['pfaults']],
|
||||
rawtuple[pidtaskinfo_map['pageins']],
|
||||
)
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_full_info(self):
|
||||
basic_mem = self.memory_info()
|
||||
uss = cext.proc_memory_uss(self.pid)
|
||||
return pfullmem(*basic_mem + (uss, ))
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_times(self):
|
||||
rawtuple = self._get_pidtaskinfo()
|
||||
return _common.pcputimes(
|
||||
rawtuple[pidtaskinfo_map['cpuutime']],
|
||||
rawtuple[pidtaskinfo_map['cpustime']],
|
||||
# children user / system times are not retrievable (set to 0)
|
||||
0.0, 0.0)
|
||||
|
||||
@wrap_exceptions
|
||||
def create_time(self):
|
||||
return self._get_kinfo_proc()[kinfo_proc_map['ctime']]
|
||||
|
||||
@wrap_exceptions
|
||||
def num_ctx_switches(self):
|
||||
# Unvoluntary value seems not to be available;
|
||||
# getrusage() numbers seems to confirm this theory.
|
||||
# We set it to 0.
|
||||
vol = self._get_pidtaskinfo()[pidtaskinfo_map['volctxsw']]
|
||||
return _common.pctxsw(vol, 0)
|
||||
|
||||
@wrap_exceptions
|
||||
def num_threads(self):
|
||||
return self._get_pidtaskinfo()[pidtaskinfo_map['numthreads']]
|
||||
|
||||
@wrap_exceptions
|
||||
def open_files(self):
|
||||
if self.pid == 0:
|
||||
return []
|
||||
files = []
|
||||
with catch_zombie(self):
|
||||
rawlist = cext.proc_open_files(self.pid)
|
||||
for path, fd in rawlist:
|
||||
if isfile_strict(path):
|
||||
ntuple = _common.popenfile(path, fd)
|
||||
files.append(ntuple)
|
||||
return files
|
||||
|
||||
@wrap_exceptions
|
||||
def connections(self, kind='inet'):
|
||||
if kind not in conn_tmap:
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in conn_tmap])))
|
||||
families, types = conn_tmap[kind]
|
||||
with catch_zombie(self):
|
||||
rawlist = cext.proc_connections(self.pid, families, types)
|
||||
ret = []
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status = item
|
||||
status = TCP_STATUSES[status]
|
||||
fam = sockfam_to_enum(fam)
|
||||
type = socktype_to_enum(type)
|
||||
if fam in (AF_INET, AF_INET6):
|
||||
if laddr:
|
||||
laddr = _common.addr(*laddr)
|
||||
if raddr:
|
||||
raddr = _common.addr(*raddr)
|
||||
nt = _common.pconn(fd, fam, type, laddr, raddr, status)
|
||||
ret.append(nt)
|
||||
return ret
|
||||
|
||||
@wrap_exceptions
|
||||
def num_fds(self):
|
||||
if self.pid == 0:
|
||||
return 0
|
||||
with catch_zombie(self):
|
||||
return cext.proc_num_fds(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def wait(self, timeout=None):
|
||||
return _psposix.wait_pid(self.pid, timeout, self._name)
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_get(self):
|
||||
with catch_zombie(self):
|
||||
return cext_posix.getpriority(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_set(self, value):
|
||||
with catch_zombie(self):
|
||||
return cext_posix.setpriority(self.pid, value)
|
||||
|
||||
@wrap_exceptions
|
||||
def status(self):
|
||||
code = self._get_kinfo_proc()[kinfo_proc_map['status']]
|
||||
# XXX is '?' legit? (we're not supposed to return it anyway)
|
||||
return PROC_STATUSES.get(code, '?')
|
||||
|
||||
@wrap_exceptions
|
||||
def threads(self):
|
||||
with catch_zombie(self):
|
||||
rawlist = cext.proc_threads(self.pid)
|
||||
retlist = []
|
||||
for thread_id, utime, stime in rawlist:
|
||||
ntuple = _common.pthread(thread_id, utime, stime)
|
||||
retlist.append(ntuple)
|
||||
return retlist
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_maps(self):
|
||||
with catch_zombie(self):
|
||||
return cext.proc_memory_maps(self.pid)
|
|
@ -0,0 +1,182 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Routines common to all posix systems."""
|
||||
|
||||
import errno
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
from ._common import memoize
|
||||
from ._common import sdiskusage
|
||||
from ._common import usage_percent
|
||||
from ._compat import PY3
|
||||
from ._compat import unicode
|
||||
from ._exceptions import TimeoutExpired
|
||||
|
||||
|
||||
__all__ = ['pid_exists', 'wait_pid', 'disk_usage', 'get_terminal_map']
|
||||
|
||||
|
||||
def pid_exists(pid):
|
||||
"""Check whether pid exists in the current process table."""
|
||||
if pid == 0:
|
||||
# According to "man 2 kill" PID 0 has a special meaning:
|
||||
# it refers to <<every process in the process group of the
|
||||
# calling process>> so we don't want to go any further.
|
||||
# If we get here it means this UNIX platform *does* have
|
||||
# a process with id 0.
|
||||
return True
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except OSError as err:
|
||||
if err.errno == errno.ESRCH:
|
||||
# ESRCH == No such process
|
||||
return False
|
||||
elif err.errno == errno.EPERM:
|
||||
# EPERM clearly means there's a process to deny access to
|
||||
return True
|
||||
else:
|
||||
# According to "man 2 kill" possible error values are
|
||||
# (EINVAL, EPERM, ESRCH) therefore we should never get
|
||||
# here. If we do let's be explicit in considering this
|
||||
# an error.
|
||||
raise err
|
||||
else:
|
||||
return True
|
||||
|
||||
|
||||
def wait_pid(pid, timeout=None, proc_name=None):
|
||||
"""Wait for process with pid 'pid' to terminate and return its
|
||||
exit status code as an integer.
|
||||
|
||||
If pid is not a children of os.getpid() (current process) just
|
||||
waits until the process disappears and return None.
|
||||
|
||||
If pid does not exist at all return None immediately.
|
||||
|
||||
Raise TimeoutExpired on timeout expired.
|
||||
"""
|
||||
def check_timeout(delay):
|
||||
if timeout is not None:
|
||||
if timer() >= stop_at:
|
||||
raise TimeoutExpired(timeout, pid=pid, name=proc_name)
|
||||
time.sleep(delay)
|
||||
return min(delay * 2, 0.04)
|
||||
|
||||
timer = getattr(time, 'monotonic', time.time)
|
||||
if timeout is not None:
|
||||
def waitcall():
|
||||
return os.waitpid(pid, os.WNOHANG)
|
||||
stop_at = timer() + timeout
|
||||
else:
|
||||
def waitcall():
|
||||
return os.waitpid(pid, 0)
|
||||
|
||||
delay = 0.0001
|
||||
while True:
|
||||
try:
|
||||
retpid, status = waitcall()
|
||||
except OSError as err:
|
||||
if err.errno == errno.EINTR:
|
||||
delay = check_timeout(delay)
|
||||
continue
|
||||
elif err.errno == errno.ECHILD:
|
||||
# This has two meanings:
|
||||
# - pid is not a child of os.getpid() in which case
|
||||
# we keep polling until it's gone
|
||||
# - pid never existed in the first place
|
||||
# In both cases we'll eventually return None as we
|
||||
# can't determine its exit status code.
|
||||
while True:
|
||||
if pid_exists(pid):
|
||||
delay = check_timeout(delay)
|
||||
else:
|
||||
return
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
if retpid == 0:
|
||||
# WNOHANG was used, pid is still running
|
||||
delay = check_timeout(delay)
|
||||
continue
|
||||
# process exited due to a signal; return the integer of
|
||||
# that signal
|
||||
if os.WIFSIGNALED(status):
|
||||
return -os.WTERMSIG(status)
|
||||
# process exited using exit(2) system call; return the
|
||||
# integer exit(2) system call has been called with
|
||||
elif os.WIFEXITED(status):
|
||||
return os.WEXITSTATUS(status)
|
||||
else:
|
||||
# should never happen
|
||||
raise ValueError("unknown process exit status %r" % status)
|
||||
|
||||
|
||||
def disk_usage(path):
|
||||
"""Return disk usage associated with path.
|
||||
Note: UNIX usually reserves 5% disk space which is not accessible
|
||||
by user. In this function "total" and "used" values reflect the
|
||||
total and used disk space whereas "free" and "percent" represent
|
||||
the "free" and "used percent" user disk space.
|
||||
"""
|
||||
if PY3:
|
||||
st = os.statvfs(path)
|
||||
else:
|
||||
# os.statvfs() does not support unicode on Python 2:
|
||||
# - https://github.com/giampaolo/psutil/issues/416
|
||||
# - http://bugs.python.org/issue18695
|
||||
try:
|
||||
st = os.statvfs(path)
|
||||
except UnicodeEncodeError:
|
||||
if isinstance(path, unicode):
|
||||
try:
|
||||
path = path.encode(sys.getfilesystemencoding())
|
||||
except UnicodeEncodeError:
|
||||
pass
|
||||
st = os.statvfs(path)
|
||||
else:
|
||||
raise
|
||||
|
||||
# Total space which is only available to root (unless changed
|
||||
# at system level).
|
||||
total = (st.f_blocks * st.f_frsize)
|
||||
# Remaining free space usable by root.
|
||||
avail_to_root = (st.f_bfree * st.f_frsize)
|
||||
# Remaining free space usable by user.
|
||||
avail_to_user = (st.f_bavail * st.f_frsize)
|
||||
# Total space being used in general.
|
||||
used = (total - avail_to_root)
|
||||
# Total space which is available to user (same as 'total' but
|
||||
# for the user).
|
||||
total_user = used + avail_to_user
|
||||
# User usage percent compared to the total amount of space
|
||||
# the user can use. This number would be higher if compared
|
||||
# to root's because the user has less space (usually -5%).
|
||||
usage_percent_user = usage_percent(used, total_user, _round=1)
|
||||
|
||||
# NB: the percentage is -5% than what shown by df due to
|
||||
# reserved blocks that we are currently not considering:
|
||||
# https://github.com/giampaolo/psutil/issues/829#issuecomment-223750462
|
||||
return sdiskusage(
|
||||
total=total, used=used, free=avail_to_user, percent=usage_percent_user)
|
||||
|
||||
|
||||
@memoize
|
||||
def get_terminal_map():
|
||||
"""Get a map of device-id -> path as a dict.
|
||||
Used by Process.terminal()
|
||||
"""
|
||||
ret = {}
|
||||
ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*')
|
||||
for name in ls:
|
||||
assert name not in ret, name
|
||||
try:
|
||||
ret[os.stat(name).st_rdev] = name
|
||||
except OSError as err:
|
||||
if err.errno != errno.ENOENT:
|
||||
raise
|
||||
return ret
|
|
@ -0,0 +1,725 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Sun OS Solaris platform implementation."""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import namedtuple
|
||||
from socket import AF_INET
|
||||
|
||||
from . import _common
|
||||
from . import _psposix
|
||||
from . import _psutil_posix as cext_posix
|
||||
from . import _psutil_sunos as cext
|
||||
from ._common import AF_INET6
|
||||
from ._common import isfile_strict
|
||||
from ._common import memoize_when_activated
|
||||
from ._common import sockfam_to_enum
|
||||
from ._common import socktype_to_enum
|
||||
from ._common import usage_percent
|
||||
from ._compat import b
|
||||
from ._compat import PY3
|
||||
from ._exceptions import AccessDenied
|
||||
from ._exceptions import NoSuchProcess
|
||||
from ._exceptions import ZombieProcess
|
||||
|
||||
|
||||
__extra__all__ = ["CONN_IDLE", "CONN_BOUND", "PROCFS_PATH"]
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- globals
|
||||
# =====================================================================
|
||||
|
||||
|
||||
PAGE_SIZE = os.sysconf('SC_PAGE_SIZE')
|
||||
AF_LINK = cext_posix.AF_LINK
|
||||
IS_64_BIT = sys.maxsize > 2**32
|
||||
|
||||
CONN_IDLE = "IDLE"
|
||||
CONN_BOUND = "BOUND"
|
||||
|
||||
PROC_STATUSES = {
|
||||
cext.SSLEEP: _common.STATUS_SLEEPING,
|
||||
cext.SRUN: _common.STATUS_RUNNING,
|
||||
cext.SZOMB: _common.STATUS_ZOMBIE,
|
||||
cext.SSTOP: _common.STATUS_STOPPED,
|
||||
cext.SIDL: _common.STATUS_IDLE,
|
||||
cext.SONPROC: _common.STATUS_RUNNING, # same as run
|
||||
cext.SWAIT: _common.STATUS_WAITING,
|
||||
}
|
||||
|
||||
TCP_STATUSES = {
|
||||
cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED,
|
||||
cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT,
|
||||
cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV,
|
||||
cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1,
|
||||
cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2,
|
||||
cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT,
|
||||
cext.TCPS_CLOSED: _common.CONN_CLOSE,
|
||||
cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
||||
cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK,
|
||||
cext.TCPS_LISTEN: _common.CONN_LISTEN,
|
||||
cext.TCPS_CLOSING: _common.CONN_CLOSING,
|
||||
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
||||
cext.TCPS_IDLE: CONN_IDLE, # sunos specific
|
||||
cext.TCPS_BOUND: CONN_BOUND, # sunos specific
|
||||
}
|
||||
|
||||
proc_info_map = dict(
|
||||
ppid=0,
|
||||
rss=1,
|
||||
vms=2,
|
||||
create_time=3,
|
||||
nice=4,
|
||||
num_threads=5,
|
||||
status=6,
|
||||
ttynr=7)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- named tuples
|
||||
# =====================================================================
|
||||
|
||||
|
||||
# psutil.cpu_times()
|
||||
scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait'])
|
||||
# psutil.cpu_times(percpu=True)
|
||||
pcputimes = namedtuple('pcputimes',
|
||||
['user', 'system', 'children_user', 'children_system'])
|
||||
# psutil.virtual_memory()
|
||||
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
|
||||
# psutil.Process.memory_info()
|
||||
pmem = namedtuple('pmem', ['rss', 'vms'])
|
||||
pfullmem = pmem
|
||||
# psutil.Process.memory_maps(grouped=True)
|
||||
pmmap_grouped = namedtuple('pmmap_grouped',
|
||||
['path', 'rss', 'anonymous', 'locked'])
|
||||
# psutil.Process.memory_maps(grouped=False)
|
||||
pmmap_ext = namedtuple(
|
||||
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- utils
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def get_procfs_path():
|
||||
"""Return updated psutil.PROCFS_PATH constant."""
|
||||
return sys.modules['psutil'].PROCFS_PATH
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- memory
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def virtual_memory():
|
||||
"""Report virtual memory metrics."""
|
||||
# we could have done this with kstat, but IMHO this is good enough
|
||||
total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE
|
||||
# note: there's no difference on Solaris
|
||||
free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE
|
||||
used = total - free
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return svmem(total, avail, percent, used, free)
|
||||
|
||||
|
||||
def swap_memory():
|
||||
"""Report swap memory metrics."""
|
||||
sin, sout = cext.swap_mem()
|
||||
# XXX
|
||||
# we are supposed to get total/free by doing so:
|
||||
# http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/
|
||||
# usr/src/cmd/swap/swap.c
|
||||
# ...nevertheless I can't manage to obtain the same numbers as 'swap'
|
||||
# cmdline utility, so let's parse its output (sigh!)
|
||||
p = subprocess.Popen(['/usr/bin/env', 'PATH=/usr/sbin:/sbin:%s' %
|
||||
os.environ['PATH'], 'swap', '-l'],
|
||||
stdout=subprocess.PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
if PY3:
|
||||
stdout = stdout.decode(sys.stdout.encoding)
|
||||
if p.returncode != 0:
|
||||
raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode)
|
||||
|
||||
lines = stdout.strip().split('\n')[1:]
|
||||
if not lines:
|
||||
raise RuntimeError('no swap device(s) configured')
|
||||
total = free = 0
|
||||
for line in lines:
|
||||
line = line.split()
|
||||
t, f = line[-2:]
|
||||
total += int(int(t) * 512)
|
||||
free += int(int(f) * 512)
|
||||
used = total - free
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return _common.sswap(total, used, free, percent,
|
||||
sin * PAGE_SIZE, sout * PAGE_SIZE)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- CPU
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def cpu_times():
|
||||
"""Return system-wide CPU times as a named tuple"""
|
||||
ret = cext.per_cpu_times()
|
||||
return scputimes(*[sum(x) for x in zip(*ret)])
|
||||
|
||||
|
||||
def per_cpu_times():
|
||||
"""Return system per-CPU times as a list of named tuples"""
|
||||
ret = cext.per_cpu_times()
|
||||
return [scputimes(*x) for x in ret]
|
||||
|
||||
|
||||
def cpu_count_logical():
|
||||
"""Return the number of logical CPUs in the system."""
|
||||
try:
|
||||
return os.sysconf("SC_NPROCESSORS_ONLN")
|
||||
except ValueError:
|
||||
# mimic os.cpu_count() behavior
|
||||
return None
|
||||
|
||||
|
||||
def cpu_count_physical():
|
||||
"""Return the number of physical CPUs in the system."""
|
||||
return cext.cpu_count_phys()
|
||||
|
||||
|
||||
def cpu_stats():
|
||||
"""Return various CPU stats as a named tuple."""
|
||||
ctx_switches, interrupts, syscalls, traps = cext.cpu_stats()
|
||||
soft_interrupts = 0
|
||||
return _common.scpustats(ctx_switches, interrupts, soft_interrupts,
|
||||
syscalls)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- disks
|
||||
# =====================================================================
|
||||
|
||||
|
||||
disk_io_counters = cext.disk_io_counters
|
||||
disk_usage = _psposix.disk_usage
|
||||
|
||||
|
||||
def disk_partitions(all=False):
|
||||
"""Return system disk partitions."""
|
||||
# TODO - the filtering logic should be better checked so that
|
||||
# it tries to reflect 'df' as much as possible
|
||||
retlist = []
|
||||
partitions = cext.disk_partitions()
|
||||
for partition in partitions:
|
||||
device, mountpoint, fstype, opts = partition
|
||||
if device == 'none':
|
||||
device = ''
|
||||
if not all:
|
||||
# Differently from, say, Linux, we don't have a list of
|
||||
# common fs types so the best we can do, AFAIK, is to
|
||||
# filter by filesystem having a total size > 0.
|
||||
if not disk_usage(mountpoint).total:
|
||||
continue
|
||||
ntuple = _common.sdiskpart(device, mountpoint, fstype, opts)
|
||||
retlist.append(ntuple)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- network
|
||||
# =====================================================================
|
||||
|
||||
|
||||
net_io_counters = cext.net_io_counters
|
||||
net_if_addrs = cext_posix.net_if_addrs
|
||||
|
||||
|
||||
def net_connections(kind, _pid=-1):
|
||||
"""Return socket connections. If pid == -1 return system-wide
|
||||
connections (as opposed to connections opened by one process only).
|
||||
Only INET sockets are returned (UNIX are not).
|
||||
"""
|
||||
cmap = _common.conn_tmap.copy()
|
||||
if _pid == -1:
|
||||
cmap.pop('unix', 0)
|
||||
if kind not in cmap:
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in cmap])))
|
||||
families, types = _common.conn_tmap[kind]
|
||||
rawlist = cext.net_connections(_pid)
|
||||
ret = set()
|
||||
for item in rawlist:
|
||||
fd, fam, type_, laddr, raddr, status, pid = item
|
||||
if fam not in families:
|
||||
continue
|
||||
if type_ not in types:
|
||||
continue
|
||||
if fam in (AF_INET, AF_INET6):
|
||||
if laddr:
|
||||
laddr = _common.addr(*laddr)
|
||||
if raddr:
|
||||
raddr = _common.addr(*raddr)
|
||||
status = TCP_STATUSES[status]
|
||||
fam = sockfam_to_enum(fam)
|
||||
type_ = socktype_to_enum(type_)
|
||||
if _pid == -1:
|
||||
nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid)
|
||||
else:
|
||||
nt = _common.pconn(fd, fam, type_, laddr, raddr, status)
|
||||
ret.add(nt)
|
||||
return list(ret)
|
||||
|
||||
|
||||
def net_if_stats():
|
||||
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
||||
ret = cext.net_if_stats()
|
||||
for name, items in ret.items():
|
||||
isup, duplex, speed, mtu = items
|
||||
if hasattr(_common, 'NicDuplex'):
|
||||
duplex = _common.NicDuplex(duplex)
|
||||
ret[name] = _common.snicstats(isup, duplex, speed, mtu)
|
||||
return ret
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- other system functions
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def boot_time():
|
||||
"""The system boot time expressed in seconds since the epoch."""
|
||||
return cext.boot_time()
|
||||
|
||||
|
||||
def users():
|
||||
"""Return currently connected users as a list of namedtuples."""
|
||||
retlist = []
|
||||
rawlist = cext.users()
|
||||
localhost = (':0.0', ':0')
|
||||
for item in rawlist:
|
||||
user, tty, hostname, tstamp, user_process, pid = item
|
||||
# note: the underlying C function includes entries about
|
||||
# system boot, run level and others. We might want
|
||||
# to use them in the future.
|
||||
if not user_process:
|
||||
continue
|
||||
if hostname in localhost:
|
||||
hostname = 'localhost'
|
||||
nt = _common.suser(user, tty, hostname, tstamp, pid)
|
||||
retlist.append(nt)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- processes
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def pids():
|
||||
"""Returns a list of PIDs currently running on the system."""
|
||||
return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()]
|
||||
|
||||
|
||||
def pid_exists(pid):
|
||||
"""Check for the existence of a unix pid."""
|
||||
return _psposix.pid_exists(pid)
|
||||
|
||||
|
||||
def wrap_exceptions(fun):
|
||||
"""Call callable into a try/except clause and translate ENOENT,
|
||||
EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
|
||||
"""
|
||||
|
||||
def wrapper(self, *args, **kwargs):
|
||||
try:
|
||||
return fun(self, *args, **kwargs)
|
||||
except EnvironmentError as err:
|
||||
if self.pid == 0:
|
||||
if 0 in pids():
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
else:
|
||||
raise
|
||||
# ENOENT (no such file or directory) gets raised on open().
|
||||
# ESRCH (no such process) can get raised on read() if
|
||||
# process is gone in meantime.
|
||||
if err.errno in (errno.ENOENT, errno.ESRCH):
|
||||
if not pid_exists(self.pid):
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
else:
|
||||
raise ZombieProcess(self.pid, self._name, self._ppid)
|
||||
if err.errno in (errno.EPERM, errno.EACCES):
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
class Process(object):
|
||||
"""Wrapper class around underlying C implementation."""
|
||||
|
||||
__slots__ = ["pid", "_name", "_ppid", "_procfs_path"]
|
||||
|
||||
def __init__(self, pid):
|
||||
self.pid = pid
|
||||
self._name = None
|
||||
self._ppid = None
|
||||
self._procfs_path = get_procfs_path()
|
||||
|
||||
def oneshot_enter(self):
|
||||
self._proc_name_and_args.cache_activate()
|
||||
self._proc_basic_info.cache_activate()
|
||||
self._proc_cred.cache_activate()
|
||||
|
||||
def oneshot_exit(self):
|
||||
self._proc_name_and_args.cache_deactivate()
|
||||
self._proc_basic_info.cache_deactivate()
|
||||
self._proc_cred.cache_deactivate()
|
||||
|
||||
@memoize_when_activated
|
||||
def _proc_name_and_args(self):
|
||||
return cext.proc_name_and_args(self.pid, self._procfs_path)
|
||||
|
||||
@memoize_when_activated
|
||||
def _proc_basic_info(self):
|
||||
ret = cext.proc_basic_info(self.pid, self._procfs_path)
|
||||
assert len(ret) == len(proc_info_map)
|
||||
return ret
|
||||
|
||||
@memoize_when_activated
|
||||
def _proc_cred(self):
|
||||
return cext.proc_cred(self.pid, self._procfs_path)
|
||||
|
||||
@wrap_exceptions
|
||||
def name(self):
|
||||
# note: max len == 15
|
||||
return self._proc_name_and_args()[0]
|
||||
|
||||
@wrap_exceptions
|
||||
def exe(self):
|
||||
try:
|
||||
return os.readlink(
|
||||
"%s/%s/path/a.out" % (self._procfs_path, self.pid))
|
||||
except OSError:
|
||||
pass # continue and guess the exe name from the cmdline
|
||||
# Will be guessed later from cmdline but we want to explicitly
|
||||
# invoke cmdline here in order to get an AccessDenied
|
||||
# exception if the user has not enough privileges.
|
||||
self.cmdline()
|
||||
return ""
|
||||
|
||||
@wrap_exceptions
|
||||
def cmdline(self):
|
||||
return self._proc_name_and_args()[1].split(' ')
|
||||
|
||||
@wrap_exceptions
|
||||
def environ(self):
|
||||
return cext.proc_environ(self.pid, self._procfs_path)
|
||||
|
||||
@wrap_exceptions
|
||||
def create_time(self):
|
||||
return self._proc_basic_info()[proc_info_map['create_time']]
|
||||
|
||||
@wrap_exceptions
|
||||
def num_threads(self):
|
||||
return self._proc_basic_info()[proc_info_map['num_threads']]
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_get(self):
|
||||
# Note #1: for some reason getpriority(3) return ESRCH (no such
|
||||
# process) for certain low-pid processes, no matter what (even
|
||||
# as root).
|
||||
# The process actually exists though, as it has a name,
|
||||
# creation time, etc.
|
||||
# The best thing we can do here appears to be raising AD.
|
||||
# Note: tested on Solaris 11; on Open Solaris 5 everything is
|
||||
# fine.
|
||||
#
|
||||
# Note #2: we also can get niceness from /proc/pid/psinfo
|
||||
# but it's wrong, see:
|
||||
# https://github.com/giampaolo/psutil/issues/1082
|
||||
try:
|
||||
return cext_posix.getpriority(self.pid)
|
||||
except EnvironmentError as err:
|
||||
# 48 is 'operation not supported' but errno does not expose
|
||||
# it. It occurs for low system pids.
|
||||
if err.errno in (errno.ENOENT, errno.ESRCH, 48):
|
||||
if pid_exists(self.pid):
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_set(self, value):
|
||||
if self.pid in (2, 3):
|
||||
# Special case PIDs: internally setpriority(3) return ESRCH
|
||||
# (no such process), no matter what.
|
||||
# The process actually exists though, as it has a name,
|
||||
# creation time, etc.
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
return cext_posix.setpriority(self.pid, value)
|
||||
|
||||
@wrap_exceptions
|
||||
def ppid(self):
|
||||
self._ppid = self._proc_basic_info()[proc_info_map['ppid']]
|
||||
return self._ppid
|
||||
|
||||
@wrap_exceptions
|
||||
def uids(self):
|
||||
real, effective, saved, _, _, _ = self._proc_cred()
|
||||
return _common.puids(real, effective, saved)
|
||||
|
||||
@wrap_exceptions
|
||||
def gids(self):
|
||||
_, _, _, real, effective, saved = self._proc_cred()
|
||||
return _common.puids(real, effective, saved)
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_times(self):
|
||||
try:
|
||||
times = cext.proc_cpu_times(self.pid, self._procfs_path)
|
||||
except OSError as err:
|
||||
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
|
||||
# We may get here if we attempt to query a 64bit process
|
||||
# with a 32bit python.
|
||||
# Error originates from read() and also tools like "cat"
|
||||
# fail in the same way (!).
|
||||
# Since there simply is no way to determine CPU times we
|
||||
# return 0.0 as a fallback. See:
|
||||
# https://github.com/giampaolo/psutil/issues/857
|
||||
times = (0.0, 0.0, 0.0, 0.0)
|
||||
else:
|
||||
raise
|
||||
return _common.pcputimes(*times)
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_num(self):
|
||||
return cext.proc_cpu_num(self.pid, self._procfs_path)
|
||||
|
||||
@wrap_exceptions
|
||||
def terminal(self):
|
||||
procfs_path = self._procfs_path
|
||||
hit_enoent = False
|
||||
tty = wrap_exceptions(
|
||||
self._proc_basic_info()[proc_info_map['ttynr']])
|
||||
if tty != cext.PRNODEV:
|
||||
for x in (0, 1, 2, 255):
|
||||
try:
|
||||
return os.readlink(
|
||||
'%s/%d/path/%d' % (procfs_path, self.pid, x))
|
||||
except OSError as err:
|
||||
if err.errno == errno.ENOENT:
|
||||
hit_enoent = True
|
||||
continue
|
||||
raise
|
||||
if hit_enoent:
|
||||
# raise NSP if the process disappeared on us
|
||||
os.stat('%s/%s' % (procfs_path, self.pid))
|
||||
|
||||
@wrap_exceptions
|
||||
def cwd(self):
|
||||
# /proc/PID/path/cwd may not be resolved by readlink() even if
|
||||
# it exists (ls shows it). If that's the case and the process
|
||||
# is still alive return None (we can return None also on BSD).
|
||||
# Reference: http://goo.gl/55XgO
|
||||
procfs_path = self._procfs_path
|
||||
try:
|
||||
return os.readlink("%s/%s/path/cwd" % (procfs_path, self.pid))
|
||||
except OSError as err:
|
||||
if err.errno == errno.ENOENT:
|
||||
os.stat("%s/%s" % (procfs_path, self.pid)) # raise NSP or AD
|
||||
return None
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_info(self):
|
||||
ret = self._proc_basic_info()
|
||||
rss = ret[proc_info_map['rss']] * 1024
|
||||
vms = ret[proc_info_map['vms']] * 1024
|
||||
return pmem(rss, vms)
|
||||
|
||||
memory_full_info = memory_info
|
||||
|
||||
@wrap_exceptions
|
||||
def status(self):
|
||||
code = self._proc_basic_info()[proc_info_map['status']]
|
||||
# XXX is '?' legit? (we're not supposed to return it anyway)
|
||||
return PROC_STATUSES.get(code, '?')
|
||||
|
||||
@wrap_exceptions
|
||||
def threads(self):
|
||||
procfs_path = self._procfs_path
|
||||
ret = []
|
||||
tids = os.listdir('%s/%d/lwp' % (procfs_path, self.pid))
|
||||
hit_enoent = False
|
||||
for tid in tids:
|
||||
tid = int(tid)
|
||||
try:
|
||||
utime, stime = cext.query_process_thread(
|
||||
self.pid, tid, procfs_path)
|
||||
except EnvironmentError as err:
|
||||
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
|
||||
# We may get here if we attempt to query a 64bit process
|
||||
# with a 32bit python.
|
||||
# Error originates from read() and also tools like "cat"
|
||||
# fail in the same way (!).
|
||||
# Since there simply is no way to determine CPU times we
|
||||
# return 0.0 as a fallback. See:
|
||||
# https://github.com/giampaolo/psutil/issues/857
|
||||
continue
|
||||
# ENOENT == thread gone in meantime
|
||||
if err.errno == errno.ENOENT:
|
||||
hit_enoent = True
|
||||
continue
|
||||
raise
|
||||
else:
|
||||
nt = _common.pthread(tid, utime, stime)
|
||||
ret.append(nt)
|
||||
if hit_enoent:
|
||||
# raise NSP if the process disappeared on us
|
||||
os.stat('%s/%s' % (procfs_path, self.pid))
|
||||
return ret
|
||||
|
||||
@wrap_exceptions
|
||||
def open_files(self):
|
||||
retlist = []
|
||||
hit_enoent = False
|
||||
procfs_path = self._procfs_path
|
||||
pathdir = '%s/%d/path' % (procfs_path, self.pid)
|
||||
for fd in os.listdir('%s/%d/fd' % (procfs_path, self.pid)):
|
||||
path = os.path.join(pathdir, fd)
|
||||
if os.path.islink(path):
|
||||
try:
|
||||
file = os.readlink(path)
|
||||
except OSError as err:
|
||||
# ENOENT == file which is gone in the meantime
|
||||
if err.errno == errno.ENOENT:
|
||||
hit_enoent = True
|
||||
continue
|
||||
raise
|
||||
else:
|
||||
if isfile_strict(file):
|
||||
retlist.append(_common.popenfile(file, int(fd)))
|
||||
if hit_enoent:
|
||||
# raise NSP if the process disappeared on us
|
||||
os.stat('%s/%s' % (procfs_path, self.pid))
|
||||
return retlist
|
||||
|
||||
def _get_unix_sockets(self, pid):
|
||||
"""Get UNIX sockets used by process by parsing 'pfiles' output."""
|
||||
# TODO: rewrite this in C (...but the damn netstat source code
|
||||
# does not include this part! Argh!!)
|
||||
cmd = "pfiles %s" % pid
|
||||
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
stdout, stderr = p.communicate()
|
||||
if PY3:
|
||||
stdout, stderr = [x.decode(sys.stdout.encoding)
|
||||
for x in (stdout, stderr)]
|
||||
if p.returncode != 0:
|
||||
if 'permission denied' in stderr.lower():
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
if 'no such process' in stderr.lower():
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
raise RuntimeError("%r command error\n%s" % (cmd, stderr))
|
||||
|
||||
lines = stdout.split('\n')[2:]
|
||||
for i, line in enumerate(lines):
|
||||
line = line.lstrip()
|
||||
if line.startswith('sockname: AF_UNIX'):
|
||||
path = line.split(' ', 2)[2]
|
||||
type = lines[i - 2].strip()
|
||||
if type == 'SOCK_STREAM':
|
||||
type = socket.SOCK_STREAM
|
||||
elif type == 'SOCK_DGRAM':
|
||||
type = socket.SOCK_DGRAM
|
||||
else:
|
||||
type = -1
|
||||
yield (-1, socket.AF_UNIX, type, path, "", _common.CONN_NONE)
|
||||
|
||||
@wrap_exceptions
|
||||
def connections(self, kind='inet'):
|
||||
ret = net_connections(kind, _pid=self.pid)
|
||||
# The underlying C implementation retrieves all OS connections
|
||||
# and filters them by PID. At this point we can't tell whether
|
||||
# an empty list means there were no connections for process or
|
||||
# process is no longer active so we force NSP in case the PID
|
||||
# is no longer there.
|
||||
if not ret:
|
||||
# will raise NSP if process is gone
|
||||
os.stat('%s/%s' % (self._procfs_path, self.pid))
|
||||
|
||||
# UNIX sockets
|
||||
if kind in ('all', 'unix'):
|
||||
ret.extend([_common.pconn(*conn) for conn in
|
||||
self._get_unix_sockets(self.pid)])
|
||||
return ret
|
||||
|
||||
nt_mmap_grouped = namedtuple('mmap', 'path rss anon locked')
|
||||
nt_mmap_ext = namedtuple('mmap', 'addr perms path rss anon locked')
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_maps(self):
|
||||
def toaddr(start, end):
|
||||
return '%s-%s' % (hex(start)[2:].strip('L'),
|
||||
hex(end)[2:].strip('L'))
|
||||
|
||||
procfs_path = self._procfs_path
|
||||
retlist = []
|
||||
try:
|
||||
rawlist = cext.proc_memory_maps(self.pid, procfs_path)
|
||||
except OSError as err:
|
||||
if err.errno == errno.EOVERFLOW and not IS_64_BIT:
|
||||
# We may get here if we attempt to query a 64bit process
|
||||
# with a 32bit python.
|
||||
# Error originates from read() and also tools like "cat"
|
||||
# fail in the same way (!).
|
||||
# Since there simply is no way to determine CPU times we
|
||||
# return 0.0 as a fallback. See:
|
||||
# https://github.com/giampaolo/psutil/issues/857
|
||||
return []
|
||||
else:
|
||||
raise
|
||||
hit_enoent = False
|
||||
for item in rawlist:
|
||||
addr, addrsize, perm, name, rss, anon, locked = item
|
||||
addr = toaddr(addr, addrsize)
|
||||
if not name.startswith('['):
|
||||
try:
|
||||
name = os.readlink(
|
||||
'%s/%s/path/%s' % (procfs_path, self.pid, name))
|
||||
except OSError as err:
|
||||
if err.errno == errno.ENOENT:
|
||||
# sometimes the link may not be resolved by
|
||||
# readlink() even if it exists (ls shows it).
|
||||
# If that's the case we just return the
|
||||
# unresolved link path.
|
||||
# This seems an incosistency with /proc similar
|
||||
# to: http://goo.gl/55XgO
|
||||
name = '%s/%s/path/%s' % (procfs_path, self.pid, name)
|
||||
hit_enoent = True
|
||||
else:
|
||||
raise
|
||||
retlist.append((addr, perm, name, rss, anon, locked))
|
||||
if hit_enoent:
|
||||
# raise NSP if the process disappeared on us
|
||||
os.stat('%s/%s' % (procfs_path, self.pid))
|
||||
return retlist
|
||||
|
||||
@wrap_exceptions
|
||||
def num_fds(self):
|
||||
return len(os.listdir("%s/%s/fd" % (self._procfs_path, self.pid)))
|
||||
|
||||
@wrap_exceptions
|
||||
def num_ctx_switches(self):
|
||||
return _common.pctxsw(
|
||||
*cext.proc_num_ctx_switches(self.pid, self._procfs_path))
|
||||
|
||||
@wrap_exceptions
|
||||
def wait(self, timeout=None):
|
||||
return _psposix.wait_pid(self.pid, timeout, self._name)
|
|
@ -0,0 +1,993 @@
|
|||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Windows platform implementation."""
|
||||
|
||||
import contextlib
|
||||
import errno
|
||||
import functools
|
||||
import os
|
||||
import sys
|
||||
from collections import namedtuple
|
||||
|
||||
from . import _common
|
||||
try:
|
||||
from . import _psutil_windows as cext
|
||||
except ImportError as err:
|
||||
if str(err).lower().startswith("dll load failed") and \
|
||||
sys.getwindowsversion()[0] < 6:
|
||||
# We may get here if:
|
||||
# 1) we are on an old Windows version
|
||||
# 2) psutil was installed via pip + wheel
|
||||
# See: https://github.com/giampaolo/psutil/issues/811
|
||||
# It must be noted that psutil can still (kind of) work
|
||||
# on outdated systems if compiled / installed from sources,
|
||||
# but if we get here it means this this was a wheel (or exe).
|
||||
msg = "this Windows version is too old (< Windows Vista); "
|
||||
msg += "psutil 3.4.2 is the latest version which supports Windows "
|
||||
msg += "2000, XP and 2003 server; it may be possible that psutil "
|
||||
msg += "will work if compiled from sources though"
|
||||
raise RuntimeError(msg)
|
||||
else:
|
||||
raise
|
||||
|
||||
from ._common import conn_tmap
|
||||
from ._common import ENCODING
|
||||
from ._common import ENCODING_ERRS
|
||||
from ._common import isfile_strict
|
||||
from ._common import memoize_when_activated
|
||||
from ._common import parse_environ_block
|
||||
from ._common import sockfam_to_enum
|
||||
from ._common import socktype_to_enum
|
||||
from ._common import usage_percent
|
||||
from ._compat import long
|
||||
from ._compat import lru_cache
|
||||
from ._compat import PY3
|
||||
from ._compat import unicode
|
||||
from ._compat import xrange
|
||||
from ._exceptions import AccessDenied
|
||||
from ._exceptions import NoSuchProcess
|
||||
from ._exceptions import TimeoutExpired
|
||||
from ._psutil_windows import ABOVE_NORMAL_PRIORITY_CLASS
|
||||
from ._psutil_windows import BELOW_NORMAL_PRIORITY_CLASS
|
||||
from ._psutil_windows import HIGH_PRIORITY_CLASS
|
||||
from ._psutil_windows import IDLE_PRIORITY_CLASS
|
||||
from ._psutil_windows import NORMAL_PRIORITY_CLASS
|
||||
from ._psutil_windows import REALTIME_PRIORITY_CLASS
|
||||
|
||||
if sys.version_info >= (3, 4):
|
||||
import enum
|
||||
else:
|
||||
enum = None
|
||||
|
||||
# process priority constants, import from __init__.py:
|
||||
# http://msdn.microsoft.com/en-us/library/ms686219(v=vs.85).aspx
|
||||
__extra__all__ = [
|
||||
"win_service_iter", "win_service_get",
|
||||
"ABOVE_NORMAL_PRIORITY_CLASS", "BELOW_NORMAL_PRIORITY_CLASS",
|
||||
"HIGH_PRIORITY_CLASS", "IDLE_PRIORITY_CLASS",
|
||||
"NORMAL_PRIORITY_CLASS", "REALTIME_PRIORITY_CLASS",
|
||||
"CONN_DELETE_TCB",
|
||||
"AF_LINK",
|
||||
]
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- globals
|
||||
# =====================================================================
|
||||
|
||||
CONN_DELETE_TCB = "DELETE_TCB"
|
||||
WAIT_TIMEOUT = 0x00000102 # 258 in decimal
|
||||
ACCESS_DENIED_ERRSET = frozenset([errno.EPERM, errno.EACCES,
|
||||
cext.ERROR_ACCESS_DENIED])
|
||||
NO_SUCH_SERVICE_ERRSET = frozenset([cext.ERROR_INVALID_NAME,
|
||||
cext.ERROR_SERVICE_DOES_NOT_EXIST])
|
||||
|
||||
|
||||
if enum is None:
|
||||
AF_LINK = -1
|
||||
else:
|
||||
AddressFamily = enum.IntEnum('AddressFamily', {'AF_LINK': -1})
|
||||
AF_LINK = AddressFamily.AF_LINK
|
||||
|
||||
TCP_STATUSES = {
|
||||
cext.MIB_TCP_STATE_ESTAB: _common.CONN_ESTABLISHED,
|
||||
cext.MIB_TCP_STATE_SYN_SENT: _common.CONN_SYN_SENT,
|
||||
cext.MIB_TCP_STATE_SYN_RCVD: _common.CONN_SYN_RECV,
|
||||
cext.MIB_TCP_STATE_FIN_WAIT1: _common.CONN_FIN_WAIT1,
|
||||
cext.MIB_TCP_STATE_FIN_WAIT2: _common.CONN_FIN_WAIT2,
|
||||
cext.MIB_TCP_STATE_TIME_WAIT: _common.CONN_TIME_WAIT,
|
||||
cext.MIB_TCP_STATE_CLOSED: _common.CONN_CLOSE,
|
||||
cext.MIB_TCP_STATE_CLOSE_WAIT: _common.CONN_CLOSE_WAIT,
|
||||
cext.MIB_TCP_STATE_LAST_ACK: _common.CONN_LAST_ACK,
|
||||
cext.MIB_TCP_STATE_LISTEN: _common.CONN_LISTEN,
|
||||
cext.MIB_TCP_STATE_CLOSING: _common.CONN_CLOSING,
|
||||
cext.MIB_TCP_STATE_DELETE_TCB: CONN_DELETE_TCB,
|
||||
cext.PSUTIL_CONN_NONE: _common.CONN_NONE,
|
||||
}
|
||||
|
||||
if enum is not None:
|
||||
class Priority(enum.IntEnum):
|
||||
ABOVE_NORMAL_PRIORITY_CLASS = ABOVE_NORMAL_PRIORITY_CLASS
|
||||
BELOW_NORMAL_PRIORITY_CLASS = BELOW_NORMAL_PRIORITY_CLASS
|
||||
HIGH_PRIORITY_CLASS = HIGH_PRIORITY_CLASS
|
||||
IDLE_PRIORITY_CLASS = IDLE_PRIORITY_CLASS
|
||||
NORMAL_PRIORITY_CLASS = NORMAL_PRIORITY_CLASS
|
||||
REALTIME_PRIORITY_CLASS = REALTIME_PRIORITY_CLASS
|
||||
|
||||
globals().update(Priority.__members__)
|
||||
|
||||
pinfo_map = dict(
|
||||
num_handles=0,
|
||||
ctx_switches=1,
|
||||
user_time=2,
|
||||
kernel_time=3,
|
||||
create_time=4,
|
||||
num_threads=5,
|
||||
io_rcount=6,
|
||||
io_wcount=7,
|
||||
io_rbytes=8,
|
||||
io_wbytes=9,
|
||||
io_count_others=10,
|
||||
io_bytes_others=11,
|
||||
num_page_faults=12,
|
||||
peak_wset=13,
|
||||
wset=14,
|
||||
peak_paged_pool=15,
|
||||
paged_pool=16,
|
||||
peak_non_paged_pool=17,
|
||||
non_paged_pool=18,
|
||||
pagefile=19,
|
||||
peak_pagefile=20,
|
||||
mem_private=21,
|
||||
)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- named tuples
|
||||
# =====================================================================
|
||||
|
||||
|
||||
# psutil.cpu_times()
|
||||
scputimes = namedtuple('scputimes',
|
||||
['user', 'system', 'idle', 'interrupt', 'dpc'])
|
||||
# psutil.virtual_memory()
|
||||
svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free'])
|
||||
# psutil.Process.memory_info()
|
||||
pmem = namedtuple(
|
||||
'pmem', ['rss', 'vms',
|
||||
'num_page_faults', 'peak_wset', 'wset', 'peak_paged_pool',
|
||||
'paged_pool', 'peak_nonpaged_pool', 'nonpaged_pool',
|
||||
'pagefile', 'peak_pagefile', 'private'])
|
||||
# psutil.Process.memory_full_info()
|
||||
pfullmem = namedtuple('pfullmem', pmem._fields + ('uss', ))
|
||||
# psutil.Process.memory_maps(grouped=True)
|
||||
pmmap_grouped = namedtuple('pmmap_grouped', ['path', 'rss'])
|
||||
# psutil.Process.memory_maps(grouped=False)
|
||||
pmmap_ext = namedtuple(
|
||||
'pmmap_ext', 'addr perms ' + ' '.join(pmmap_grouped._fields))
|
||||
# psutil.Process.io_counters()
|
||||
pio = namedtuple('pio', ['read_count', 'write_count',
|
||||
'read_bytes', 'write_bytes',
|
||||
'other_count', 'other_bytes'])
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- utils
|
||||
# =====================================================================
|
||||
|
||||
|
||||
@lru_cache(maxsize=512)
|
||||
def convert_dos_path(s):
|
||||
r"""Convert paths using native DOS format like:
|
||||
"\Device\HarddiskVolume1\Windows\systemew\file.txt"
|
||||
into:
|
||||
"C:\Windows\systemew\file.txt"
|
||||
"""
|
||||
rawdrive = '\\'.join(s.split('\\')[:3])
|
||||
driveletter = cext.win32_QueryDosDevice(rawdrive)
|
||||
return os.path.join(driveletter, s[len(rawdrive):])
|
||||
|
||||
|
||||
def py2_strencode(s):
|
||||
"""Encode a unicode string to a byte string by using the default fs
|
||||
encoding + "replace" error handler.
|
||||
"""
|
||||
if PY3:
|
||||
return s
|
||||
else:
|
||||
if isinstance(s, str):
|
||||
return s
|
||||
else:
|
||||
return s.encode(ENCODING, errors=ENCODING_ERRS)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- memory
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def virtual_memory():
|
||||
"""System virtual memory as a namedtuple."""
|
||||
mem = cext.virtual_mem()
|
||||
totphys, availphys, totpagef, availpagef, totvirt, freevirt = mem
|
||||
#
|
||||
total = totphys
|
||||
avail = availphys
|
||||
free = availphys
|
||||
used = total - avail
|
||||
percent = usage_percent((total - avail), total, _round=1)
|
||||
return svmem(total, avail, percent, used, free)
|
||||
|
||||
|
||||
def swap_memory():
|
||||
"""Swap system memory as a (total, used, free, sin, sout) tuple."""
|
||||
mem = cext.virtual_mem()
|
||||
total = mem[2]
|
||||
free = mem[3]
|
||||
used = total - free
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return _common.sswap(total, used, free, percent, 0, 0)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- disk
|
||||
# =====================================================================
|
||||
|
||||
|
||||
disk_io_counters = cext.disk_io_counters
|
||||
|
||||
|
||||
def disk_usage(path):
|
||||
"""Return disk usage associated with path."""
|
||||
if PY3 and isinstance(path, bytes):
|
||||
# XXX: do we want to use "strict"? Probably yes, in order
|
||||
# to fail immediately. After all we are accepting input here...
|
||||
path = path.decode(ENCODING, errors="strict")
|
||||
total, free = cext.disk_usage(path)
|
||||
used = total - free
|
||||
percent = usage_percent(used, total, _round=1)
|
||||
return _common.sdiskusage(total, used, free, percent)
|
||||
|
||||
|
||||
def disk_partitions(all):
|
||||
"""Return disk partitions."""
|
||||
rawlist = cext.disk_partitions(all)
|
||||
return [_common.sdiskpart(*x) for x in rawlist]
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- CPU
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def cpu_times():
|
||||
"""Return system CPU times as a named tuple."""
|
||||
user, system, idle = cext.cpu_times()
|
||||
# Internally, GetSystemTimes() is used, and it doesn't return
|
||||
# interrupt and dpc times. cext.per_cpu_times() does, so we
|
||||
# rely on it to get those only.
|
||||
percpu_summed = scputimes(*[sum(n) for n in zip(*cext.per_cpu_times())])
|
||||
return scputimes(user, system, idle,
|
||||
percpu_summed.interrupt, percpu_summed.dpc)
|
||||
|
||||
|
||||
def per_cpu_times():
|
||||
"""Return system per-CPU times as a list of named tuples."""
|
||||
ret = []
|
||||
for user, system, idle, interrupt, dpc in cext.per_cpu_times():
|
||||
item = scputimes(user, system, idle, interrupt, dpc)
|
||||
ret.append(item)
|
||||
return ret
|
||||
|
||||
|
||||
def cpu_count_logical():
|
||||
"""Return the number of logical CPUs in the system."""
|
||||
return cext.cpu_count_logical()
|
||||
|
||||
|
||||
def cpu_count_physical():
|
||||
"""Return the number of physical CPUs in the system."""
|
||||
return cext.cpu_count_phys()
|
||||
|
||||
|
||||
def cpu_stats():
|
||||
"""Return CPU statistics."""
|
||||
ctx_switches, interrupts, dpcs, syscalls = cext.cpu_stats()
|
||||
soft_interrupts = 0
|
||||
return _common.scpustats(ctx_switches, interrupts, soft_interrupts,
|
||||
syscalls)
|
||||
|
||||
|
||||
def cpu_freq():
|
||||
"""Return CPU frequency.
|
||||
On Windows per-cpu frequency is not supported.
|
||||
"""
|
||||
curr, max_ = cext.cpu_freq()
|
||||
min_ = 0.0
|
||||
return [_common.scpufreq(float(curr), min_, float(max_))]
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- network
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def net_connections(kind, _pid=-1):
|
||||
"""Return socket connections. If pid == -1 return system-wide
|
||||
connections (as opposed to connections opened by one process only).
|
||||
"""
|
||||
if kind not in conn_tmap:
|
||||
raise ValueError("invalid %r kind argument; choose between %s"
|
||||
% (kind, ', '.join([repr(x) for x in conn_tmap])))
|
||||
families, types = conn_tmap[kind]
|
||||
rawlist = cext.net_connections(_pid, families, types)
|
||||
ret = set()
|
||||
for item in rawlist:
|
||||
fd, fam, type, laddr, raddr, status, pid = item
|
||||
if laddr:
|
||||
laddr = _common.addr(*laddr)
|
||||
if raddr:
|
||||
raddr = _common.addr(*raddr)
|
||||
status = TCP_STATUSES[status]
|
||||
fam = sockfam_to_enum(fam)
|
||||
type = socktype_to_enum(type)
|
||||
if _pid == -1:
|
||||
nt = _common.sconn(fd, fam, type, laddr, raddr, status, pid)
|
||||
else:
|
||||
nt = _common.pconn(fd, fam, type, laddr, raddr, status)
|
||||
ret.add(nt)
|
||||
return list(ret)
|
||||
|
||||
|
||||
def net_if_stats():
|
||||
"""Get NIC stats (isup, duplex, speed, mtu)."""
|
||||
ret = {}
|
||||
rawdict = cext.net_if_stats()
|
||||
for name, items in rawdict.items():
|
||||
if not PY3:
|
||||
assert isinstance(name, unicode), type(name)
|
||||
name = py2_strencode(name)
|
||||
isup, duplex, speed, mtu = items
|
||||
if hasattr(_common, 'NicDuplex'):
|
||||
duplex = _common.NicDuplex(duplex)
|
||||
ret[name] = _common.snicstats(isup, duplex, speed, mtu)
|
||||
return ret
|
||||
|
||||
|
||||
def net_io_counters():
|
||||
"""Return network I/O statistics for every network interface
|
||||
installed on the system as a dict of raw tuples.
|
||||
"""
|
||||
ret = cext.net_io_counters()
|
||||
return dict([(py2_strencode(k), v) for k, v in ret.items()])
|
||||
|
||||
|
||||
def net_if_addrs():
|
||||
"""Return the addresses associated to each NIC."""
|
||||
ret = []
|
||||
for items in cext.net_if_addrs():
|
||||
items = list(items)
|
||||
items[0] = py2_strencode(items[0])
|
||||
ret.append(items)
|
||||
return ret
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- sensors
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def sensors_battery():
|
||||
"""Return battery information."""
|
||||
# For constants meaning see:
|
||||
# https://msdn.microsoft.com/en-us/library/windows/desktop/
|
||||
# aa373232(v=vs.85).aspx
|
||||
acline_status, flags, percent, secsleft = cext.sensors_battery()
|
||||
power_plugged = acline_status == 1
|
||||
no_battery = bool(flags & 128)
|
||||
charging = bool(flags & 8)
|
||||
|
||||
if no_battery:
|
||||
return None
|
||||
if power_plugged or charging:
|
||||
secsleft = _common.POWER_TIME_UNLIMITED
|
||||
elif secsleft == -1:
|
||||
secsleft = _common.POWER_TIME_UNKNOWN
|
||||
|
||||
return _common.sbattery(percent, secsleft, power_plugged)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- other system functions
|
||||
# =====================================================================
|
||||
|
||||
|
||||
_last_btime = 0
|
||||
|
||||
|
||||
def boot_time():
|
||||
"""The system boot time expressed in seconds since the epoch."""
|
||||
# This dirty hack is to adjust the precision of the returned
|
||||
# value which may have a 1 second fluctuation, see:
|
||||
# https://github.com/giampaolo/psutil/issues/1007
|
||||
global _last_btime
|
||||
ret = float(cext.boot_time())
|
||||
if abs(ret - _last_btime) <= 1:
|
||||
return _last_btime
|
||||
else:
|
||||
_last_btime = ret
|
||||
return ret
|
||||
|
||||
|
||||
def users():
|
||||
"""Return currently connected users as a list of namedtuples."""
|
||||
retlist = []
|
||||
rawlist = cext.users()
|
||||
for item in rawlist:
|
||||
user, hostname, tstamp = item
|
||||
user = py2_strencode(user)
|
||||
nt = _common.suser(user, None, hostname, tstamp, None)
|
||||
retlist.append(nt)
|
||||
return retlist
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- Windows services
|
||||
# =====================================================================
|
||||
|
||||
|
||||
def win_service_iter():
|
||||
"""Yields a list of WindowsService instances."""
|
||||
for name, display_name in cext.winservice_enumerate():
|
||||
yield WindowsService(py2_strencode(name), py2_strencode(display_name))
|
||||
|
||||
|
||||
def win_service_get(name):
|
||||
"""Open a Windows service and return it as a WindowsService instance."""
|
||||
service = WindowsService(name, None)
|
||||
service._display_name = service._query_config()['display_name']
|
||||
return service
|
||||
|
||||
|
||||
class WindowsService(object):
|
||||
"""Represents an installed Windows service."""
|
||||
|
||||
def __init__(self, name, display_name):
|
||||
self._name = name
|
||||
self._display_name = display_name
|
||||
|
||||
def __str__(self):
|
||||
details = "(name=%r, display_name=%r)" % (
|
||||
self._name, self._display_name)
|
||||
return "%s%s" % (self.__class__.__name__, details)
|
||||
|
||||
def __repr__(self):
|
||||
return "<%s at %s>" % (self.__str__(), id(self))
|
||||
|
||||
def __eq__(self, other):
|
||||
# Test for equality with another WindosService object based
|
||||
# on name.
|
||||
if not isinstance(other, WindowsService):
|
||||
return NotImplemented
|
||||
return self._name == other._name
|
||||
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def _query_config(self):
|
||||
with self._wrap_exceptions():
|
||||
display_name, binpath, username, start_type = \
|
||||
cext.winservice_query_config(self._name)
|
||||
# XXX - update _self.display_name?
|
||||
return dict(
|
||||
display_name=py2_strencode(display_name),
|
||||
binpath=py2_strencode(binpath),
|
||||
username=py2_strencode(username),
|
||||
start_type=py2_strencode(start_type))
|
||||
|
||||
def _query_status(self):
|
||||
with self._wrap_exceptions():
|
||||
status, pid = cext.winservice_query_status(self._name)
|
||||
if pid == 0:
|
||||
pid = None
|
||||
return dict(status=status, pid=pid)
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _wrap_exceptions(self):
|
||||
"""Ctx manager which translates bare OSError and WindowsError
|
||||
exceptions into NoSuchProcess and AccessDenied.
|
||||
"""
|
||||
try:
|
||||
yield
|
||||
except WindowsError as err:
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
raise AccessDenied(
|
||||
pid=None, name=self._name,
|
||||
msg="service %r is not querable (not enough privileges)" %
|
||||
self._name)
|
||||
elif err.errno in NO_SUCH_SERVICE_ERRSET or \
|
||||
err.winerror in NO_SUCH_SERVICE_ERRSET:
|
||||
raise NoSuchProcess(
|
||||
pid=None, name=self._name,
|
||||
msg="service %r does not exist)" % self._name)
|
||||
else:
|
||||
raise
|
||||
|
||||
# config query
|
||||
|
||||
def name(self):
|
||||
"""The service name. This string is how a service is referenced
|
||||
and can be passed to win_service_get() to get a new
|
||||
WindowsService instance.
|
||||
"""
|
||||
return self._name
|
||||
|
||||
def display_name(self):
|
||||
"""The service display name. The value is cached when this class
|
||||
is instantiated.
|
||||
"""
|
||||
return self._display_name
|
||||
|
||||
def binpath(self):
|
||||
"""The fully qualified path to the service binary/exe file as
|
||||
a string, including command line arguments.
|
||||
"""
|
||||
return self._query_config()['binpath']
|
||||
|
||||
def username(self):
|
||||
"""The name of the user that owns this service."""
|
||||
return self._query_config()['username']
|
||||
|
||||
def start_type(self):
|
||||
"""A string which can either be "automatic", "manual" or
|
||||
"disabled".
|
||||
"""
|
||||
return self._query_config()['start_type']
|
||||
|
||||
# status query
|
||||
|
||||
def pid(self):
|
||||
"""The process PID, if any, else None. This can be passed
|
||||
to Process class to control the service's process.
|
||||
"""
|
||||
return self._query_status()['pid']
|
||||
|
||||
def status(self):
|
||||
"""Service status as a string."""
|
||||
return self._query_status()['status']
|
||||
|
||||
def description(self):
|
||||
"""Service long description."""
|
||||
return py2_strencode(cext.winservice_query_descr(self.name()))
|
||||
|
||||
# utils
|
||||
|
||||
def as_dict(self):
|
||||
"""Utility method retrieving all the information above as a
|
||||
dictionary.
|
||||
"""
|
||||
d = self._query_config()
|
||||
d.update(self._query_status())
|
||||
d['name'] = self.name()
|
||||
d['display_name'] = self.display_name()
|
||||
d['description'] = self.description()
|
||||
return d
|
||||
|
||||
# actions
|
||||
# XXX: the necessary C bindings for start() and stop() are
|
||||
# implemented but for now I prefer not to expose them.
|
||||
# I may change my mind in the future. Reasons:
|
||||
# - they require Administrator privileges
|
||||
# - can't implement a timeout for stop() (unless by using a thread,
|
||||
# which sucks)
|
||||
# - would require adding ServiceAlreadyStarted and
|
||||
# ServiceAlreadyStopped exceptions, adding two new APIs.
|
||||
# - we might also want to have modify(), which would basically mean
|
||||
# rewriting win32serviceutil.ChangeServiceConfig, which involves a
|
||||
# lot of stuff (and API constants which would pollute the API), see:
|
||||
# http://pyxr.sourceforge.net/PyXR/c/python24/lib/site-packages/
|
||||
# win32/lib/win32serviceutil.py.html#0175
|
||||
# - psutil is typically about "read only" monitoring stuff;
|
||||
# win_service_* APIs should only be used to retrieve a service and
|
||||
# check whether it's running
|
||||
|
||||
# def start(self, timeout=None):
|
||||
# with self._wrap_exceptions():
|
||||
# cext.winservice_start(self.name())
|
||||
# if timeout:
|
||||
# giveup_at = time.time() + timeout
|
||||
# while True:
|
||||
# if self.status() == "running":
|
||||
# return
|
||||
# else:
|
||||
# if time.time() > giveup_at:
|
||||
# raise TimeoutExpired(timeout)
|
||||
# else:
|
||||
# time.sleep(.1)
|
||||
|
||||
# def stop(self):
|
||||
# # Note: timeout is not implemented because it's just not
|
||||
# # possible, see:
|
||||
# # http://stackoverflow.com/questions/11973228/
|
||||
# with self._wrap_exceptions():
|
||||
# return cext.winservice_stop(self.name())
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- processes
|
||||
# =====================================================================
|
||||
|
||||
|
||||
pids = cext.pids
|
||||
pid_exists = cext.pid_exists
|
||||
ppid_map = cext.ppid_map # used internally by Process.children()
|
||||
|
||||
|
||||
def wrap_exceptions(fun):
|
||||
"""Decorator which translates bare OSError and WindowsError
|
||||
exceptions into NoSuchProcess and AccessDenied.
|
||||
"""
|
||||
@functools.wraps(fun)
|
||||
def wrapper(self, *args, **kwargs):
|
||||
try:
|
||||
return fun(self, *args, **kwargs)
|
||||
except OSError as err:
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
if err.errno == errno.ESRCH:
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
class Process(object):
|
||||
"""Wrapper class around underlying C implementation."""
|
||||
|
||||
__slots__ = ["pid", "_name", "_ppid"]
|
||||
|
||||
def __init__(self, pid):
|
||||
self.pid = pid
|
||||
self._name = None
|
||||
self._ppid = None
|
||||
|
||||
# --- oneshot() stuff
|
||||
|
||||
def oneshot_enter(self):
|
||||
self.oneshot_info.cache_activate()
|
||||
|
||||
def oneshot_exit(self):
|
||||
self.oneshot_info.cache_deactivate()
|
||||
|
||||
@memoize_when_activated
|
||||
def oneshot_info(self):
|
||||
"""Return multiple information about this process as a
|
||||
raw tuple.
|
||||
"""
|
||||
ret = cext.proc_info(self.pid)
|
||||
assert len(ret) == len(pinfo_map)
|
||||
return ret
|
||||
|
||||
@wrap_exceptions
|
||||
def name(self):
|
||||
"""Return process name, which on Windows is always the final
|
||||
part of the executable.
|
||||
"""
|
||||
# This is how PIDs 0 and 4 are always represented in taskmgr
|
||||
# and process-hacker.
|
||||
if self.pid == 0:
|
||||
return "System Idle Process"
|
||||
elif self.pid == 4:
|
||||
return "System"
|
||||
else:
|
||||
try:
|
||||
# Note: this will fail with AD for most PIDs owned
|
||||
# by another user but it's faster.
|
||||
return py2_strencode(os.path.basename(self.exe()))
|
||||
except AccessDenied:
|
||||
return py2_strencode(cext.proc_name(self.pid))
|
||||
|
||||
@wrap_exceptions
|
||||
def exe(self):
|
||||
# Note: os.path.exists(path) may return False even if the file
|
||||
# is there, see:
|
||||
# http://stackoverflow.com/questions/3112546/os-path-exists-lies
|
||||
|
||||
# see https://github.com/giampaolo/psutil/issues/414
|
||||
# see https://github.com/giampaolo/psutil/issues/528
|
||||
if self.pid in (0, 4):
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
return py2_strencode(convert_dos_path(cext.proc_exe(self.pid)))
|
||||
|
||||
@wrap_exceptions
|
||||
def cmdline(self):
|
||||
ret = cext.proc_cmdline(self.pid)
|
||||
if PY3:
|
||||
return ret
|
||||
else:
|
||||
return [py2_strencode(s) for s in ret]
|
||||
|
||||
@wrap_exceptions
|
||||
def environ(self):
|
||||
ustr = cext.proc_environ(self.pid)
|
||||
if ustr and not PY3:
|
||||
assert isinstance(ustr, unicode), type(ustr)
|
||||
return parse_environ_block(py2_strencode(ustr))
|
||||
|
||||
def ppid(self):
|
||||
try:
|
||||
return ppid_map()[self.pid]
|
||||
except KeyError:
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
|
||||
def _get_raw_meminfo(self):
|
||||
try:
|
||||
return cext.proc_memory_info(self.pid)
|
||||
except OSError as err:
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
# TODO: the C ext can probably be refactored in order
|
||||
# to get this from cext.proc_info()
|
||||
info = self.oneshot_info()
|
||||
return (
|
||||
info[pinfo_map['num_page_faults']],
|
||||
info[pinfo_map['peak_wset']],
|
||||
info[pinfo_map['wset']],
|
||||
info[pinfo_map['peak_paged_pool']],
|
||||
info[pinfo_map['paged_pool']],
|
||||
info[pinfo_map['peak_non_paged_pool']],
|
||||
info[pinfo_map['non_paged_pool']],
|
||||
info[pinfo_map['pagefile']],
|
||||
info[pinfo_map['peak_pagefile']],
|
||||
info[pinfo_map['mem_private']],
|
||||
)
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_info(self):
|
||||
# on Windows RSS == WorkingSetSize and VSM == PagefileUsage.
|
||||
# Underlying C function returns fields of PROCESS_MEMORY_COUNTERS
|
||||
# struct.
|
||||
t = self._get_raw_meminfo()
|
||||
rss = t[2] # wset
|
||||
vms = t[7] # pagefile
|
||||
return pmem(*(rss, vms, ) + t)
|
||||
|
||||
@wrap_exceptions
|
||||
def memory_full_info(self):
|
||||
basic_mem = self.memory_info()
|
||||
uss = cext.proc_memory_uss(self.pid)
|
||||
return pfullmem(*basic_mem + (uss, ))
|
||||
|
||||
def memory_maps(self):
|
||||
try:
|
||||
raw = cext.proc_memory_maps(self.pid)
|
||||
except OSError as err:
|
||||
# XXX - can't use wrap_exceptions decorator as we're
|
||||
# returning a generator; probably needs refactoring.
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
if err.errno == errno.ESRCH:
|
||||
raise NoSuchProcess(self.pid, self._name)
|
||||
raise
|
||||
else:
|
||||
for addr, perm, path, rss in raw:
|
||||
path = convert_dos_path(path)
|
||||
if not PY3:
|
||||
assert isinstance(path, unicode), type(path)
|
||||
path = py2_strencode(path)
|
||||
addr = hex(addr)
|
||||
yield (addr, perm, path, rss)
|
||||
|
||||
@wrap_exceptions
|
||||
def kill(self):
|
||||
return cext.proc_kill(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def send_signal(self, sig):
|
||||
os.kill(self.pid, sig)
|
||||
|
||||
@wrap_exceptions
|
||||
def wait(self, timeout=None):
|
||||
if timeout is None:
|
||||
cext_timeout = cext.INFINITE
|
||||
else:
|
||||
# WaitForSingleObject() expects time in milliseconds
|
||||
cext_timeout = int(timeout * 1000)
|
||||
while True:
|
||||
ret = cext.proc_wait(self.pid, cext_timeout)
|
||||
if ret == WAIT_TIMEOUT:
|
||||
raise TimeoutExpired(timeout, self.pid, self._name)
|
||||
if pid_exists(self.pid):
|
||||
if timeout is None:
|
||||
continue
|
||||
else:
|
||||
raise TimeoutExpired(timeout, self.pid, self._name)
|
||||
return ret
|
||||
|
||||
@wrap_exceptions
|
||||
def username(self):
|
||||
if self.pid in (0, 4):
|
||||
return 'NT AUTHORITY\\SYSTEM'
|
||||
domain, user = cext.proc_username(self.pid)
|
||||
return py2_strencode(domain) + '\\' + py2_strencode(user)
|
||||
|
||||
@wrap_exceptions
|
||||
def create_time(self):
|
||||
# special case for kernel process PIDs; return system boot time
|
||||
if self.pid in (0, 4):
|
||||
return boot_time()
|
||||
try:
|
||||
return cext.proc_create_time(self.pid)
|
||||
except OSError as err:
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
return self.oneshot_info()[pinfo_map['create_time']]
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def num_threads(self):
|
||||
return self.oneshot_info()[pinfo_map['num_threads']]
|
||||
|
||||
@wrap_exceptions
|
||||
def threads(self):
|
||||
rawlist = cext.proc_threads(self.pid)
|
||||
retlist = []
|
||||
for thread_id, utime, stime in rawlist:
|
||||
ntuple = _common.pthread(thread_id, utime, stime)
|
||||
retlist.append(ntuple)
|
||||
return retlist
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_times(self):
|
||||
try:
|
||||
user, system = cext.proc_cpu_times(self.pid)
|
||||
except OSError as err:
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
info = self.oneshot_info()
|
||||
user = info[pinfo_map['user_time']]
|
||||
system = info[pinfo_map['kernel_time']]
|
||||
else:
|
||||
raise
|
||||
# Children user/system times are not retrievable (set to 0).
|
||||
return _common.pcputimes(user, system, 0.0, 0.0)
|
||||
|
||||
@wrap_exceptions
|
||||
def suspend(self):
|
||||
return cext.proc_suspend(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def resume(self):
|
||||
return cext.proc_resume(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def cwd(self):
|
||||
if self.pid in (0, 4):
|
||||
raise AccessDenied(self.pid, self._name)
|
||||
# return a normalized pathname since the native C function appends
|
||||
# "\\" at the and of the path
|
||||
path = cext.proc_cwd(self.pid)
|
||||
return py2_strencode(os.path.normpath(path))
|
||||
|
||||
@wrap_exceptions
|
||||
def open_files(self):
|
||||
if self.pid in (0, 4):
|
||||
return []
|
||||
ret = set()
|
||||
# Filenames come in in native format like:
|
||||
# "\Device\HarddiskVolume1\Windows\systemew\file.txt"
|
||||
# Convert the first part in the corresponding drive letter
|
||||
# (e.g. "C:\") by using Windows's QueryDosDevice()
|
||||
raw_file_names = cext.proc_open_files(self.pid)
|
||||
for _file in raw_file_names:
|
||||
_file = convert_dos_path(_file)
|
||||
if isfile_strict(_file):
|
||||
if not PY3:
|
||||
_file = py2_strencode(_file)
|
||||
ntuple = _common.popenfile(_file, -1)
|
||||
ret.add(ntuple)
|
||||
return list(ret)
|
||||
|
||||
@wrap_exceptions
|
||||
def connections(self, kind='inet'):
|
||||
return net_connections(kind, _pid=self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_get(self):
|
||||
value = cext.proc_priority_get(self.pid)
|
||||
if enum is not None:
|
||||
value = Priority(value)
|
||||
return value
|
||||
|
||||
@wrap_exceptions
|
||||
def nice_set(self, value):
|
||||
return cext.proc_priority_set(self.pid, value)
|
||||
|
||||
# available on Windows >= Vista
|
||||
if hasattr(cext, "proc_io_priority_get"):
|
||||
@wrap_exceptions
|
||||
def ionice_get(self):
|
||||
return cext.proc_io_priority_get(self.pid)
|
||||
|
||||
@wrap_exceptions
|
||||
def ionice_set(self, value, _):
|
||||
if _:
|
||||
raise TypeError("set_proc_ionice() on Windows takes only "
|
||||
"1 argument (2 given)")
|
||||
if value not in (2, 1, 0):
|
||||
raise ValueError("value must be 2 (normal), 1 (low) or 0 "
|
||||
"(very low); got %r" % value)
|
||||
return cext.proc_io_priority_set(self.pid, value)
|
||||
|
||||
@wrap_exceptions
|
||||
def io_counters(self):
|
||||
try:
|
||||
ret = cext.proc_io_counters(self.pid)
|
||||
except OSError as err:
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
info = self.oneshot_info()
|
||||
ret = (
|
||||
info[pinfo_map['io_rcount']],
|
||||
info[pinfo_map['io_wcount']],
|
||||
info[pinfo_map['io_rbytes']],
|
||||
info[pinfo_map['io_wbytes']],
|
||||
info[pinfo_map['io_count_others']],
|
||||
info[pinfo_map['io_bytes_others']],
|
||||
)
|
||||
else:
|
||||
raise
|
||||
return pio(*ret)
|
||||
|
||||
@wrap_exceptions
|
||||
def status(self):
|
||||
suspended = cext.proc_is_suspended(self.pid)
|
||||
if suspended:
|
||||
return _common.STATUS_STOPPED
|
||||
else:
|
||||
return _common.STATUS_RUNNING
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_affinity_get(self):
|
||||
def from_bitmask(x):
|
||||
return [i for i in xrange(64) if (1 << i) & x]
|
||||
bitmask = cext.proc_cpu_affinity_get(self.pid)
|
||||
return from_bitmask(bitmask)
|
||||
|
||||
@wrap_exceptions
|
||||
def cpu_affinity_set(self, value):
|
||||
def to_bitmask(l):
|
||||
if not l:
|
||||
raise ValueError("invalid argument %r" % l)
|
||||
out = 0
|
||||
for b in l:
|
||||
out |= 2 ** b
|
||||
return out
|
||||
|
||||
# SetProcessAffinityMask() states that ERROR_INVALID_PARAMETER
|
||||
# is returned for an invalid CPU but this seems not to be true,
|
||||
# therefore we check CPUs validy beforehand.
|
||||
allcpus = list(range(len(per_cpu_times())))
|
||||
for cpu in value:
|
||||
if cpu not in allcpus:
|
||||
if not isinstance(cpu, (int, long)):
|
||||
raise TypeError(
|
||||
"invalid CPU %r; an integer is required" % cpu)
|
||||
else:
|
||||
raise ValueError("invalid CPU %r" % cpu)
|
||||
|
||||
bitmask = to_bitmask(value)
|
||||
cext.proc_cpu_affinity_set(self.pid, bitmask)
|
||||
|
||||
@wrap_exceptions
|
||||
def num_handles(self):
|
||||
try:
|
||||
return cext.proc_num_handles(self.pid)
|
||||
except OSError as err:
|
||||
if err.errno in ACCESS_DENIED_ERRSET:
|
||||
return self.oneshot_info()[pinfo_map['num_handles']]
|
||||
raise
|
||||
|
||||
@wrap_exceptions
|
||||
def num_ctx_switches(self):
|
||||
ctx_switches = self.oneshot_info()[pinfo_map['ctx_switches']]
|
||||
# only voluntary ctx switches are supported
|
||||
return _common.pctxsw(ctx_switches, 0)
|
1198
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/__init__.py
поставляемый
Normal file
1198
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/__init__.py
поставляемый
Normal file
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,96 @@
|
|||
#!/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.
|
||||
|
||||
"""
|
||||
Run unit tests. This is invoked by:
|
||||
|
||||
$ python -m psutil.tests
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import optparse
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import tempfile
|
||||
try:
|
||||
from urllib.request import urlopen # py3
|
||||
except ImportError:
|
||||
from urllib2 import urlopen
|
||||
|
||||
from psutil.tests import PYTHON_EXE
|
||||
from psutil.tests import run_suite
|
||||
|
||||
|
||||
HERE = os.path.abspath(os.path.dirname(__file__))
|
||||
GET_PIP_URL = "https://bootstrap.pypa.io/get-pip.py"
|
||||
TEST_DEPS = []
|
||||
if sys.version_info[:2] == (2, 6):
|
||||
TEST_DEPS.extend(["ipaddress", "unittest2", "argparse", "mock==1.0.1"])
|
||||
elif sys.version_info[:2] == (2, 7) or sys.version_info[:2] <= (3, 2):
|
||||
TEST_DEPS.extend(["ipaddress", "mock"])
|
||||
elif sys.version_info[:2] == (3, 3):
|
||||
TEST_DEPS.extend(["ipaddress"])
|
||||
|
||||
|
||||
def install_pip():
|
||||
try:
|
||||
import pip # NOQA
|
||||
except ImportError:
|
||||
f = tempfile.NamedTemporaryFile(suffix='.py')
|
||||
with contextlib.closing(f):
|
||||
print("downloading %s to %s" % (GET_PIP_URL, f.name))
|
||||
if hasattr(ssl, '_create_unverified_context'):
|
||||
ctx = ssl._create_unverified_context()
|
||||
else:
|
||||
ctx = None
|
||||
kwargs = dict(context=ctx) if ctx else {}
|
||||
req = urlopen(GET_PIP_URL, **kwargs)
|
||||
data = req.read()
|
||||
f.write(data)
|
||||
f.flush()
|
||||
|
||||
print("installing pip")
|
||||
code = os.system('%s %s --user' % (PYTHON_EXE, f.name))
|
||||
return code
|
||||
|
||||
|
||||
def install_test_deps(deps=None):
|
||||
"""Install test dependencies via pip."""
|
||||
if deps is None:
|
||||
deps = TEST_DEPS
|
||||
deps = set(deps)
|
||||
if deps:
|
||||
is_venv = hasattr(sys, 'real_prefix')
|
||||
opts = "--user" if not is_venv else ""
|
||||
install_pip()
|
||||
code = os.system('%s -m pip install %s --upgrade %s' % (
|
||||
PYTHON_EXE, opts, " ".join(deps)))
|
||||
return code
|
||||
|
||||
|
||||
def main():
|
||||
usage = "%s -m psutil.tests [opts]" % PYTHON_EXE
|
||||
parser = optparse.OptionParser(usage=usage, description="run unit tests")
|
||||
parser.add_option("-i", "--install-deps",
|
||||
action="store_true", default=False,
|
||||
help="don't print status messages to stdout")
|
||||
|
||||
opts, args = parser.parse_args()
|
||||
if opts.install_deps:
|
||||
install_pip()
|
||||
install_test_deps()
|
||||
else:
|
||||
for dep in TEST_DEPS:
|
||||
try:
|
||||
__import__(dep.split("==")[0])
|
||||
except ImportError:
|
||||
sys.exit("%r lib is not installed; run %s -m psutil.tests "
|
||||
"--install-deps" % (dep, PYTHON_EXE))
|
||||
run_suite()
|
||||
|
||||
|
||||
main()
|
|
@ -0,0 +1,121 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'
|
||||
# Copyright (c) 2017, Arnon Yaari
|
||||
# All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""AIX specific tests."""
|
||||
|
||||
import re
|
||||
|
||||
from psutil import AIX
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import sh
|
||||
from psutil.tests import unittest
|
||||
import psutil
|
||||
|
||||
|
||||
@unittest.skipIf(not AIX, "AIX only")
|
||||
class AIXSpecificTestCase(unittest.TestCase):
|
||||
|
||||
def test_virtual_memory(self):
|
||||
out = sh('/usr/bin/svmon -O unit=KB')
|
||||
re_pattern = "memory\s*"
|
||||
for field in ("size inuse free pin virtual available mmode").split():
|
||||
re_pattern += "(?P<%s>\S+)\s+" % (field,)
|
||||
matchobj = re.search(re_pattern, out)
|
||||
|
||||
self.assertIsNotNone(
|
||||
matchobj, "svmon command returned unexpected output")
|
||||
|
||||
KB = 1024
|
||||
total = int(matchobj.group("size")) * KB
|
||||
available = int(matchobj.group("available")) * KB
|
||||
used = int(matchobj.group("inuse")) * KB
|
||||
free = int(matchobj.group("free")) * KB
|
||||
|
||||
psutil_result = psutil.virtual_memory()
|
||||
|
||||
# MEMORY_TOLERANCE from psutil.tests is not enough. For some reason
|
||||
# we're seeing differences of ~1.2 MB. 2 MB is still a good tolerance
|
||||
# when compared to GBs.
|
||||
MEMORY_TOLERANCE = 2 * KB * KB # 2 MB
|
||||
self.assertEqual(psutil_result.total, total)
|
||||
self.assertAlmostEqual(
|
||||
psutil_result.used, used, delta=MEMORY_TOLERANCE)
|
||||
self.assertAlmostEqual(
|
||||
psutil_result.available, available, delta=MEMORY_TOLERANCE)
|
||||
self.assertAlmostEqual(
|
||||
psutil_result.free, free, delta=MEMORY_TOLERANCE)
|
||||
|
||||
def test_swap_memory(self):
|
||||
out = sh('/usr/sbin/lsps -a')
|
||||
# From the man page, "The size is given in megabytes" so we assume
|
||||
# we'll always have 'MB' in the result
|
||||
# TODO maybe try to use "swap -l" to check "used" too, but its units
|
||||
# are not guaranteed to be "MB" so parsing may not be consistent
|
||||
matchobj = re.search("(?P<space>\S+)\s+"
|
||||
"(?P<vol>\S+)\s+"
|
||||
"(?P<vg>\S+)\s+"
|
||||
"(?P<size>\d+)MB", out)
|
||||
|
||||
self.assertIsNotNone(
|
||||
matchobj, "lsps command returned unexpected output")
|
||||
|
||||
total_mb = int(matchobj.group("size"))
|
||||
MB = 1024 ** 2
|
||||
psutil_result = psutil.swap_memory()
|
||||
# we divide our result by MB instead of multiplying the lsps value by
|
||||
# MB because lsps may round down, so we round down too
|
||||
self.assertEqual(int(psutil_result.total / MB), total_mb)
|
||||
|
||||
def test_cpu_stats(self):
|
||||
out = sh('/usr/bin/mpstat -a')
|
||||
|
||||
re_pattern = "ALL\s*"
|
||||
for field in ("min maj mpcs mpcr dev soft dec ph cs ics bound rq "
|
||||
"push S3pull S3grd S0rd S1rd S2rd S3rd S4rd S5rd "
|
||||
"sysc").split():
|
||||
re_pattern += "(?P<%s>\S+)\s+" % (field,)
|
||||
matchobj = re.search(re_pattern, out)
|
||||
|
||||
self.assertIsNotNone(
|
||||
matchobj, "mpstat command returned unexpected output")
|
||||
|
||||
# numbers are usually in the millions so 1000 is ok for tolerance
|
||||
CPU_STATS_TOLERANCE = 1000
|
||||
psutil_result = psutil.cpu_stats()
|
||||
self.assertAlmostEqual(
|
||||
psutil_result.ctx_switches,
|
||||
int(matchobj.group("cs")),
|
||||
delta=CPU_STATS_TOLERANCE)
|
||||
self.assertAlmostEqual(
|
||||
psutil_result.syscalls,
|
||||
int(matchobj.group("sysc")),
|
||||
delta=CPU_STATS_TOLERANCE)
|
||||
self.assertAlmostEqual(
|
||||
psutil_result.interrupts,
|
||||
int(matchobj.group("dev")),
|
||||
delta=CPU_STATS_TOLERANCE)
|
||||
self.assertAlmostEqual(
|
||||
psutil_result.soft_interrupts,
|
||||
int(matchobj.group("soft")),
|
||||
delta=CPU_STATS_TOLERANCE)
|
||||
|
||||
def test_cpu_count_logical(self):
|
||||
out = sh('/usr/bin/mpstat -a')
|
||||
mpstat_lcpu = int(re.search("lcpu=(\d+)", out).group(1))
|
||||
psutil_lcpu = psutil.cpu_count(logical=True)
|
||||
self.assertEqual(mpstat_lcpu, psutil_lcpu)
|
||||
|
||||
def test_net_if_addrs_names(self):
|
||||
out = sh('/etc/ifconfig -l')
|
||||
ifconfig_names = set(out.split())
|
||||
psutil_names = set(psutil.net_if_addrs().keys())
|
||||
self.assertSetEqual(ifconfig_names, psutil_names)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
|
@ -0,0 +1,489 @@
|
|||
#!/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.
|
||||
|
||||
# TODO: (FreeBSD) add test for comparing connections with 'sockstat' cmd.
|
||||
|
||||
|
||||
"""Tests specific to all BSD platforms."""
|
||||
|
||||
|
||||
import datetime
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import psutil
|
||||
from psutil import BSD
|
||||
from psutil import FREEBSD
|
||||
from psutil import NETBSD
|
||||
from psutil import OPENBSD
|
||||
from psutil.tests import get_test_subprocess
|
||||
from psutil.tests import HAS_BATTERY
|
||||
from psutil.tests import MEMORY_TOLERANCE
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import retry_before_failing
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import sh
|
||||
from psutil.tests import unittest
|
||||
from psutil.tests import which
|
||||
|
||||
|
||||
if BSD:
|
||||
PAGESIZE = os.sysconf("SC_PAGE_SIZE")
|
||||
if os.getuid() == 0: # muse requires root privileges
|
||||
MUSE_AVAILABLE = which('muse')
|
||||
else:
|
||||
MUSE_AVAILABLE = False
|
||||
else:
|
||||
MUSE_AVAILABLE = False
|
||||
|
||||
|
||||
def sysctl(cmdline):
|
||||
"""Expects a sysctl command with an argument and parse the result
|
||||
returning only the value of interest.
|
||||
"""
|
||||
result = sh("sysctl " + cmdline)
|
||||
if FREEBSD:
|
||||
result = result[result.find(": ") + 2:]
|
||||
elif OPENBSD or NETBSD:
|
||||
result = result[result.find("=") + 1:]
|
||||
try:
|
||||
return int(result)
|
||||
except ValueError:
|
||||
return result
|
||||
|
||||
|
||||
def muse(field):
|
||||
"""Thin wrapper around 'muse' cmdline utility."""
|
||||
out = sh('muse')
|
||||
for line in out.split('\n'):
|
||||
if line.startswith(field):
|
||||
break
|
||||
else:
|
||||
raise ValueError("line not found")
|
||||
return int(line.split()[1])
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- All BSD*
|
||||
# =====================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not BSD, "BSD only")
|
||||
class BSDSpecificTestCase(unittest.TestCase):
|
||||
"""Generic tests common to all BSD variants."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.pid = get_test_subprocess().pid
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
|
||||
@unittest.skipIf(NETBSD, "-o lstart doesn't work on NETBSD")
|
||||
def test_process_create_time(self):
|
||||
output = sh("ps -o lstart -p %s" % self.pid)
|
||||
start_ps = output.replace('STARTED', '').strip()
|
||||
start_psutil = psutil.Process(self.pid).create_time()
|
||||
start_psutil = time.strftime("%a %b %e %H:%M:%S %Y",
|
||||
time.localtime(start_psutil))
|
||||
self.assertEqual(start_ps, start_psutil)
|
||||
|
||||
def test_disks(self):
|
||||
# test psutil.disk_usage() and psutil.disk_partitions()
|
||||
# against "df -a"
|
||||
def df(path):
|
||||
out = sh('df -k "%s"' % path).strip()
|
||||
lines = out.split('\n')
|
||||
lines.pop(0)
|
||||
line = lines.pop(0)
|
||||
dev, total, used, free = line.split()[:4]
|
||||
if dev == 'none':
|
||||
dev = ''
|
||||
total = int(total) * 1024
|
||||
used = int(used) * 1024
|
||||
free = int(free) * 1024
|
||||
return dev, total, used, free
|
||||
|
||||
for part in psutil.disk_partitions(all=False):
|
||||
usage = psutil.disk_usage(part.mountpoint)
|
||||
dev, total, used, free = df(part.mountpoint)
|
||||
self.assertEqual(part.device, dev)
|
||||
self.assertEqual(usage.total, total)
|
||||
# 10 MB tollerance
|
||||
if abs(usage.free - free) > 10 * 1024 * 1024:
|
||||
self.fail("psutil=%s, df=%s" % (usage.free, free))
|
||||
if abs(usage.used - used) > 10 * 1024 * 1024:
|
||||
self.fail("psutil=%s, df=%s" % (usage.used, used))
|
||||
|
||||
@unittest.skipIf(not which('sysctl'), "sysctl cmd not available")
|
||||
def test_cpu_count_logical(self):
|
||||
syst = sysctl("hw.ncpu")
|
||||
self.assertEqual(psutil.cpu_count(logical=True), syst)
|
||||
|
||||
@unittest.skipIf(not which('sysctl'), "sysctl cmd not available")
|
||||
def test_virtual_memory_total(self):
|
||||
num = sysctl('hw.physmem')
|
||||
self.assertEqual(num, psutil.virtual_memory().total)
|
||||
|
||||
def test_net_if_stats(self):
|
||||
for name, stats in psutil.net_if_stats().items():
|
||||
try:
|
||||
out = sh("ifconfig %s" % name)
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
|
||||
if "mtu" in out:
|
||||
self.assertEqual(stats.mtu,
|
||||
int(re.findall(r'mtu (\d+)', out)[0]))
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- FreeBSD
|
||||
# =====================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not FREEBSD, "FREEBSD only")
|
||||
class FreeBSDSpecificTestCase(unittest.TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.pid = get_test_subprocess().pid
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
|
||||
@retry_before_failing()
|
||||
def test_proc_memory_maps(self):
|
||||
out = sh('procstat -v %s' % self.pid)
|
||||
maps = psutil.Process(self.pid).memory_maps(grouped=False)
|
||||
lines = out.split('\n')[1:]
|
||||
while lines:
|
||||
line = lines.pop()
|
||||
fields = line.split()
|
||||
_, start, stop, perms, res = fields[:5]
|
||||
map = maps.pop()
|
||||
self.assertEqual("%s-%s" % (start, stop), map.addr)
|
||||
self.assertEqual(int(res), map.rss)
|
||||
if not map.path.startswith('['):
|
||||
self.assertEqual(fields[10], map.path)
|
||||
|
||||
def test_proc_exe(self):
|
||||
out = sh('procstat -b %s' % self.pid)
|
||||
self.assertEqual(psutil.Process(self.pid).exe(),
|
||||
out.split('\n')[1].split()[-1])
|
||||
|
||||
def test_proc_cmdline(self):
|
||||
out = sh('procstat -c %s' % self.pid)
|
||||
self.assertEqual(' '.join(psutil.Process(self.pid).cmdline()),
|
||||
' '.join(out.split('\n')[1].split()[2:]))
|
||||
|
||||
def test_proc_uids_gids(self):
|
||||
out = sh('procstat -s %s' % self.pid)
|
||||
euid, ruid, suid, egid, rgid, sgid = out.split('\n')[1].split()[2:8]
|
||||
p = psutil.Process(self.pid)
|
||||
uids = p.uids()
|
||||
gids = p.gids()
|
||||
self.assertEqual(uids.real, int(ruid))
|
||||
self.assertEqual(uids.effective, int(euid))
|
||||
self.assertEqual(uids.saved, int(suid))
|
||||
self.assertEqual(gids.real, int(rgid))
|
||||
self.assertEqual(gids.effective, int(egid))
|
||||
self.assertEqual(gids.saved, int(sgid))
|
||||
|
||||
@retry_before_failing()
|
||||
def test_proc_ctx_switches(self):
|
||||
tested = []
|
||||
out = sh('procstat -r %s' % self.pid)
|
||||
p = psutil.Process(self.pid)
|
||||
for line in out.split('\n'):
|
||||
line = line.lower().strip()
|
||||
if ' voluntary context' in line:
|
||||
pstat_value = int(line.split()[-1])
|
||||
psutil_value = p.num_ctx_switches().voluntary
|
||||
self.assertEqual(pstat_value, psutil_value)
|
||||
tested.append(None)
|
||||
elif ' involuntary context' in line:
|
||||
pstat_value = int(line.split()[-1])
|
||||
psutil_value = p.num_ctx_switches().involuntary
|
||||
self.assertEqual(pstat_value, psutil_value)
|
||||
tested.append(None)
|
||||
if len(tested) != 2:
|
||||
raise RuntimeError("couldn't find lines match in procstat out")
|
||||
|
||||
@retry_before_failing()
|
||||
def test_proc_cpu_times(self):
|
||||
tested = []
|
||||
out = sh('procstat -r %s' % self.pid)
|
||||
p = psutil.Process(self.pid)
|
||||
for line in out.split('\n'):
|
||||
line = line.lower().strip()
|
||||
if 'user time' in line:
|
||||
pstat_value = float('0.' + line.split()[-1].split('.')[-1])
|
||||
psutil_value = p.cpu_times().user
|
||||
self.assertEqual(pstat_value, psutil_value)
|
||||
tested.append(None)
|
||||
elif 'system time' in line:
|
||||
pstat_value = float('0.' + line.split()[-1].split('.')[-1])
|
||||
psutil_value = p.cpu_times().system
|
||||
self.assertEqual(pstat_value, psutil_value)
|
||||
tested.append(None)
|
||||
if len(tested) != 2:
|
||||
raise RuntimeError("couldn't find lines match in procstat out")
|
||||
|
||||
# --- virtual_memory(); tests against sysctl
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_active(self):
|
||||
syst = sysctl("vm.stats.vm.v_active_count") * PAGESIZE
|
||||
self.assertAlmostEqual(psutil.virtual_memory().active, syst,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_inactive(self):
|
||||
syst = sysctl("vm.stats.vm.v_inactive_count") * PAGESIZE
|
||||
self.assertAlmostEqual(psutil.virtual_memory().inactive, syst,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_wired(self):
|
||||
syst = sysctl("vm.stats.vm.v_wire_count") * PAGESIZE
|
||||
self.assertAlmostEqual(psutil.virtual_memory().wired, syst,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_cached(self):
|
||||
syst = sysctl("vm.stats.vm.v_cache_count") * PAGESIZE
|
||||
self.assertAlmostEqual(psutil.virtual_memory().cached, syst,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_free(self):
|
||||
syst = sysctl("vm.stats.vm.v_free_count") * PAGESIZE
|
||||
self.assertAlmostEqual(psutil.virtual_memory().free, syst,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_buffers(self):
|
||||
syst = sysctl("vfs.bufspace")
|
||||
self.assertAlmostEqual(psutil.virtual_memory().buffers, syst,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
# --- virtual_memory(); tests against muse
|
||||
|
||||
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
|
||||
def test_muse_vmem_total(self):
|
||||
num = muse('Total')
|
||||
self.assertEqual(psutil.virtual_memory().total, num)
|
||||
|
||||
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
|
||||
@retry_before_failing()
|
||||
def test_muse_vmem_active(self):
|
||||
num = muse('Active')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().active, num,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
|
||||
@retry_before_failing()
|
||||
def test_muse_vmem_inactive(self):
|
||||
num = muse('Inactive')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().inactive, num,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
|
||||
@retry_before_failing()
|
||||
def test_muse_vmem_wired(self):
|
||||
num = muse('Wired')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().wired, num,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
|
||||
@retry_before_failing()
|
||||
def test_muse_vmem_cached(self):
|
||||
num = muse('Cache')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().cached, num,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
|
||||
@retry_before_failing()
|
||||
def test_muse_vmem_free(self):
|
||||
num = muse('Free')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().free, num,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
@unittest.skipIf(not MUSE_AVAILABLE, "muse not installed")
|
||||
@retry_before_failing()
|
||||
def test_muse_vmem_buffers(self):
|
||||
num = muse('Buffer')
|
||||
self.assertAlmostEqual(psutil.virtual_memory().buffers, num,
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
def test_cpu_stats_ctx_switches(self):
|
||||
self.assertAlmostEqual(psutil.cpu_stats().ctx_switches,
|
||||
sysctl('vm.stats.sys.v_swtch'), delta=1000)
|
||||
|
||||
def test_cpu_stats_interrupts(self):
|
||||
self.assertAlmostEqual(psutil.cpu_stats().interrupts,
|
||||
sysctl('vm.stats.sys.v_intr'), delta=1000)
|
||||
|
||||
def test_cpu_stats_soft_interrupts(self):
|
||||
self.assertAlmostEqual(psutil.cpu_stats().soft_interrupts,
|
||||
sysctl('vm.stats.sys.v_soft'), delta=1000)
|
||||
|
||||
def test_cpu_stats_syscalls(self):
|
||||
self.assertAlmostEqual(psutil.cpu_stats().syscalls,
|
||||
sysctl('vm.stats.sys.v_syscall'), delta=1000)
|
||||
|
||||
# def test_cpu_stats_traps(self):
|
||||
# self.assertAlmostEqual(psutil.cpu_stats().traps,
|
||||
# sysctl('vm.stats.sys.v_trap'), delta=1000)
|
||||
|
||||
# --- others
|
||||
|
||||
def test_boot_time(self):
|
||||
s = sysctl('sysctl kern.boottime')
|
||||
s = s[s.find(" sec = ") + 7:]
|
||||
s = s[:s.find(',')]
|
||||
btime = int(s)
|
||||
self.assertEqual(btime, psutil.boot_time())
|
||||
|
||||
# --- sensors_battery
|
||||
|
||||
@unittest.skipIf(not HAS_BATTERY, "no battery")
|
||||
def test_sensors_battery(self):
|
||||
def secs2hours(secs):
|
||||
m, s = divmod(secs, 60)
|
||||
h, m = divmod(m, 60)
|
||||
return "%d:%02d" % (h, m)
|
||||
|
||||
out = sh("acpiconf -i 0")
|
||||
fields = dict([(x.split('\t')[0], x.split('\t')[-1])
|
||||
for x in out.split("\n")])
|
||||
metrics = psutil.sensors_battery()
|
||||
percent = int(fields['Remaining capacity:'].replace('%', ''))
|
||||
remaining_time = fields['Remaining time:']
|
||||
self.assertEqual(metrics.percent, percent)
|
||||
if remaining_time == 'unknown':
|
||||
self.assertEqual(metrics.secsleft, psutil.POWER_TIME_UNLIMITED)
|
||||
else:
|
||||
self.assertEqual(secs2hours(metrics.secsleft), remaining_time)
|
||||
|
||||
@unittest.skipIf(not HAS_BATTERY, "no battery")
|
||||
def test_sensors_battery_against_sysctl(self):
|
||||
self.assertEqual(psutil.sensors_battery().percent,
|
||||
sysctl("hw.acpi.battery.life"))
|
||||
self.assertEqual(psutil.sensors_battery().power_plugged,
|
||||
sysctl("hw.acpi.acline") == 1)
|
||||
secsleft = psutil.sensors_battery().secsleft
|
||||
if secsleft < 0:
|
||||
self.assertEqual(sysctl("hw.acpi.battery.time"), -1)
|
||||
else:
|
||||
self.assertEqual(secsleft, sysctl("hw.acpi.battery.time") * 60)
|
||||
|
||||
@unittest.skipIf(HAS_BATTERY, "has battery")
|
||||
def test_sensors_battery_no_battery(self):
|
||||
# If no battery is present one of these calls is supposed
|
||||
# to fail, see:
|
||||
# https://github.com/giampaolo/psutil/issues/1074
|
||||
with self.assertRaises(RuntimeError):
|
||||
sysctl("hw.acpi.battery.life")
|
||||
sysctl("hw.acpi.battery.time")
|
||||
sysctl("hw.acpi.acline")
|
||||
self.assertIsNone(psutil.sensors_battery())
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- OpenBSD
|
||||
# =====================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not OPENBSD, "OPENBSD only")
|
||||
class OpenBSDSpecificTestCase(unittest.TestCase):
|
||||
|
||||
def test_boot_time(self):
|
||||
s = sysctl('kern.boottime')
|
||||
sys_bt = datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %Y")
|
||||
psutil_bt = datetime.datetime.fromtimestamp(psutil.boot_time())
|
||||
self.assertEqual(sys_bt, psutil_bt)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- NetBSD
|
||||
# =====================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not NETBSD, "NETBSD only")
|
||||
class NetBSDSpecificTestCase(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def parse_meminfo(look_for):
|
||||
with open('/proc/meminfo', 'rb') as f:
|
||||
for line in f:
|
||||
if line.startswith(look_for):
|
||||
return int(line.split()[1]) * 1024
|
||||
raise ValueError("can't find %s" % look_for)
|
||||
|
||||
def test_vmem_total(self):
|
||||
self.assertEqual(
|
||||
psutil.virtual_memory().total, self.parse_meminfo("MemTotal:"))
|
||||
|
||||
def test_vmem_free(self):
|
||||
self.assertAlmostEqual(
|
||||
psutil.virtual_memory().free, self.parse_meminfo("MemFree:"),
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
def test_vmem_buffers(self):
|
||||
self.assertAlmostEqual(
|
||||
psutil.virtual_memory().buffers, self.parse_meminfo("Buffers:"),
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
def test_vmem_shared(self):
|
||||
self.assertAlmostEqual(
|
||||
psutil.virtual_memory().shared, self.parse_meminfo("MemShared:"),
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
def test_swapmem_total(self):
|
||||
self.assertAlmostEqual(
|
||||
psutil.swap_memory().total, self.parse_meminfo("SwapTotal:"),
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
def test_swapmem_free(self):
|
||||
self.assertAlmostEqual(
|
||||
psutil.swap_memory().free, self.parse_meminfo("SwapFree:"),
|
||||
delta=MEMORY_TOLERANCE)
|
||||
|
||||
def test_swapmem_used(self):
|
||||
smem = psutil.swap_memory()
|
||||
self.assertEqual(smem.used, smem.total - smem.free)
|
||||
|
||||
def test_cpu_stats_interrupts(self):
|
||||
with open('/proc/stat', 'rb') as f:
|
||||
for line in f:
|
||||
if line.startswith(b'intr'):
|
||||
interrupts = int(line.split()[1])
|
||||
break
|
||||
else:
|
||||
raise ValueError("couldn't find line")
|
||||
self.assertAlmostEqual(
|
||||
psutil.cpu_stats().interrupts, interrupts, delta=1000)
|
||||
|
||||
def test_cpu_stats_ctx_switches(self):
|
||||
with open('/proc/stat', 'rb') as f:
|
||||
for line in f:
|
||||
if line.startswith(b'ctxt'):
|
||||
ctx_switches = int(line.split()[1])
|
||||
break
|
||||
else:
|
||||
raise ValueError("couldn't find line")
|
||||
self.assertAlmostEqual(
|
||||
psutil.cpu_stats().ctx_switches, ctx_switches, delta=1000)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
525
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_connections.py
поставляемый
Normal file
525
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_connections.py
поставляемый
Normal file
|
@ -0,0 +1,525 @@
|
|||
#!/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.
|
||||
|
||||
"""Tests for net_connections() and Process.connections() APIs."""
|
||||
|
||||
import os
|
||||
import socket
|
||||
import textwrap
|
||||
from contextlib import closing
|
||||
from socket import AF_INET
|
||||
from socket import AF_INET6
|
||||
from socket import SOCK_DGRAM
|
||||
from socket import SOCK_STREAM
|
||||
|
||||
import psutil
|
||||
from psutil import FREEBSD
|
||||
from psutil import LINUX
|
||||
from psutil import NETBSD
|
||||
from psutil import OPENBSD
|
||||
from psutil import OSX
|
||||
from psutil import POSIX
|
||||
from psutil import SUNOS
|
||||
from psutil import WINDOWS
|
||||
from psutil._common import supports_ipv6
|
||||
from psutil._compat import PY3
|
||||
from psutil.tests import AF_UNIX
|
||||
from psutil.tests import bind_socket
|
||||
from psutil.tests import bind_unix_socket
|
||||
from psutil.tests import check_connection_ntuple
|
||||
from psutil.tests import create_sockets
|
||||
from psutil.tests import get_free_port
|
||||
from psutil.tests import HAS_CONNECTIONS_UNIX
|
||||
from psutil.tests import pyrun
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import safe_rmpath
|
||||
from psutil.tests import skip_on_access_denied
|
||||
from psutil.tests import tcp_socketpair
|
||||
from psutil.tests import TESTFN
|
||||
from psutil.tests import TRAVIS
|
||||
from psutil.tests import unittest
|
||||
from psutil.tests import unix_socket_path
|
||||
from psutil.tests import unix_socketpair
|
||||
from psutil.tests import wait_for_file
|
||||
|
||||
|
||||
thisproc = psutil.Process()
|
||||
|
||||
|
||||
class Base(object):
|
||||
|
||||
def setUp(self):
|
||||
if not NETBSD:
|
||||
# NetBSD opens a UNIX socket to /var/log/run.
|
||||
cons = thisproc.connections(kind='all')
|
||||
assert not cons, cons
|
||||
|
||||
def tearDown(self):
|
||||
safe_rmpath(TESTFN)
|
||||
reap_children()
|
||||
if not NETBSD:
|
||||
# Make sure we closed all resources.
|
||||
# NetBSD opens a UNIX socket to /var/log/run.
|
||||
cons = thisproc.connections(kind='all')
|
||||
assert not cons, cons
|
||||
|
||||
def get_conn_from_sock(self, sock):
|
||||
cons = thisproc.connections(kind='all')
|
||||
smap = dict([(c.fd, c) for c in cons])
|
||||
if NETBSD:
|
||||
# NetBSD opens a UNIX socket to /var/log/run
|
||||
# so there may be more connections.
|
||||
return smap[sock.fileno()]
|
||||
else:
|
||||
self.assertEqual(len(cons), 1)
|
||||
if cons[0].fd != -1:
|
||||
self.assertEqual(smap[sock.fileno()].fd, sock.fileno())
|
||||
return cons[0]
|
||||
|
||||
def check_socket(self, sock, conn=None):
|
||||
"""Given a socket, makes sure it matches the one obtained
|
||||
via psutil. It assumes this process created one connection
|
||||
only (the one supposed to be checked).
|
||||
"""
|
||||
if conn is None:
|
||||
conn = self.get_conn_from_sock(sock)
|
||||
check_connection_ntuple(conn)
|
||||
|
||||
# fd, family, type
|
||||
if conn.fd != -1:
|
||||
self.assertEqual(conn.fd, sock.fileno())
|
||||
self.assertEqual(conn.family, sock.family)
|
||||
# see: http://bugs.python.org/issue30204
|
||||
self.assertEqual(
|
||||
conn.type, sock.getsockopt(socket.SOL_SOCKET, socket.SO_TYPE))
|
||||
|
||||
# local address
|
||||
laddr = sock.getsockname()
|
||||
if not laddr and PY3 and isinstance(laddr, bytes):
|
||||
# See: http://bugs.python.org/issue30205
|
||||
laddr = laddr.decode()
|
||||
if sock.family == AF_INET6:
|
||||
laddr = laddr[:2]
|
||||
if sock.family == AF_UNIX and OPENBSD:
|
||||
# No addresses are set for UNIX sockets on OpenBSD.
|
||||
pass
|
||||
else:
|
||||
self.assertEqual(conn.laddr, laddr)
|
||||
|
||||
# XXX Solaris can't retrieve system-wide UNIX sockets
|
||||
if sock.family == AF_UNIX and HAS_CONNECTIONS_UNIX:
|
||||
cons = thisproc.connections(kind='all')
|
||||
self.compare_procsys_connections(os.getpid(), cons)
|
||||
return conn
|
||||
|
||||
def compare_procsys_connections(self, pid, proc_cons, kind='all'):
|
||||
"""Given a process PID and its list of connections compare
|
||||
those against system-wide connections retrieved via
|
||||
psutil.net_connections.
|
||||
"""
|
||||
try:
|
||||
sys_cons = psutil.net_connections(kind=kind)
|
||||
except psutil.AccessDenied:
|
||||
# On OSX, system-wide connections are retrieved by iterating
|
||||
# over all processes
|
||||
if OSX:
|
||||
return
|
||||
else:
|
||||
raise
|
||||
# Filter for this proc PID and exlucde PIDs from the tuple.
|
||||
sys_cons = [c[:-1] for c in sys_cons if c.pid == pid]
|
||||
sys_cons.sort()
|
||||
proc_cons.sort()
|
||||
self.assertEqual(proc_cons, sys_cons)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- Test unconnected sockets
|
||||
# =====================================================================
|
||||
|
||||
|
||||
class TestUnconnectedSockets(Base, unittest.TestCase):
|
||||
"""Tests sockets which are open but not connected to anything."""
|
||||
|
||||
def test_tcp_v4(self):
|
||||
addr = ("127.0.0.1", get_free_port())
|
||||
with closing(bind_socket(AF_INET, SOCK_STREAM, addr=addr)) as sock:
|
||||
conn = self.check_socket(sock)
|
||||
assert not conn.raddr
|
||||
self.assertEqual(conn.status, psutil.CONN_LISTEN)
|
||||
|
||||
@unittest.skipIf(not supports_ipv6(), "IPv6 not supported")
|
||||
def test_tcp_v6(self):
|
||||
addr = ("::1", get_free_port())
|
||||
with closing(bind_socket(AF_INET6, SOCK_STREAM, addr=addr)) as sock:
|
||||
conn = self.check_socket(sock)
|
||||
assert not conn.raddr
|
||||
self.assertEqual(conn.status, psutil.CONN_LISTEN)
|
||||
|
||||
def test_udp_v4(self):
|
||||
addr = ("127.0.0.1", get_free_port())
|
||||
with closing(bind_socket(AF_INET, SOCK_DGRAM, addr=addr)) as sock:
|
||||
conn = self.check_socket(sock)
|
||||
assert not conn.raddr
|
||||
self.assertEqual(conn.status, psutil.CONN_NONE)
|
||||
|
||||
@unittest.skipIf(not supports_ipv6(), "IPv6 not supported")
|
||||
def test_udp_v6(self):
|
||||
addr = ("::1", get_free_port())
|
||||
with closing(bind_socket(AF_INET6, SOCK_DGRAM, addr=addr)) as sock:
|
||||
conn = self.check_socket(sock)
|
||||
assert not conn.raddr
|
||||
self.assertEqual(conn.status, psutil.CONN_NONE)
|
||||
|
||||
@unittest.skipIf(not POSIX, 'POSIX only')
|
||||
def test_unix_tcp(self):
|
||||
with unix_socket_path() as name:
|
||||
with closing(bind_unix_socket(name, type=SOCK_STREAM)) as sock:
|
||||
conn = self.check_socket(sock)
|
||||
assert not conn.raddr
|
||||
self.assertEqual(conn.status, psutil.CONN_NONE)
|
||||
|
||||
@unittest.skipIf(not POSIX, 'POSIX only')
|
||||
def test_unix_udp(self):
|
||||
with unix_socket_path() as name:
|
||||
with closing(bind_unix_socket(name, type=SOCK_STREAM)) as sock:
|
||||
conn = self.check_socket(sock)
|
||||
assert not conn.raddr
|
||||
self.assertEqual(conn.status, psutil.CONN_NONE)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- Test connected sockets
|
||||
# =====================================================================
|
||||
|
||||
|
||||
class TestConnectedSocketPairs(Base, unittest.TestCase):
|
||||
"""Test socket pairs which are are actually connected to
|
||||
each other.
|
||||
"""
|
||||
|
||||
# On SunOS, even after we close() it, the server socket stays around
|
||||
# in TIME_WAIT state.
|
||||
@unittest.skipIf(SUNOS, "unreliable on SUONS")
|
||||
def test_tcp(self):
|
||||
addr = ("127.0.0.1", get_free_port())
|
||||
assert not thisproc.connections(kind='tcp4')
|
||||
server, client = tcp_socketpair(AF_INET, addr=addr)
|
||||
try:
|
||||
cons = thisproc.connections(kind='tcp4')
|
||||
self.assertEqual(len(cons), 2)
|
||||
self.assertEqual(cons[0].status, psutil.CONN_ESTABLISHED)
|
||||
self.assertEqual(cons[1].status, psutil.CONN_ESTABLISHED)
|
||||
# May not be fast enough to change state so it stays
|
||||
# commenteed.
|
||||
# client.close()
|
||||
# cons = thisproc.connections(kind='all')
|
||||
# self.assertEqual(len(cons), 1)
|
||||
# self.assertEqual(cons[0].status, psutil.CONN_CLOSE_WAIT)
|
||||
finally:
|
||||
server.close()
|
||||
client.close()
|
||||
|
||||
@unittest.skipIf(not POSIX, 'POSIX only')
|
||||
def test_unix(self):
|
||||
with unix_socket_path() as name:
|
||||
server, client = unix_socketpair(name)
|
||||
try:
|
||||
cons = thisproc.connections(kind='unix')
|
||||
assert not (cons[0].laddr and cons[0].raddr)
|
||||
assert not (cons[1].laddr and cons[1].raddr)
|
||||
if NETBSD:
|
||||
# On NetBSD creating a UNIX socket will cause
|
||||
# a UNIX connection to /var/run/log.
|
||||
cons = [c for c in cons if c.raddr != '/var/run/log']
|
||||
self.assertEqual(len(cons), 2)
|
||||
if LINUX or FREEBSD or SUNOS:
|
||||
# remote path is never set
|
||||
self.assertEqual(cons[0].raddr, "")
|
||||
self.assertEqual(cons[1].raddr, "")
|
||||
# one local address should though
|
||||
self.assertEqual(name, cons[0].laddr or cons[1].laddr)
|
||||
elif OPENBSD:
|
||||
# No addresses whatsoever here.
|
||||
for addr in (cons[0].laddr, cons[0].raddr,
|
||||
cons[1].laddr, cons[1].raddr):
|
||||
self.assertEqual(addr, "")
|
||||
else:
|
||||
# On other systems either the laddr or raddr
|
||||
# of both peers are set.
|
||||
self.assertEqual(cons[0].laddr or cons[1].laddr, name)
|
||||
self.assertEqual(cons[0].raddr or cons[1].raddr, name)
|
||||
finally:
|
||||
server.close()
|
||||
client.close()
|
||||
|
||||
@skip_on_access_denied(only_if=OSX)
|
||||
def test_combos(self):
|
||||
def check_conn(proc, conn, family, type, laddr, raddr, status, kinds):
|
||||
all_kinds = ("all", "inet", "inet4", "inet6", "tcp", "tcp4",
|
||||
"tcp6", "udp", "udp4", "udp6")
|
||||
check_connection_ntuple(conn)
|
||||
self.assertEqual(conn.family, family)
|
||||
self.assertEqual(conn.type, type)
|
||||
self.assertEqual(conn.laddr, laddr)
|
||||
self.assertEqual(conn.raddr, raddr)
|
||||
self.assertEqual(conn.status, status)
|
||||
for kind in all_kinds:
|
||||
cons = proc.connections(kind=kind)
|
||||
if kind in kinds:
|
||||
assert cons
|
||||
else:
|
||||
assert not cons, cons
|
||||
# compare against system-wide connections
|
||||
# XXX Solaris can't retrieve system-wide UNIX
|
||||
# sockets.
|
||||
if HAS_CONNECTIONS_UNIX:
|
||||
self.compare_procsys_connections(proc.pid, [conn])
|
||||
|
||||
tcp_template = textwrap.dedent("""
|
||||
import socket, time
|
||||
s = socket.socket($family, socket.SOCK_STREAM)
|
||||
s.bind(('$addr', 0))
|
||||
s.listen(1)
|
||||
with open('$testfn', 'w') as f:
|
||||
f.write(str(s.getsockname()[:2]))
|
||||
time.sleep(60)
|
||||
""")
|
||||
|
||||
udp_template = textwrap.dedent("""
|
||||
import socket, time
|
||||
s = socket.socket($family, socket.SOCK_DGRAM)
|
||||
s.bind(('$addr', 0))
|
||||
with open('$testfn', 'w') as f:
|
||||
f.write(str(s.getsockname()[:2]))
|
||||
time.sleep(60)
|
||||
""")
|
||||
|
||||
from string import Template
|
||||
testfile = os.path.basename(TESTFN)
|
||||
tcp4_template = Template(tcp_template).substitute(
|
||||
family=int(AF_INET), addr="127.0.0.1", testfn=testfile)
|
||||
udp4_template = Template(udp_template).substitute(
|
||||
family=int(AF_INET), addr="127.0.0.1", testfn=testfile)
|
||||
tcp6_template = Template(tcp_template).substitute(
|
||||
family=int(AF_INET6), addr="::1", testfn=testfile)
|
||||
udp6_template = Template(udp_template).substitute(
|
||||
family=int(AF_INET6), addr="::1", testfn=testfile)
|
||||
|
||||
# launch various subprocess instantiating a socket of various
|
||||
# families and types to enrich psutil results
|
||||
tcp4_proc = pyrun(tcp4_template)
|
||||
tcp4_addr = eval(wait_for_file(testfile))
|
||||
udp4_proc = pyrun(udp4_template)
|
||||
udp4_addr = eval(wait_for_file(testfile))
|
||||
if supports_ipv6():
|
||||
tcp6_proc = pyrun(tcp6_template)
|
||||
tcp6_addr = eval(wait_for_file(testfile))
|
||||
udp6_proc = pyrun(udp6_template)
|
||||
udp6_addr = eval(wait_for_file(testfile))
|
||||
else:
|
||||
tcp6_proc = None
|
||||
udp6_proc = None
|
||||
tcp6_addr = None
|
||||
udp6_addr = None
|
||||
|
||||
for p in thisproc.children():
|
||||
cons = p.connections()
|
||||
self.assertEqual(len(cons), 1)
|
||||
for conn in cons:
|
||||
# TCP v4
|
||||
if p.pid == tcp4_proc.pid:
|
||||
check_conn(p, conn, AF_INET, SOCK_STREAM, tcp4_addr, (),
|
||||
psutil.CONN_LISTEN,
|
||||
("all", "inet", "inet4", "tcp", "tcp4"))
|
||||
# UDP v4
|
||||
elif p.pid == udp4_proc.pid:
|
||||
check_conn(p, conn, AF_INET, SOCK_DGRAM, udp4_addr, (),
|
||||
psutil.CONN_NONE,
|
||||
("all", "inet", "inet4", "udp", "udp4"))
|
||||
# TCP v6
|
||||
elif p.pid == getattr(tcp6_proc, "pid", None):
|
||||
check_conn(p, conn, AF_INET6, SOCK_STREAM, tcp6_addr, (),
|
||||
psutil.CONN_LISTEN,
|
||||
("all", "inet", "inet6", "tcp", "tcp6"))
|
||||
# UDP v6
|
||||
elif p.pid == getattr(udp6_proc, "pid", None):
|
||||
check_conn(p, conn, AF_INET6, SOCK_DGRAM, udp6_addr, (),
|
||||
psutil.CONN_NONE,
|
||||
("all", "inet", "inet6", "udp", "udp6"))
|
||||
|
||||
# err
|
||||
self.assertRaises(ValueError, p.connections, kind='???')
|
||||
|
||||
def test_multi_sockets_filtering(self):
|
||||
with create_sockets() as socks:
|
||||
cons = thisproc.connections(kind='all')
|
||||
self.assertEqual(len(cons), len(socks))
|
||||
# tcp
|
||||
cons = thisproc.connections(kind='tcp')
|
||||
self.assertEqual(len(cons), 2 if supports_ipv6() else 1)
|
||||
for conn in cons:
|
||||
self.assertIn(conn.family, (AF_INET, AF_INET6))
|
||||
self.assertEqual(conn.type, SOCK_STREAM)
|
||||
# tcp4
|
||||
cons = thisproc.connections(kind='tcp4')
|
||||
self.assertEqual(len(cons), 1)
|
||||
self.assertEqual(cons[0].family, AF_INET)
|
||||
self.assertEqual(cons[0].type, SOCK_STREAM)
|
||||
# tcp6
|
||||
if supports_ipv6():
|
||||
cons = thisproc.connections(kind='tcp6')
|
||||
self.assertEqual(len(cons), 1)
|
||||
self.assertEqual(cons[0].family, AF_INET6)
|
||||
self.assertEqual(cons[0].type, SOCK_STREAM)
|
||||
# udp
|
||||
cons = thisproc.connections(kind='udp')
|
||||
self.assertEqual(len(cons), 2 if supports_ipv6() else 1)
|
||||
for conn in cons:
|
||||
self.assertIn(conn.family, (AF_INET, AF_INET6))
|
||||
self.assertEqual(conn.type, SOCK_DGRAM)
|
||||
# udp4
|
||||
cons = thisproc.connections(kind='udp4')
|
||||
self.assertEqual(len(cons), 1)
|
||||
self.assertEqual(cons[0].family, AF_INET)
|
||||
self.assertEqual(cons[0].type, SOCK_DGRAM)
|
||||
# udp6
|
||||
if supports_ipv6():
|
||||
cons = thisproc.connections(kind='udp6')
|
||||
self.assertEqual(len(cons), 1)
|
||||
self.assertEqual(cons[0].family, AF_INET6)
|
||||
self.assertEqual(cons[0].type, SOCK_DGRAM)
|
||||
# inet
|
||||
cons = thisproc.connections(kind='inet')
|
||||
self.assertEqual(len(cons), 4 if supports_ipv6() else 2)
|
||||
for conn in cons:
|
||||
self.assertIn(conn.family, (AF_INET, AF_INET6))
|
||||
self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
|
||||
# inet6
|
||||
if supports_ipv6():
|
||||
cons = thisproc.connections(kind='inet6')
|
||||
self.assertEqual(len(cons), 2)
|
||||
for conn in cons:
|
||||
self.assertEqual(conn.family, AF_INET6)
|
||||
self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
|
||||
# unix
|
||||
if HAS_CONNECTIONS_UNIX:
|
||||
cons = thisproc.connections(kind='unix')
|
||||
self.assertEqual(len(cons), 3)
|
||||
for conn in cons:
|
||||
self.assertEqual(conn.family, AF_UNIX)
|
||||
self.assertIn(conn.type, (SOCK_STREAM, SOCK_DGRAM))
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- Miscellaneous tests
|
||||
# =====================================================================
|
||||
|
||||
|
||||
class TestSystemWideConnections(Base, unittest.TestCase):
|
||||
"""Tests for net_connections()."""
|
||||
|
||||
@skip_on_access_denied()
|
||||
def test_it(self):
|
||||
def check(cons, families, types_):
|
||||
AF_UNIX = getattr(socket, 'AF_UNIX', object())
|
||||
for conn in cons:
|
||||
self.assertIn(conn.family, families, msg=conn)
|
||||
if conn.family != AF_UNIX:
|
||||
self.assertIn(conn.type, types_, msg=conn)
|
||||
check_connection_ntuple(conn)
|
||||
|
||||
with create_sockets():
|
||||
from psutil._common import conn_tmap
|
||||
for kind, groups in conn_tmap.items():
|
||||
# XXX: SunOS does not retrieve UNIX sockets.
|
||||
if kind == 'unix' and not HAS_CONNECTIONS_UNIX:
|
||||
continue
|
||||
families, types_ = groups
|
||||
cons = psutil.net_connections(kind)
|
||||
self.assertEqual(len(cons), len(set(cons)))
|
||||
check(cons, families, types_)
|
||||
|
||||
self.assertRaises(ValueError, psutil.net_connections, kind='???')
|
||||
|
||||
@skip_on_access_denied()
|
||||
def test_multi_socks(self):
|
||||
with create_sockets() as socks:
|
||||
cons = [x for x in psutil.net_connections(kind='all')
|
||||
if x.pid == os.getpid()]
|
||||
self.assertEqual(len(cons), len(socks))
|
||||
|
||||
@skip_on_access_denied()
|
||||
# See: https://travis-ci.org/giampaolo/psutil/jobs/237566297
|
||||
@unittest.skipIf(OSX and TRAVIS, "unreliable on OSX + TRAVIS")
|
||||
def test_multi_sockets_procs(self):
|
||||
# Creates multiple sub processes, each creating different
|
||||
# sockets. For each process check that proc.connections()
|
||||
# and net_connections() return the same results.
|
||||
# This is done mainly to check whether net_connections()'s
|
||||
# pid is properly set, see:
|
||||
# https://github.com/giampaolo/psutil/issues/1013
|
||||
with create_sockets() as socks:
|
||||
expected = len(socks)
|
||||
pids = []
|
||||
times = 10
|
||||
for i in range(times):
|
||||
fname = os.path.realpath(TESTFN) + str(i)
|
||||
src = textwrap.dedent("""\
|
||||
import time, os
|
||||
from psutil.tests import create_sockets
|
||||
with create_sockets():
|
||||
with open('%s', 'w') as f:
|
||||
f.write(str(os.getpid()))
|
||||
time.sleep(60)
|
||||
""" % fname)
|
||||
sproc = pyrun(src)
|
||||
pids.append(sproc.pid)
|
||||
self.addCleanup(safe_rmpath, fname)
|
||||
|
||||
# sync
|
||||
for i in range(times):
|
||||
fname = TESTFN + str(i)
|
||||
wait_for_file(fname)
|
||||
|
||||
syscons = [x for x in psutil.net_connections(kind='all') if x.pid
|
||||
in pids]
|
||||
for pid in pids:
|
||||
self.assertEqual(len([x for x in syscons if x.pid == pid]),
|
||||
expected)
|
||||
p = psutil.Process(pid)
|
||||
self.assertEqual(len(p.connections('all')), expected)
|
||||
|
||||
|
||||
# =====================================================================
|
||||
# --- Miscellaneous tests
|
||||
# =====================================================================
|
||||
|
||||
|
||||
class TestMisc(unittest.TestCase):
|
||||
|
||||
def test_connection_constants(self):
|
||||
ints = []
|
||||
strs = []
|
||||
for name in dir(psutil):
|
||||
if name.startswith('CONN_'):
|
||||
num = getattr(psutil, name)
|
||||
str_ = str(num)
|
||||
assert str_.isupper(), str_
|
||||
self.assertNotIn(str, strs)
|
||||
self.assertNotIn(num, ints)
|
||||
ints.append(num)
|
||||
strs.append(str_)
|
||||
if SUNOS:
|
||||
psutil.CONN_IDLE
|
||||
psutil.CONN_BOUND
|
||||
if WINDOWS:
|
||||
psutil.CONN_DELETE_TCB
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
651
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_contracts.py
поставляемый
Normal file
651
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_contracts.py
поставляемый
Normal file
|
@ -0,0 +1,651 @@
|
|||
#!/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.
|
||||
|
||||
"""Contracts tests. These tests mainly check API sanity in terms of
|
||||
returned types and APIs availability.
|
||||
Some of these are duplicates of tests test_system.py and test_process.py
|
||||
"""
|
||||
|
||||
import errno
|
||||
import os
|
||||
import stat
|
||||
import time
|
||||
import traceback
|
||||
import warnings
|
||||
from contextlib import closing
|
||||
|
||||
from psutil import AIX
|
||||
from psutil import BSD
|
||||
from psutil import FREEBSD
|
||||
from psutil import LINUX
|
||||
from psutil import NETBSD
|
||||
from psutil import OPENBSD
|
||||
from psutil import OSX
|
||||
from psutil import POSIX
|
||||
from psutil import SUNOS
|
||||
from psutil import WINDOWS
|
||||
from psutil._compat import callable
|
||||
from psutil._compat import long
|
||||
from psutil.tests import bind_unix_socket
|
||||
from psutil.tests import check_connection_ntuple
|
||||
from psutil.tests import get_kernel_version
|
||||
from psutil.tests import HAS_CONNECTIONS_UNIX
|
||||
from psutil.tests import HAS_RLIMIT
|
||||
from psutil.tests import HAS_SENSORS_FANS
|
||||
from psutil.tests import HAS_SENSORS_TEMPERATURES
|
||||
from psutil.tests import is_namedtuple
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import safe_rmpath
|
||||
from psutil.tests import skip_on_access_denied
|
||||
from psutil.tests import TESTFN
|
||||
from psutil.tests import unittest
|
||||
from psutil.tests import unix_socket_path
|
||||
from psutil.tests import VALID_PROC_STATUSES
|
||||
from psutil.tests import warn
|
||||
import psutil
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- APIs availability
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestAvailability(unittest.TestCase):
|
||||
"""Make sure code reflects what doc promises in terms of APIs
|
||||
availability.
|
||||
"""
|
||||
|
||||
def test_cpu_affinity(self):
|
||||
hasit = LINUX or WINDOWS or FREEBSD
|
||||
self.assertEqual(hasattr(psutil.Process, "cpu_affinity"), hasit)
|
||||
|
||||
def test_win_service(self):
|
||||
self.assertEqual(hasattr(psutil, "win_service_iter"), WINDOWS)
|
||||
self.assertEqual(hasattr(psutil, "win_service_get"), WINDOWS)
|
||||
|
||||
def test_PROCFS_PATH(self):
|
||||
self.assertEqual(hasattr(psutil, "PROCFS_PATH"),
|
||||
LINUX or SUNOS or AIX)
|
||||
|
||||
def test_win_priority(self):
|
||||
ae = self.assertEqual
|
||||
ae(hasattr(psutil, "ABOVE_NORMAL_PRIORITY_CLASS"), WINDOWS)
|
||||
ae(hasattr(psutil, "BELOW_NORMAL_PRIORITY_CLASS"), WINDOWS)
|
||||
ae(hasattr(psutil, "HIGH_PRIORITY_CLASS"), WINDOWS)
|
||||
ae(hasattr(psutil, "IDLE_PRIORITY_CLASS"), WINDOWS)
|
||||
ae(hasattr(psutil, "NORMAL_PRIORITY_CLASS"), WINDOWS)
|
||||
ae(hasattr(psutil, "REALTIME_PRIORITY_CLASS"), WINDOWS)
|
||||
|
||||
def test_linux_ioprio(self):
|
||||
ae = self.assertEqual
|
||||
ae(hasattr(psutil, "IOPRIO_CLASS_NONE"), LINUX)
|
||||
ae(hasattr(psutil, "IOPRIO_CLASS_RT"), LINUX)
|
||||
ae(hasattr(psutil, "IOPRIO_CLASS_BE"), LINUX)
|
||||
ae(hasattr(psutil, "IOPRIO_CLASS_IDLE"), LINUX)
|
||||
|
||||
def test_linux_rlimit(self):
|
||||
ae = self.assertEqual
|
||||
hasit = LINUX and get_kernel_version() >= (2, 6, 36)
|
||||
ae(hasattr(psutil.Process, "rlimit"), hasit)
|
||||
ae(hasattr(psutil, "RLIM_INFINITY"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_AS"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_CORE"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_CPU"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_DATA"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_FSIZE"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_LOCKS"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_MEMLOCK"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_NOFILE"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_NPROC"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_RSS"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_STACK"), hasit)
|
||||
|
||||
hasit = LINUX and get_kernel_version() >= (3, 0)
|
||||
ae(hasattr(psutil, "RLIMIT_MSGQUEUE"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_NICE"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_RTPRIO"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_RTTIME"), hasit)
|
||||
ae(hasattr(psutil, "RLIMIT_SIGPENDING"), hasit)
|
||||
|
||||
def test_cpu_freq(self):
|
||||
linux = (LINUX and
|
||||
(os.path.exists("/sys/devices/system/cpu/cpufreq") or
|
||||
os.path.exists("/sys/devices/system/cpu/cpu0/cpufreq")))
|
||||
self.assertEqual(hasattr(psutil, "cpu_freq"), linux or OSX or WINDOWS)
|
||||
|
||||
def test_sensors_temperatures(self):
|
||||
self.assertEqual(hasattr(psutil, "sensors_temperatures"), LINUX)
|
||||
|
||||
def test_sensors_fans(self):
|
||||
self.assertEqual(hasattr(psutil, "sensors_fans"), LINUX)
|
||||
|
||||
def test_battery(self):
|
||||
self.assertEqual(hasattr(psutil, "sensors_battery"),
|
||||
LINUX or WINDOWS or FREEBSD or OSX)
|
||||
|
||||
def test_proc_environ(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "environ"),
|
||||
LINUX or OSX or WINDOWS)
|
||||
|
||||
def test_proc_uids(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)
|
||||
|
||||
def test_proc_gids(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "uids"), POSIX)
|
||||
|
||||
def test_proc_terminal(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "terminal"), POSIX)
|
||||
|
||||
def test_proc_ionice(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "ionice"), LINUX or WINDOWS)
|
||||
|
||||
def test_proc_rlimit(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "rlimit"), LINUX)
|
||||
|
||||
def test_proc_io_counters(self):
|
||||
hasit = hasattr(psutil.Process, "io_counters")
|
||||
self.assertEqual(hasit, False if OSX or SUNOS else True)
|
||||
|
||||
def test_proc_num_fds(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "num_fds"), POSIX)
|
||||
|
||||
def test_proc_num_handles(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "num_handles"), WINDOWS)
|
||||
|
||||
def test_proc_cpu_affinity(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "cpu_affinity"),
|
||||
LINUX or WINDOWS or FREEBSD)
|
||||
|
||||
def test_proc_cpu_num(self):
|
||||
self.assertEqual(hasattr(psutil.Process, "cpu_num"),
|
||||
LINUX or FREEBSD or SUNOS)
|
||||
|
||||
def test_proc_memory_maps(self):
|
||||
hasit = hasattr(psutil.Process, "memory_maps")
|
||||
self.assertEqual(hasit, False if OPENBSD or NETBSD or AIX else True)
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- Test deprecations
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestDeprecations(unittest.TestCase):
|
||||
|
||||
def test_memory_info_ex(self):
|
||||
with warnings.catch_warnings(record=True) as ws:
|
||||
psutil.Process().memory_info_ex()
|
||||
w = ws[0]
|
||||
self.assertIsInstance(w.category(), FutureWarning)
|
||||
self.assertIn("memory_info_ex() is deprecated", str(w.message))
|
||||
self.assertIn("use memory_info() instead", str(w.message))
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- System API types
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestSystem(unittest.TestCase):
|
||||
"""Check the return types of system related APIs.
|
||||
Mainly we want to test we never return unicode on Python 2, see:
|
||||
https://github.com/giampaolo/psutil/issues/1039
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.proc = psutil.Process()
|
||||
|
||||
def tearDown(self):
|
||||
safe_rmpath(TESTFN)
|
||||
|
||||
def test_cpu_times(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
ret = psutil.cpu_times()
|
||||
assert is_namedtuple(ret)
|
||||
for n in ret:
|
||||
self.assertIsInstance(n, float)
|
||||
self.assertGreaterEqual(n, 0)
|
||||
|
||||
def test_io_counters(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for k in psutil.disk_io_counters(perdisk=True):
|
||||
self.assertIsInstance(k, str)
|
||||
|
||||
def test_disk_partitions(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for disk in psutil.disk_partitions():
|
||||
self.assertIsInstance(disk.device, str)
|
||||
self.assertIsInstance(disk.mountpoint, str)
|
||||
self.assertIsInstance(disk.fstype, str)
|
||||
self.assertIsInstance(disk.opts, str)
|
||||
|
||||
@unittest.skipIf(not POSIX, 'POSIX only')
|
||||
@unittest.skipIf(not HAS_CONNECTIONS_UNIX, "can't list UNIX sockets")
|
||||
@skip_on_access_denied(only_if=OSX)
|
||||
def test_net_connections(self):
|
||||
with unix_socket_path() as name:
|
||||
with closing(bind_unix_socket(name)):
|
||||
cons = psutil.net_connections(kind='unix')
|
||||
assert cons
|
||||
for conn in cons:
|
||||
self.assertIsInstance(conn.laddr, str)
|
||||
|
||||
def test_net_if_addrs(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for ifname, addrs in psutil.net_if_addrs().items():
|
||||
self.assertIsInstance(ifname, str)
|
||||
for addr in addrs:
|
||||
self.assertIsInstance(addr.address, str)
|
||||
self.assertIsInstance(addr.netmask, (str, type(None)))
|
||||
self.assertIsInstance(addr.broadcast, (str, type(None)))
|
||||
|
||||
def test_net_if_stats(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for ifname, _ in psutil.net_if_stats().items():
|
||||
self.assertIsInstance(ifname, str)
|
||||
|
||||
def test_net_io_counters(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for ifname, _ in psutil.net_io_counters(pernic=True).items():
|
||||
self.assertIsInstance(ifname, str)
|
||||
|
||||
@unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
|
||||
def test_sensors_fans(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for name, units in psutil.sensors_fans().items():
|
||||
self.assertIsInstance(name, str)
|
||||
for unit in units:
|
||||
self.assertIsInstance(unit.label, str)
|
||||
|
||||
@unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
|
||||
def test_sensors_temperatures(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for name, units in psutil.sensors_temperatures().items():
|
||||
self.assertIsInstance(name, str)
|
||||
for unit in units:
|
||||
self.assertIsInstance(unit.label, str)
|
||||
|
||||
def test_users(self):
|
||||
# Duplicate of test_system.py. Keep it anyway.
|
||||
for user in psutil.users():
|
||||
self.assertIsInstance(user.name, str)
|
||||
self.assertIsInstance(user.terminal, (str, type(None)))
|
||||
self.assertIsInstance(user.host, (str, type(None)))
|
||||
self.assertIsInstance(user.pid, (int, type(None)))
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- Featch all processes test
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestFetchAllProcesses(unittest.TestCase):
|
||||
"""Test which iterates over all running processes and performs
|
||||
some sanity checks against Process API's returned values.
|
||||
"""
|
||||
|
||||
def setUp(self):
|
||||
if POSIX:
|
||||
import pwd
|
||||
import grp
|
||||
users = pwd.getpwall()
|
||||
groups = grp.getgrall()
|
||||
self.all_uids = set([x.pw_uid for x in users])
|
||||
self.all_usernames = set([x.pw_name for x in users])
|
||||
self.all_gids = set([x.gr_gid for x in groups])
|
||||
|
||||
def test_fetch_all(self):
|
||||
valid_procs = 0
|
||||
excluded_names = set([
|
||||
'send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait',
|
||||
'as_dict', 'parent', 'children', 'memory_info_ex', 'oneshot',
|
||||
])
|
||||
if LINUX and not HAS_RLIMIT:
|
||||
excluded_names.add('rlimit')
|
||||
attrs = []
|
||||
for name in dir(psutil.Process):
|
||||
if name.startswith("_"):
|
||||
continue
|
||||
if name in excluded_names:
|
||||
continue
|
||||
attrs.append(name)
|
||||
|
||||
default = object()
|
||||
failures = []
|
||||
for p in psutil.process_iter():
|
||||
with p.oneshot():
|
||||
for name in attrs:
|
||||
ret = default
|
||||
try:
|
||||
args = ()
|
||||
kwargs = {}
|
||||
attr = getattr(p, name, None)
|
||||
if attr is not None and callable(attr):
|
||||
if name == 'rlimit':
|
||||
args = (psutil.RLIMIT_NOFILE,)
|
||||
elif name == 'memory_maps':
|
||||
kwargs = {'grouped': False}
|
||||
ret = attr(*args, **kwargs)
|
||||
else:
|
||||
ret = attr
|
||||
valid_procs += 1
|
||||
except NotImplementedError:
|
||||
msg = "%r was skipped because not implemented" % (
|
||||
self.__class__.__name__ + '.test_' + name)
|
||||
warn(msg)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied) as err:
|
||||
self.assertEqual(err.pid, p.pid)
|
||||
if err.name:
|
||||
# make sure exception's name attr is set
|
||||
# with the actual process name
|
||||
self.assertEqual(err.name, p.name())
|
||||
assert str(err)
|
||||
assert err.msg
|
||||
except Exception as err:
|
||||
s = '\n' + '=' * 70 + '\n'
|
||||
s += "FAIL: test_%s (proc=%s" % (name, p)
|
||||
if ret != default:
|
||||
s += ", ret=%s)" % repr(ret)
|
||||
s += ')\n'
|
||||
s += '-' * 70
|
||||
s += "\n%s" % traceback.format_exc()
|
||||
s = "\n".join((" " * 4) + i for i in s.splitlines())
|
||||
s += '\n'
|
||||
failures.append(s)
|
||||
break
|
||||
else:
|
||||
if ret not in (0, 0.0, [], None, '', {}):
|
||||
assert ret, ret
|
||||
meth = getattr(self, name)
|
||||
meth(ret, p)
|
||||
|
||||
if failures:
|
||||
self.fail(''.join(failures))
|
||||
|
||||
# we should always have a non-empty list, not including PID 0 etc.
|
||||
# special cases.
|
||||
assert valid_procs
|
||||
|
||||
def cmdline(self, ret, proc):
|
||||
self.assertIsInstance(ret, list)
|
||||
for part in ret:
|
||||
self.assertIsInstance(part, str)
|
||||
|
||||
def exe(self, ret, proc):
|
||||
self.assertIsInstance(ret, (str, type(None)))
|
||||
if not ret:
|
||||
self.assertEqual(ret, '')
|
||||
else:
|
||||
assert os.path.isabs(ret), ret
|
||||
# Note: os.stat() may return False even if the file is there
|
||||
# hence we skip the test, see:
|
||||
# http://stackoverflow.com/questions/3112546/os-path-exists-lies
|
||||
if POSIX and os.path.isfile(ret):
|
||||
if hasattr(os, 'access') and hasattr(os, "X_OK"):
|
||||
# XXX may fail on OSX
|
||||
assert os.access(ret, os.X_OK)
|
||||
|
||||
def pid(self, ret, proc):
|
||||
self.assertIsInstance(ret, int)
|
||||
self.assertGreaterEqual(ret, 0)
|
||||
|
||||
def ppid(self, ret, proc):
|
||||
self.assertIsInstance(ret, (int, long))
|
||||
self.assertGreaterEqual(ret, 0)
|
||||
|
||||
def name(self, ret, proc):
|
||||
self.assertIsInstance(ret, str)
|
||||
# on AIX, "<exiting>" processes don't have names
|
||||
if not AIX:
|
||||
assert ret
|
||||
|
||||
def create_time(self, ret, proc):
|
||||
self.assertIsInstance(ret, float)
|
||||
try:
|
||||
self.assertGreaterEqual(ret, 0)
|
||||
except AssertionError:
|
||||
# XXX
|
||||
if OPENBSD and proc.status() == psutil.STATUS_ZOMBIE:
|
||||
pass
|
||||
else:
|
||||
raise
|
||||
# this can't be taken for granted on all platforms
|
||||
# self.assertGreaterEqual(ret, psutil.boot_time())
|
||||
# make sure returned value can be pretty printed
|
||||
# with strftime
|
||||
time.strftime("%Y %m %d %H:%M:%S", time.localtime(ret))
|
||||
|
||||
def uids(self, ret, proc):
|
||||
assert is_namedtuple(ret)
|
||||
for uid in ret:
|
||||
self.assertIsInstance(uid, int)
|
||||
self.assertGreaterEqual(uid, 0)
|
||||
self.assertIn(uid, self.all_uids)
|
||||
|
||||
def gids(self, ret, proc):
|
||||
assert is_namedtuple(ret)
|
||||
# note: testing all gids as above seems not to be reliable for
|
||||
# gid == 30 (nodoby); not sure why.
|
||||
for gid in ret:
|
||||
self.assertIsInstance(gid, int)
|
||||
if not OSX and not NETBSD:
|
||||
self.assertGreaterEqual(gid, 0)
|
||||
self.assertIn(gid, self.all_gids)
|
||||
|
||||
def username(self, ret, proc):
|
||||
self.assertIsInstance(ret, str)
|
||||
assert ret
|
||||
if POSIX:
|
||||
self.assertIn(ret, self.all_usernames)
|
||||
|
||||
def status(self, ret, proc):
|
||||
self.assertIsInstance(ret, str)
|
||||
assert ret
|
||||
self.assertNotEqual(ret, '?') # XXX
|
||||
self.assertIn(ret, VALID_PROC_STATUSES)
|
||||
|
||||
def io_counters(self, ret, proc):
|
||||
assert is_namedtuple(ret)
|
||||
for field in ret:
|
||||
self.assertIsInstance(field, (int, long))
|
||||
if field != -1:
|
||||
self.assertGreaterEqual(field, 0)
|
||||
|
||||
def ionice(self, ret, proc):
|
||||
if POSIX:
|
||||
assert is_namedtuple(ret)
|
||||
for field in ret:
|
||||
self.assertIsInstance(field, int)
|
||||
if LINUX:
|
||||
self.assertGreaterEqual(ret.ioclass, 0)
|
||||
self.assertGreaterEqual(ret.value, 0)
|
||||
else:
|
||||
self.assertGreaterEqual(ret, 0)
|
||||
self.assertIn(ret, (0, 1, 2))
|
||||
|
||||
def num_threads(self, ret, proc):
|
||||
self.assertIsInstance(ret, int)
|
||||
self.assertGreaterEqual(ret, 1)
|
||||
|
||||
def threads(self, ret, proc):
|
||||
self.assertIsInstance(ret, list)
|
||||
for t in ret:
|
||||
assert is_namedtuple(t)
|
||||
self.assertGreaterEqual(t.id, 0)
|
||||
self.assertGreaterEqual(t.user_time, 0)
|
||||
self.assertGreaterEqual(t.system_time, 0)
|
||||
for field in t:
|
||||
self.assertIsInstance(field, (int, float))
|
||||
|
||||
def cpu_times(self, ret, proc):
|
||||
assert is_namedtuple(ret)
|
||||
for n in ret:
|
||||
self.assertIsInstance(n, float)
|
||||
self.assertGreaterEqual(n, 0)
|
||||
# TODO: check ntuple fields
|
||||
|
||||
def cpu_percent(self, ret, proc):
|
||||
self.assertIsInstance(ret, float)
|
||||
assert 0.0 <= ret <= 100.0, ret
|
||||
|
||||
def cpu_num(self, ret, proc):
|
||||
self.assertIsInstance(ret, int)
|
||||
if FREEBSD and ret == -1:
|
||||
return
|
||||
self.assertGreaterEqual(ret, 0)
|
||||
if psutil.cpu_count() == 1:
|
||||
self.assertEqual(ret, 0)
|
||||
self.assertIn(ret, list(range(psutil.cpu_count())))
|
||||
|
||||
def memory_info(self, ret, proc):
|
||||
assert is_namedtuple(ret)
|
||||
for value in ret:
|
||||
self.assertIsInstance(value, (int, long))
|
||||
self.assertGreaterEqual(value, 0)
|
||||
if POSIX and not AIX and ret.vms != 0:
|
||||
# VMS is always supposed to be the highest
|
||||
for name in ret._fields:
|
||||
if name != 'vms':
|
||||
value = getattr(ret, name)
|
||||
self.assertGreater(ret.vms, value, msg=ret)
|
||||
elif WINDOWS:
|
||||
self.assertGreaterEqual(ret.peak_wset, ret.wset)
|
||||
self.assertGreaterEqual(ret.peak_paged_pool, ret.paged_pool)
|
||||
self.assertGreaterEqual(ret.peak_nonpaged_pool, ret.nonpaged_pool)
|
||||
self.assertGreaterEqual(ret.peak_pagefile, ret.pagefile)
|
||||
|
||||
def memory_full_info(self, ret, proc):
|
||||
assert is_namedtuple(ret)
|
||||
total = psutil.virtual_memory().total
|
||||
for name in ret._fields:
|
||||
value = getattr(ret, name)
|
||||
self.assertIsInstance(value, (int, long))
|
||||
self.assertGreaterEqual(value, 0, msg=(name, value))
|
||||
self.assertLessEqual(value, total, msg=(name, value, total))
|
||||
|
||||
if LINUX:
|
||||
self.assertGreaterEqual(ret.pss, ret.uss)
|
||||
|
||||
def open_files(self, ret, proc):
|
||||
self.assertIsInstance(ret, list)
|
||||
for f in ret:
|
||||
self.assertIsInstance(f.fd, int)
|
||||
self.assertIsInstance(f.path, str)
|
||||
if WINDOWS:
|
||||
self.assertEqual(f.fd, -1)
|
||||
elif LINUX:
|
||||
self.assertIsInstance(f.position, int)
|
||||
self.assertIsInstance(f.mode, str)
|
||||
self.assertIsInstance(f.flags, int)
|
||||
self.assertGreaterEqual(f.position, 0)
|
||||
self.assertIn(f.mode, ('r', 'w', 'a', 'r+', 'a+'))
|
||||
self.assertGreater(f.flags, 0)
|
||||
elif BSD and not f.path:
|
||||
# XXX see: https://github.com/giampaolo/psutil/issues/595
|
||||
continue
|
||||
assert os.path.isabs(f.path), f
|
||||
assert os.path.isfile(f.path), f
|
||||
|
||||
def num_fds(self, ret, proc):
|
||||
self.assertIsInstance(ret, int)
|
||||
self.assertGreaterEqual(ret, 0)
|
||||
|
||||
def connections(self, ret, proc):
|
||||
self.assertEqual(len(ret), len(set(ret)))
|
||||
for conn in ret:
|
||||
check_connection_ntuple(conn)
|
||||
|
||||
def cwd(self, ret, proc):
|
||||
if ret: # 'ret' can be None or empty
|
||||
self.assertIsInstance(ret, str)
|
||||
assert os.path.isabs(ret), ret
|
||||
try:
|
||||
st = os.stat(ret)
|
||||
except OSError as err:
|
||||
if WINDOWS and err.errno in \
|
||||
psutil._psplatform.ACCESS_DENIED_SET:
|
||||
pass
|
||||
# directory has been removed in mean time
|
||||
elif err.errno != errno.ENOENT:
|
||||
raise
|
||||
else:
|
||||
assert stat.S_ISDIR(st.st_mode)
|
||||
|
||||
def memory_percent(self, ret, proc):
|
||||
self.assertIsInstance(ret, float)
|
||||
assert 0 <= ret <= 100, ret
|
||||
|
||||
def is_running(self, ret, proc):
|
||||
self.assertIsInstance(ret, bool)
|
||||
|
||||
def cpu_affinity(self, ret, proc):
|
||||
self.assertIsInstance(ret, list)
|
||||
assert ret != [], ret
|
||||
cpus = range(psutil.cpu_count())
|
||||
for n in ret:
|
||||
self.assertIsInstance(n, int)
|
||||
self.assertIn(n, cpus)
|
||||
|
||||
def terminal(self, ret, proc):
|
||||
self.assertIsInstance(ret, (str, type(None)))
|
||||
if ret is not None:
|
||||
assert os.path.isabs(ret), ret
|
||||
assert os.path.exists(ret), ret
|
||||
|
||||
def memory_maps(self, ret, proc):
|
||||
for nt in ret:
|
||||
self.assertIsInstance(nt.addr, str)
|
||||
self.assertIsInstance(nt.perms, str)
|
||||
self.assertIsInstance(nt.path, str)
|
||||
for fname in nt._fields:
|
||||
value = getattr(nt, fname)
|
||||
if fname == 'path':
|
||||
if not value.startswith('['):
|
||||
assert os.path.isabs(nt.path), nt.path
|
||||
# commented as on Linux we might get
|
||||
# '/foo/bar (deleted)'
|
||||
# assert os.path.exists(nt.path), nt.path
|
||||
elif fname in ('addr', 'perms'):
|
||||
assert value
|
||||
else:
|
||||
self.assertIsInstance(value, (int, long))
|
||||
self.assertGreaterEqual(value, 0)
|
||||
|
||||
def num_handles(self, ret, proc):
|
||||
self.assertIsInstance(ret, int)
|
||||
self.assertGreaterEqual(ret, 0)
|
||||
|
||||
def nice(self, ret, proc):
|
||||
self.assertIsInstance(ret, int)
|
||||
if POSIX:
|
||||
assert -20 <= ret <= 20, ret
|
||||
else:
|
||||
priorities = [getattr(psutil, x) for x in dir(psutil)
|
||||
if x.endswith('_PRIORITY_CLASS')]
|
||||
self.assertIn(ret, priorities)
|
||||
|
||||
def num_ctx_switches(self, ret, proc):
|
||||
assert is_namedtuple(ret)
|
||||
for value in ret:
|
||||
self.assertIsInstance(value, (int, long))
|
||||
self.assertGreaterEqual(value, 0)
|
||||
|
||||
def rlimit(self, ret, proc):
|
||||
self.assertIsInstance(ret, tuple)
|
||||
self.assertEqual(len(ret), 2)
|
||||
self.assertGreaterEqual(ret[0], -1)
|
||||
self.assertGreaterEqual(ret[1], -1)
|
||||
|
||||
def environ(self, ret, proc):
|
||||
self.assertIsInstance(ret, dict)
|
||||
for k, v in ret.items():
|
||||
self.assertIsInstance(k, str)
|
||||
self.assertIsInstance(v, str)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
1910
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_linux.py
поставляемый
Normal file
1910
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_linux.py
поставляемый
Normal file
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
599
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_memory_leaks.py
поставляемый
Normal file
599
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_memory_leaks.py
поставляемый
Normal file
|
@ -0,0 +1,599 @@
|
|||
#!/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.
|
||||
|
||||
"""
|
||||
Tests for detecting function memory leaks (typically the ones
|
||||
implemented in C). It does so by calling a function many times and
|
||||
checking whether process memory usage keeps increasing between
|
||||
calls or over time.
|
||||
Note that this may produce false positives (especially on Windows
|
||||
for some reason).
|
||||
"""
|
||||
|
||||
from __future__ import print_function
|
||||
import errno
|
||||
import functools
|
||||
import gc
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
import psutil
|
||||
import psutil._common
|
||||
from psutil import LINUX
|
||||
from psutil import OPENBSD
|
||||
from psutil import OSX
|
||||
from psutil import POSIX
|
||||
from psutil import SUNOS
|
||||
from psutil import WINDOWS
|
||||
from psutil._compat import xrange
|
||||
from psutil.tests import create_sockets
|
||||
from psutil.tests import get_test_subprocess
|
||||
from psutil.tests import HAS_CPU_AFFINITY
|
||||
from psutil.tests import HAS_CPU_FREQ
|
||||
from psutil.tests import HAS_ENVIRON
|
||||
from psutil.tests import HAS_IONICE
|
||||
from psutil.tests import HAS_MEMORY_MAPS
|
||||
from psutil.tests import HAS_PROC_CPU_NUM
|
||||
from psutil.tests import HAS_PROC_IO_COUNTERS
|
||||
from psutil.tests import HAS_RLIMIT
|
||||
from psutil.tests import HAS_SENSORS_BATTERY
|
||||
from psutil.tests import HAS_SENSORS_FANS
|
||||
from psutil.tests import HAS_SENSORS_TEMPERATURES
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import safe_rmpath
|
||||
from psutil.tests import skip_on_access_denied
|
||||
from psutil.tests import TESTFN
|
||||
from psutil.tests import TRAVIS
|
||||
from psutil.tests import unittest
|
||||
|
||||
|
||||
LOOPS = 1000
|
||||
MEMORY_TOLERANCE = 4096
|
||||
RETRY_FOR = 3
|
||||
|
||||
SKIP_PYTHON_IMPL = True if TRAVIS else False
|
||||
cext = psutil._psplatform.cext
|
||||
thisproc = psutil.Process()
|
||||
SKIP_PYTHON_IMPL = True if TRAVIS else False
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# utils
|
||||
# ===================================================================
|
||||
|
||||
|
||||
def skip_if_linux():
|
||||
return unittest.skipIf(LINUX and SKIP_PYTHON_IMPL,
|
||||
"worthless on LINUX (pure python)")
|
||||
|
||||
|
||||
def bytes2human(n):
|
||||
"""
|
||||
http://code.activestate.com/recipes/578019
|
||||
>>> bytes2human(10000)
|
||||
'9.8K'
|
||||
>>> bytes2human(100001221)
|
||||
'95.4M'
|
||||
"""
|
||||
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
|
||||
prefix = {}
|
||||
for i, s in enumerate(symbols):
|
||||
prefix[s] = 1 << (i + 1) * 10
|
||||
for s in reversed(symbols):
|
||||
if n >= prefix[s]:
|
||||
value = float(n) / prefix[s]
|
||||
return '%.2f%s' % (value, s)
|
||||
return "%sB" % n
|
||||
|
||||
|
||||
class TestMemLeak(unittest.TestCase):
|
||||
"""Base framework class which calls a function many times and
|
||||
produces a failure if process memory usage keeps increasing
|
||||
between calls or over time.
|
||||
"""
|
||||
tolerance = MEMORY_TOLERANCE
|
||||
loops = LOOPS
|
||||
retry_for = RETRY_FOR
|
||||
|
||||
def setUp(self):
|
||||
gc.collect()
|
||||
|
||||
def execute(self, fun, *args, **kwargs):
|
||||
"""Test a callable."""
|
||||
def call_many_times():
|
||||
for x in xrange(loops):
|
||||
self._call(fun, *args, **kwargs)
|
||||
del x
|
||||
gc.collect()
|
||||
|
||||
tolerance = kwargs.pop('tolerance_', None) or self.tolerance
|
||||
loops = kwargs.pop('loops_', None) or self.loops
|
||||
retry_for = kwargs.pop('retry_for_', None) or self.retry_for
|
||||
|
||||
# warm up
|
||||
for x in range(10):
|
||||
self._call(fun, *args, **kwargs)
|
||||
self.assertEqual(gc.garbage, [])
|
||||
self.assertEqual(threading.active_count(), 1)
|
||||
self.assertEqual(thisproc.children(), [])
|
||||
|
||||
# Get 2 distinct memory samples, before and after having
|
||||
# called fun repeadetly.
|
||||
# step 1
|
||||
call_many_times()
|
||||
mem1 = self._get_mem()
|
||||
# step 2
|
||||
call_many_times()
|
||||
mem2 = self._get_mem()
|
||||
|
||||
diff1 = mem2 - mem1
|
||||
if diff1 > tolerance:
|
||||
# This doesn't necessarily mean we have a leak yet.
|
||||
# At this point we assume that after having called the
|
||||
# function so many times the memory usage is stabilized
|
||||
# and if there are no leaks it should not increase
|
||||
# anymore.
|
||||
# Let's keep calling fun for 3 more seconds and fail if
|
||||
# we notice any difference.
|
||||
ncalls = 0
|
||||
stop_at = time.time() + retry_for
|
||||
while time.time() <= stop_at:
|
||||
self._call(fun, *args, **kwargs)
|
||||
ncalls += 1
|
||||
|
||||
del stop_at
|
||||
gc.collect()
|
||||
mem3 = self._get_mem()
|
||||
diff2 = mem3 - mem2
|
||||
|
||||
if mem3 > mem2:
|
||||
# failure
|
||||
extra_proc_mem = bytes2human(diff1 + diff2)
|
||||
print("exta proc mem: %s" % extra_proc_mem, file=sys.stderr)
|
||||
msg = "+%s after %s calls, +%s after another %s calls, "
|
||||
msg += "+%s extra proc mem"
|
||||
msg = msg % (
|
||||
bytes2human(diff1), loops, bytes2human(diff2), ncalls,
|
||||
extra_proc_mem)
|
||||
self.fail(msg)
|
||||
|
||||
def execute_w_exc(self, exc, fun, *args, **kwargs):
|
||||
"""Convenience function which tests a callable raising
|
||||
an exception.
|
||||
"""
|
||||
def call():
|
||||
self.assertRaises(exc, fun, *args, **kwargs)
|
||||
|
||||
self.execute(call)
|
||||
|
||||
@staticmethod
|
||||
def _get_mem():
|
||||
# By using USS memory it seems it's less likely to bump
|
||||
# into false positives.
|
||||
if LINUX or WINDOWS or OSX:
|
||||
return thisproc.memory_full_info().uss
|
||||
else:
|
||||
return thisproc.memory_info().rss
|
||||
|
||||
@staticmethod
|
||||
def _call(fun, *args, **kwargs):
|
||||
fun(*args, **kwargs)
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Process class
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestProcessObjectLeaks(TestMemLeak):
|
||||
"""Test leaks of Process class methods."""
|
||||
|
||||
proc = thisproc
|
||||
|
||||
def test_coverage(self):
|
||||
skip = set((
|
||||
"pid", "as_dict", "children", "cpu_affinity", "cpu_percent",
|
||||
"ionice", "is_running", "kill", "memory_info_ex", "memory_percent",
|
||||
"nice", "oneshot", "parent", "rlimit", "send_signal", "suspend",
|
||||
"terminate", "wait"))
|
||||
for name in dir(psutil.Process):
|
||||
if name.startswith('_'):
|
||||
continue
|
||||
if name in skip:
|
||||
continue
|
||||
self.assertTrue(hasattr(self, "test_" + name), msg=name)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_name(self):
|
||||
self.execute(self.proc.name)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_cmdline(self):
|
||||
self.execute(self.proc.cmdline)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_exe(self):
|
||||
self.execute(self.proc.exe)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_ppid(self):
|
||||
self.execute(self.proc.ppid)
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
@skip_if_linux()
|
||||
def test_uids(self):
|
||||
self.execute(self.proc.uids)
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
@skip_if_linux()
|
||||
def test_gids(self):
|
||||
self.execute(self.proc.gids)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_status(self):
|
||||
self.execute(self.proc.status)
|
||||
|
||||
def test_nice_get(self):
|
||||
self.execute(self.proc.nice)
|
||||
|
||||
def test_nice_set(self):
|
||||
niceness = thisproc.nice()
|
||||
self.execute(self.proc.nice, niceness)
|
||||
|
||||
@unittest.skipIf(not HAS_IONICE, "not supported")
|
||||
def test_ionice_get(self):
|
||||
self.execute(self.proc.ionice)
|
||||
|
||||
@unittest.skipIf(not HAS_IONICE, "not supported")
|
||||
def test_ionice_set(self):
|
||||
if WINDOWS:
|
||||
value = thisproc.ionice()
|
||||
self.execute(self.proc.ionice, value)
|
||||
else:
|
||||
self.execute(self.proc.ionice, psutil.IOPRIO_CLASS_NONE)
|
||||
fun = functools.partial(cext.proc_ioprio_set, os.getpid(), -1, 0)
|
||||
self.execute_w_exc(OSError, fun)
|
||||
|
||||
@unittest.skipIf(not HAS_PROC_IO_COUNTERS, "not supported")
|
||||
@skip_if_linux()
|
||||
def test_io_counters(self):
|
||||
self.execute(self.proc.io_counters)
|
||||
|
||||
@unittest.skipIf(POSIX, "worthless on POSIX")
|
||||
def test_username(self):
|
||||
self.execute(self.proc.username)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_create_time(self):
|
||||
self.execute(self.proc.create_time)
|
||||
|
||||
@skip_if_linux()
|
||||
@skip_on_access_denied(only_if=OPENBSD)
|
||||
def test_num_threads(self):
|
||||
self.execute(self.proc.num_threads)
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
def test_num_handles(self):
|
||||
self.execute(self.proc.num_handles)
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
@skip_if_linux()
|
||||
def test_num_fds(self):
|
||||
self.execute(self.proc.num_fds)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_num_ctx_switches(self):
|
||||
self.execute(self.proc.num_ctx_switches)
|
||||
|
||||
@skip_if_linux()
|
||||
@skip_on_access_denied(only_if=OPENBSD)
|
||||
def test_threads(self):
|
||||
self.execute(self.proc.threads)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_cpu_times(self):
|
||||
self.execute(self.proc.cpu_times)
|
||||
|
||||
@skip_if_linux()
|
||||
@unittest.skipIf(not HAS_PROC_CPU_NUM, "not supported")
|
||||
def test_cpu_num(self):
|
||||
self.execute(self.proc.cpu_num)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_memory_info(self):
|
||||
self.execute(self.proc.memory_info)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_memory_full_info(self):
|
||||
self.execute(self.proc.memory_full_info)
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
@skip_if_linux()
|
||||
def test_terminal(self):
|
||||
self.execute(self.proc.terminal)
|
||||
|
||||
@unittest.skipIf(POSIX and SKIP_PYTHON_IMPL,
|
||||
"worthless on POSIX (pure python)")
|
||||
def test_resume(self):
|
||||
self.execute(self.proc.resume)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_cwd(self):
|
||||
self.execute(self.proc.cwd)
|
||||
|
||||
@unittest.skipIf(not HAS_CPU_AFFINITY, "not supported")
|
||||
def test_cpu_affinity_get(self):
|
||||
self.execute(self.proc.cpu_affinity)
|
||||
|
||||
@unittest.skipIf(not HAS_CPU_AFFINITY, "not supported")
|
||||
def test_cpu_affinity_set(self):
|
||||
affinity = thisproc.cpu_affinity()
|
||||
self.execute(self.proc.cpu_affinity, affinity)
|
||||
if not TRAVIS:
|
||||
self.execute_w_exc(ValueError, self.proc.cpu_affinity, [-1])
|
||||
|
||||
@skip_if_linux()
|
||||
def test_open_files(self):
|
||||
safe_rmpath(TESTFN) # needed after UNIX socket test has run
|
||||
with open(TESTFN, 'w'):
|
||||
self.execute(self.proc.open_files)
|
||||
|
||||
# OSX implementation is unbelievably slow
|
||||
@unittest.skipIf(OSX, "too slow on OSX")
|
||||
@unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
|
||||
@skip_if_linux()
|
||||
def test_memory_maps(self):
|
||||
self.execute(self.proc.memory_maps)
|
||||
|
||||
@unittest.skipIf(not LINUX, "LINUX only")
|
||||
@unittest.skipIf(not HAS_RLIMIT, "not supported")
|
||||
def test_rlimit_get(self):
|
||||
self.execute(self.proc.rlimit, psutil.RLIMIT_NOFILE)
|
||||
|
||||
@unittest.skipIf(not LINUX, "LINUX only")
|
||||
@unittest.skipIf(not HAS_RLIMIT, "not supported")
|
||||
def test_rlimit_set(self):
|
||||
limit = thisproc.rlimit(psutil.RLIMIT_NOFILE)
|
||||
self.execute(self.proc.rlimit, psutil.RLIMIT_NOFILE, limit)
|
||||
self.execute_w_exc(OSError, self.proc.rlimit, -1)
|
||||
|
||||
@skip_if_linux()
|
||||
# Windows implementation is based on a single system-wide
|
||||
# function (tested later).
|
||||
@unittest.skipIf(WINDOWS, "worthless on WINDOWS")
|
||||
def test_connections(self):
|
||||
# TODO: UNIX sockets are temporarily implemented by parsing
|
||||
# 'pfiles' cmd output; we don't want that part of the code to
|
||||
# be executed.
|
||||
with create_sockets():
|
||||
kind = 'inet' if SUNOS else 'all'
|
||||
self.execute(self.proc.connections, kind)
|
||||
|
||||
@unittest.skipIf(not HAS_ENVIRON, "not supported")
|
||||
def test_environ(self):
|
||||
self.execute(self.proc.environ)
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
def test_proc_info(self):
|
||||
self.execute(cext.proc_info, os.getpid())
|
||||
|
||||
|
||||
class TestTerminatedProcessLeaks(TestProcessObjectLeaks):
|
||||
"""Repeat the tests above looking for leaks occurring when dealing
|
||||
with terminated processes raising NoSuchProcess exception.
|
||||
The C functions are still invoked but will follow different code
|
||||
paths. We'll check those code paths.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super(TestTerminatedProcessLeaks, cls).setUpClass()
|
||||
p = get_test_subprocess()
|
||||
cls.proc = psutil.Process(p.pid)
|
||||
cls.proc.kill()
|
||||
cls.proc.wait()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
super(TestTerminatedProcessLeaks, cls).tearDownClass()
|
||||
reap_children()
|
||||
|
||||
def _call(self, fun, *args, **kwargs):
|
||||
try:
|
||||
fun(*args, **kwargs)
|
||||
except psutil.NoSuchProcess:
|
||||
pass
|
||||
|
||||
if WINDOWS:
|
||||
|
||||
def test_kill(self):
|
||||
self.execute(self.proc.kill)
|
||||
|
||||
def test_terminate(self):
|
||||
self.execute(self.proc.terminate)
|
||||
|
||||
def test_suspend(self):
|
||||
self.execute(self.proc.suspend)
|
||||
|
||||
def test_resume(self):
|
||||
self.execute(self.proc.resume)
|
||||
|
||||
def test_wait(self):
|
||||
self.execute(self.proc.wait)
|
||||
|
||||
def test_proc_info(self):
|
||||
# test dual implementation
|
||||
def call():
|
||||
try:
|
||||
return cext.proc_info(self.proc.pid)
|
||||
except OSError as err:
|
||||
if err.errno != errno.ESRCH:
|
||||
raise
|
||||
|
||||
self.execute(call)
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# system APIs
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestModuleFunctionsLeaks(TestMemLeak):
|
||||
"""Test leaks of psutil module functions."""
|
||||
|
||||
def test_coverage(self):
|
||||
skip = set((
|
||||
"version_info", "__version__", "process_iter", "wait_procs",
|
||||
"cpu_percent", "cpu_times_percent", "cpu_count"))
|
||||
for name in psutil.__all__:
|
||||
if not name.islower():
|
||||
continue
|
||||
if name in skip:
|
||||
continue
|
||||
self.assertTrue(hasattr(self, "test_" + name), msg=name)
|
||||
|
||||
# --- cpu
|
||||
|
||||
@skip_if_linux()
|
||||
def test_cpu_count_logical(self):
|
||||
self.execute(psutil.cpu_count, logical=True)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_cpu_count_physical(self):
|
||||
self.execute(psutil.cpu_count, logical=False)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_cpu_times(self):
|
||||
self.execute(psutil.cpu_times)
|
||||
|
||||
@skip_if_linux()
|
||||
def test_per_cpu_times(self):
|
||||
self.execute(psutil.cpu_times, percpu=True)
|
||||
|
||||
def test_cpu_stats(self):
|
||||
self.execute(psutil.cpu_stats)
|
||||
|
||||
@skip_if_linux()
|
||||
@unittest.skipIf(not HAS_CPU_FREQ, "not supported")
|
||||
def test_cpu_freq(self):
|
||||
self.execute(psutil.cpu_freq)
|
||||
|
||||
# --- mem
|
||||
|
||||
def test_virtual_memory(self):
|
||||
self.execute(psutil.virtual_memory)
|
||||
|
||||
# TODO: remove this skip when this gets fixed
|
||||
@unittest.skipIf(SUNOS,
|
||||
"worthless on SUNOS (uses a subprocess)")
|
||||
def test_swap_memory(self):
|
||||
self.execute(psutil.swap_memory)
|
||||
|
||||
@unittest.skipIf(POSIX and SKIP_PYTHON_IMPL,
|
||||
"worthless on POSIX (pure python)")
|
||||
def test_pid_exists(self):
|
||||
self.execute(psutil.pid_exists, os.getpid())
|
||||
|
||||
# --- disk
|
||||
|
||||
@unittest.skipIf(POSIX and SKIP_PYTHON_IMPL,
|
||||
"worthless on POSIX (pure python)")
|
||||
def test_disk_usage(self):
|
||||
self.execute(psutil.disk_usage, '.')
|
||||
|
||||
def test_disk_partitions(self):
|
||||
self.execute(psutil.disk_partitions)
|
||||
|
||||
@unittest.skipIf(LINUX and not os.path.exists('/proc/diskstats'),
|
||||
'/proc/diskstats not available on this Linux version')
|
||||
@skip_if_linux()
|
||||
def test_disk_io_counters(self):
|
||||
self.execute(psutil.disk_io_counters, nowrap=False)
|
||||
|
||||
# --- proc
|
||||
|
||||
@skip_if_linux()
|
||||
def test_pids(self):
|
||||
self.execute(psutil.pids)
|
||||
|
||||
# --- net
|
||||
|
||||
@skip_if_linux()
|
||||
def test_net_io_counters(self):
|
||||
self.execute(psutil.net_io_counters, nowrap=False)
|
||||
|
||||
@unittest.skipIf(LINUX,
|
||||
"worthless on Linux (pure python)")
|
||||
@unittest.skipIf(OSX and os.getuid() != 0, "need root access")
|
||||
def test_net_connections(self):
|
||||
with create_sockets():
|
||||
self.execute(psutil.net_connections)
|
||||
|
||||
def test_net_if_addrs(self):
|
||||
# Note: verified that on Windows this was a false positive.
|
||||
self.execute(psutil.net_if_addrs,
|
||||
tolerance_=80 * 1024 if WINDOWS else None)
|
||||
|
||||
@unittest.skipIf(TRAVIS, "EPERM on travis")
|
||||
def test_net_if_stats(self):
|
||||
self.execute(psutil.net_if_stats)
|
||||
|
||||
# --- sensors
|
||||
|
||||
@skip_if_linux()
|
||||
@unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
|
||||
def test_sensors_battery(self):
|
||||
self.execute(psutil.sensors_battery)
|
||||
|
||||
@skip_if_linux()
|
||||
@unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
|
||||
def test_sensors_temperatures(self):
|
||||
self.execute(psutil.sensors_temperatures)
|
||||
|
||||
@skip_if_linux()
|
||||
@unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
|
||||
def test_sensors_fans(self):
|
||||
self.execute(psutil.sensors_fans)
|
||||
|
||||
# --- others
|
||||
|
||||
@skip_if_linux()
|
||||
def test_boot_time(self):
|
||||
self.execute(psutil.boot_time)
|
||||
|
||||
# XXX - on Windows this produces a false positive
|
||||
@unittest.skipIf(WINDOWS, "XXX produces a false positive on Windows")
|
||||
def test_users(self):
|
||||
self.execute(psutil.users)
|
||||
|
||||
if WINDOWS:
|
||||
|
||||
# --- win services
|
||||
|
||||
def test_win_service_iter(self):
|
||||
self.execute(cext.winservice_enumerate)
|
||||
|
||||
def test_win_service_get(self):
|
||||
pass
|
||||
|
||||
def test_win_service_get_config(self):
|
||||
name = next(psutil.win_service_iter()).name()
|
||||
self.execute(cext.winservice_query_config, name)
|
||||
|
||||
def test_win_service_get_status(self):
|
||||
name = next(psutil.win_service_iter()).name()
|
||||
self.execute(cext.winservice_query_status, name)
|
||||
|
||||
def test_win_service_get_description(self):
|
||||
name = next(psutil.win_service_iter()).name()
|
||||
self.execute(cext.winservice_query_descr, name)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
1039
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_misc.py
поставляемый
Normal file
1039
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_misc.py
поставляемый
Normal file
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,303 @@
|
|||
#!/usr/bin/env python
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""OSX specific tests."""
|
||||
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import psutil
|
||||
from psutil import OSX
|
||||
from psutil.tests import create_zombie_proc
|
||||
from psutil.tests import get_test_subprocess
|
||||
from psutil.tests import HAS_BATTERY
|
||||
from psutil.tests import MEMORY_TOLERANCE
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import retry_before_failing
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import sh
|
||||
from psutil.tests import unittest
|
||||
|
||||
|
||||
PAGESIZE = os.sysconf("SC_PAGE_SIZE") if OSX else None
|
||||
|
||||
|
||||
def sysctl(cmdline):
|
||||
"""Expects a sysctl command with an argument and parse the result
|
||||
returning only the value of interest.
|
||||
"""
|
||||
out = sh(cmdline)
|
||||
result = out.split()[1]
|
||||
try:
|
||||
return int(result)
|
||||
except ValueError:
|
||||
return result
|
||||
|
||||
|
||||
def vm_stat(field):
|
||||
"""Wrapper around 'vm_stat' cmdline utility."""
|
||||
out = sh('vm_stat')
|
||||
for line in out.split('\n'):
|
||||
if field in line:
|
||||
break
|
||||
else:
|
||||
raise ValueError("line not found")
|
||||
return int(re.search(r'\d+', line).group(0)) * PAGESIZE
|
||||
|
||||
|
||||
# http://code.activestate.com/recipes/578019/
|
||||
def human2bytes(s):
|
||||
SYMBOLS = {
|
||||
'customary': ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'),
|
||||
}
|
||||
init = s
|
||||
num = ""
|
||||
while s and s[0:1].isdigit() or s[0:1] == '.':
|
||||
num += s[0]
|
||||
s = s[1:]
|
||||
num = float(num)
|
||||
letter = s.strip()
|
||||
for name, sset in SYMBOLS.items():
|
||||
if letter in sset:
|
||||
break
|
||||
else:
|
||||
if letter == 'k':
|
||||
sset = SYMBOLS['customary']
|
||||
letter = letter.upper()
|
||||
else:
|
||||
raise ValueError("can't interpret %r" % init)
|
||||
prefix = {sset[0]: 1}
|
||||
for i, s in enumerate(sset[1:]):
|
||||
prefix[s] = 1 << (i + 1) * 10
|
||||
return int(num * prefix[letter])
|
||||
|
||||
|
||||
@unittest.skipIf(not OSX, "OSX only")
|
||||
class TestProcess(unittest.TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.pid = get_test_subprocess().pid
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
|
||||
def test_process_create_time(self):
|
||||
output = sh("ps -o lstart -p %s" % self.pid)
|
||||
start_ps = output.replace('STARTED', '').strip()
|
||||
hhmmss = start_ps.split(' ')[-2]
|
||||
year = start_ps.split(' ')[-1]
|
||||
start_psutil = psutil.Process(self.pid).create_time()
|
||||
self.assertEqual(
|
||||
hhmmss,
|
||||
time.strftime("%H:%M:%S", time.localtime(start_psutil)))
|
||||
self.assertEqual(
|
||||
year,
|
||||
time.strftime("%Y", time.localtime(start_psutil)))
|
||||
|
||||
|
||||
@unittest.skipIf(not OSX, "OSX only")
|
||||
class TestZombieProcessAPIs(unittest.TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
zpid = create_zombie_proc()
|
||||
cls.p = psutil.Process(zpid)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children(recursive=True)
|
||||
|
||||
def test_pidtask_info(self):
|
||||
self.assertEqual(self.p.status(), psutil.STATUS_ZOMBIE)
|
||||
self.p.ppid()
|
||||
self.p.uids()
|
||||
self.p.gids()
|
||||
self.p.terminal()
|
||||
self.p.create_time()
|
||||
|
||||
def test_exe(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.exe)
|
||||
|
||||
def test_cmdline(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.cmdline)
|
||||
|
||||
def test_environ(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.environ)
|
||||
|
||||
def test_cwd(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.cwd)
|
||||
|
||||
def test_memory_full_info(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.memory_full_info)
|
||||
|
||||
def test_cpu_times(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.cpu_times)
|
||||
|
||||
def test_num_ctx_switches(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.num_ctx_switches)
|
||||
|
||||
def test_num_threads(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.num_threads)
|
||||
|
||||
def test_open_files(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.open_files)
|
||||
|
||||
def test_connections(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.connections)
|
||||
|
||||
def test_num_fds(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.num_fds)
|
||||
|
||||
def test_threads(self):
|
||||
self.assertRaises((psutil.ZombieProcess, psutil.AccessDenied),
|
||||
self.p.threads)
|
||||
|
||||
def test_memory_maps(self):
|
||||
self.assertRaises(psutil.ZombieProcess, self.p.memory_maps)
|
||||
|
||||
|
||||
@unittest.skipIf(not OSX, "OSX only")
|
||||
class TestSystemAPIs(unittest.TestCase):
|
||||
|
||||
# --- disk
|
||||
|
||||
def test_disks(self):
|
||||
# test psutil.disk_usage() and psutil.disk_partitions()
|
||||
# against "df -a"
|
||||
def df(path):
|
||||
out = sh('df -k "%s"' % path).strip()
|
||||
lines = out.split('\n')
|
||||
lines.pop(0)
|
||||
line = lines.pop(0)
|
||||
dev, total, used, free = line.split()[:4]
|
||||
if dev == 'none':
|
||||
dev = ''
|
||||
total = int(total) * 1024
|
||||
used = int(used) * 1024
|
||||
free = int(free) * 1024
|
||||
return dev, total, used, free
|
||||
|
||||
for part in psutil.disk_partitions(all=False):
|
||||
usage = psutil.disk_usage(part.mountpoint)
|
||||
dev, total, used, free = df(part.mountpoint)
|
||||
self.assertEqual(part.device, dev)
|
||||
self.assertEqual(usage.total, total)
|
||||
# 10 MB tollerance
|
||||
if abs(usage.free - free) > 10 * 1024 * 1024:
|
||||
self.fail("psutil=%s, df=%s" % usage.free, free)
|
||||
if abs(usage.used - used) > 10 * 1024 * 1024:
|
||||
self.fail("psutil=%s, df=%s" % usage.used, used)
|
||||
|
||||
# --- cpu
|
||||
|
||||
def test_cpu_count_logical(self):
|
||||
num = sysctl("sysctl hw.logicalcpu")
|
||||
self.assertEqual(num, psutil.cpu_count(logical=True))
|
||||
|
||||
def test_cpu_count_physical(self):
|
||||
num = sysctl("sysctl hw.physicalcpu")
|
||||
self.assertEqual(num, psutil.cpu_count(logical=False))
|
||||
|
||||
def test_cpu_freq(self):
|
||||
freq = psutil.cpu_freq()
|
||||
self.assertEqual(
|
||||
freq.current * 1000 * 1000, sysctl("sysctl hw.cpufrequency"))
|
||||
self.assertEqual(
|
||||
freq.min * 1000 * 1000, sysctl("sysctl hw.cpufrequency_min"))
|
||||
self.assertEqual(
|
||||
freq.max * 1000 * 1000, sysctl("sysctl hw.cpufrequency_max"))
|
||||
|
||||
# --- virtual mem
|
||||
|
||||
def test_vmem_total(self):
|
||||
sysctl_hwphymem = sysctl('sysctl hw.memsize')
|
||||
self.assertEqual(sysctl_hwphymem, psutil.virtual_memory().total)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_free(self):
|
||||
vmstat_val = vm_stat("free")
|
||||
psutil_val = psutil.virtual_memory().free
|
||||
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_available(self):
|
||||
vmstat_val = vm_stat("inactive") + vm_stat("free")
|
||||
psutil_val = psutil.virtual_memory().available
|
||||
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_active(self):
|
||||
vmstat_val = vm_stat("active")
|
||||
psutil_val = psutil.virtual_memory().active
|
||||
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_inactive(self):
|
||||
vmstat_val = vm_stat("inactive")
|
||||
psutil_val = psutil.virtual_memory().inactive
|
||||
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_vmem_wired(self):
|
||||
vmstat_val = vm_stat("wired")
|
||||
psutil_val = psutil.virtual_memory().wired
|
||||
self.assertAlmostEqual(psutil_val, vmstat_val, delta=MEMORY_TOLERANCE)
|
||||
|
||||
# --- swap mem
|
||||
|
||||
@retry_before_failing()
|
||||
def test_swapmem_sin(self):
|
||||
vmstat_val = vm_stat("Pageins")
|
||||
psutil_val = psutil.swap_memory().sin
|
||||
self.assertEqual(psutil_val, vmstat_val)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_swapmem_sout(self):
|
||||
vmstat_val = vm_stat("Pageout")
|
||||
psutil_val = psutil.swap_memory().sout
|
||||
self.assertEqual(psutil_val, vmstat_val)
|
||||
|
||||
# Not very reliable.
|
||||
# def test_swapmem_total(self):
|
||||
# out = sh('sysctl vm.swapusage')
|
||||
# out = out.replace('vm.swapusage: ', '')
|
||||
# total, used, free = re.findall('\d+.\d+\w', out)
|
||||
# psutil_smem = psutil.swap_memory()
|
||||
# self.assertEqual(psutil_smem.total, human2bytes(total))
|
||||
# self.assertEqual(psutil_smem.used, human2bytes(used))
|
||||
# self.assertEqual(psutil_smem.free, human2bytes(free))
|
||||
|
||||
# --- network
|
||||
|
||||
def test_net_if_stats(self):
|
||||
for name, stats in psutil.net_if_stats().items():
|
||||
try:
|
||||
out = sh("ifconfig %s" % name)
|
||||
except RuntimeError:
|
||||
pass
|
||||
else:
|
||||
self.assertEqual(stats.isup, 'RUNNING' in out, msg=out)
|
||||
self.assertEqual(stats.mtu,
|
||||
int(re.findall(r'mtu (\d+)', out)[0]))
|
||||
|
||||
# --- sensors_battery
|
||||
|
||||
@unittest.skipIf(not HAS_BATTERY, "no battery")
|
||||
def test_sensors_battery(self):
|
||||
out = sh("pmset -g batt")
|
||||
percent = re.search("(\d+)%", out).group(1)
|
||||
drawing_from = re.search("Now drawing from '([^']+)'", out).group(1)
|
||||
power_plugged = drawing_from == "AC Power"
|
||||
psutil_result = psutil.sensors_battery()
|
||||
self.assertEqual(psutil_result.power_plugged, power_plugged)
|
||||
self.assertEqual(psutil_result.percent, int(percent))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
419
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_posix.py
поставляемый
Normal file
419
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_posix.py
поставляемый
Normal file
|
@ -0,0 +1,419 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""POSIX specific tests."""
|
||||
|
||||
import datetime
|
||||
import errno
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import psutil
|
||||
from psutil import AIX
|
||||
from psutil import BSD
|
||||
from psutil import LINUX
|
||||
from psutil import OPENBSD
|
||||
from psutil import OSX
|
||||
from psutil import POSIX
|
||||
from psutil import SUNOS
|
||||
from psutil._compat import callable
|
||||
from psutil._compat import PY3
|
||||
from psutil.tests import APPVEYOR
|
||||
from psutil.tests import get_kernel_version
|
||||
from psutil.tests import get_test_subprocess
|
||||
from psutil.tests import mock
|
||||
from psutil.tests import PYTHON_EXE
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import retry_before_failing
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import sh
|
||||
from psutil.tests import skip_on_access_denied
|
||||
from psutil.tests import TRAVIS
|
||||
from psutil.tests import unittest
|
||||
from psutil.tests import wait_for_pid
|
||||
from psutil.tests import which
|
||||
|
||||
|
||||
def ps(cmd):
|
||||
"""Expects a ps command with a -o argument and parse the result
|
||||
returning only the value of interest.
|
||||
"""
|
||||
if not LINUX:
|
||||
cmd = cmd.replace(" --no-headers ", " ")
|
||||
if SUNOS:
|
||||
cmd = cmd.replace("-o start", "-o stime")
|
||||
if AIX:
|
||||
cmd = cmd.replace("-o rss", "-o rssize")
|
||||
output = sh(cmd)
|
||||
if not LINUX:
|
||||
output = output.split('\n')[1].strip()
|
||||
try:
|
||||
return int(output)
|
||||
except ValueError:
|
||||
return output
|
||||
|
||||
# ps "-o" field names differ wildly between platforms.
|
||||
# "comm" means "only executable name" but is not available on BSD platforms.
|
||||
# "args" means "command with all its arguments", and is also not available
|
||||
# on BSD platforms.
|
||||
# "command" is like "args" on most platforms, but like "comm" on AIX,
|
||||
# and not available on SUNOS.
|
||||
# so for the executable name we can use "comm" on Solaris and split "command"
|
||||
# on other platforms.
|
||||
# to get the cmdline (with args) we have to use "args" on AIX and
|
||||
# Solaris, and can use "command" on all others.
|
||||
|
||||
|
||||
def ps_name(pid):
|
||||
field = "command"
|
||||
if SUNOS:
|
||||
field = "comm"
|
||||
return ps("ps --no-headers -o %s -p %s" % (field, pid)).split(' ')[0]
|
||||
|
||||
|
||||
def ps_args(pid):
|
||||
field = "command"
|
||||
if AIX or SUNOS:
|
||||
field = "args"
|
||||
return ps("ps --no-headers -o %s -p %s" % (field, pid))
|
||||
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
class TestProcess(unittest.TestCase):
|
||||
"""Compare psutil results against 'ps' command line utility (mainly)."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.pid = get_test_subprocess([PYTHON_EXE, "-E", "-O"],
|
||||
stdin=subprocess.PIPE).pid
|
||||
wait_for_pid(cls.pid)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
|
||||
def test_ppid(self):
|
||||
ppid_ps = ps("ps --no-headers -o ppid -p %s" % self.pid)
|
||||
ppid_psutil = psutil.Process(self.pid).ppid()
|
||||
self.assertEqual(ppid_ps, ppid_psutil)
|
||||
|
||||
def test_uid(self):
|
||||
uid_ps = ps("ps --no-headers -o uid -p %s" % self.pid)
|
||||
uid_psutil = psutil.Process(self.pid).uids().real
|
||||
self.assertEqual(uid_ps, uid_psutil)
|
||||
|
||||
def test_gid(self):
|
||||
gid_ps = ps("ps --no-headers -o rgid -p %s" % self.pid)
|
||||
gid_psutil = psutil.Process(self.pid).gids().real
|
||||
self.assertEqual(gid_ps, gid_psutil)
|
||||
|
||||
def test_username(self):
|
||||
username_ps = ps("ps --no-headers -o user -p %s" % self.pid)
|
||||
username_psutil = psutil.Process(self.pid).username()
|
||||
self.assertEqual(username_ps, username_psutil)
|
||||
|
||||
def test_username_no_resolution(self):
|
||||
# Emulate a case where the system can't resolve the uid to
|
||||
# a username in which case psutil is supposed to return
|
||||
# the stringified uid.
|
||||
p = psutil.Process()
|
||||
with mock.patch("psutil.pwd.getpwuid", side_effect=KeyError) as fun:
|
||||
self.assertEqual(p.username(), str(p.uids().real))
|
||||
assert fun.called
|
||||
|
||||
@skip_on_access_denied()
|
||||
@retry_before_failing()
|
||||
def test_rss_memory(self):
|
||||
# give python interpreter some time to properly initialize
|
||||
# so that the results are the same
|
||||
time.sleep(0.1)
|
||||
rss_ps = ps("ps --no-headers -o rss -p %s" % self.pid)
|
||||
rss_psutil = psutil.Process(self.pid).memory_info()[0] / 1024
|
||||
self.assertEqual(rss_ps, rss_psutil)
|
||||
|
||||
@skip_on_access_denied()
|
||||
@retry_before_failing()
|
||||
def test_vsz_memory(self):
|
||||
# give python interpreter some time to properly initialize
|
||||
# so that the results are the same
|
||||
time.sleep(0.1)
|
||||
vsz_ps = ps("ps --no-headers -o vsz -p %s" % self.pid)
|
||||
vsz_psutil = psutil.Process(self.pid).memory_info()[1] / 1024
|
||||
self.assertEqual(vsz_ps, vsz_psutil)
|
||||
|
||||
def test_name(self):
|
||||
name_ps = ps_name(self.pid)
|
||||
# remove path if there is any, from the command
|
||||
name_ps = os.path.basename(name_ps).lower()
|
||||
name_psutil = psutil.Process(self.pid).name().lower()
|
||||
# ...because of how we calculate PYTHON_EXE; on OSX this may
|
||||
# be "pythonX.Y".
|
||||
name_ps = re.sub(r"\d.\d", "", name_ps)
|
||||
name_psutil = re.sub(r"\d.\d", "", name_psutil)
|
||||
self.assertEqual(name_ps, name_psutil)
|
||||
|
||||
def test_name_long(self):
|
||||
# On UNIX the kernel truncates the name to the first 15
|
||||
# characters. In such a case psutil tries to determine the
|
||||
# full name from the cmdline.
|
||||
name = "long-program-name"
|
||||
cmdline = ["long-program-name-extended", "foo", "bar"]
|
||||
with mock.patch("psutil._psplatform.Process.name",
|
||||
return_value=name):
|
||||
with mock.patch("psutil._psplatform.Process.cmdline",
|
||||
return_value=cmdline):
|
||||
p = psutil.Process()
|
||||
self.assertEqual(p.name(), "long-program-name-extended")
|
||||
|
||||
def test_name_long_cmdline_ad_exc(self):
|
||||
# Same as above but emulates a case where cmdline() raises
|
||||
# AccessDenied in which case psutil is supposed to return
|
||||
# the truncated name instead of crashing.
|
||||
name = "long-program-name"
|
||||
with mock.patch("psutil._psplatform.Process.name",
|
||||
return_value=name):
|
||||
with mock.patch("psutil._psplatform.Process.cmdline",
|
||||
side_effect=psutil.AccessDenied(0, "")):
|
||||
p = psutil.Process()
|
||||
self.assertEqual(p.name(), "long-program-name")
|
||||
|
||||
def test_name_long_cmdline_nsp_exc(self):
|
||||
# Same as above but emulates a case where cmdline() raises NSP
|
||||
# which is supposed to propagate.
|
||||
name = "long-program-name"
|
||||
with mock.patch("psutil._psplatform.Process.name",
|
||||
return_value=name):
|
||||
with mock.patch("psutil._psplatform.Process.cmdline",
|
||||
side_effect=psutil.NoSuchProcess(0, "")):
|
||||
p = psutil.Process()
|
||||
self.assertRaises(psutil.NoSuchProcess, p.name)
|
||||
|
||||
@unittest.skipIf(OSX or BSD, 'ps -o start not available')
|
||||
def test_create_time(self):
|
||||
time_ps = ps("ps --no-headers -o start -p %s" % self.pid).split(' ')[0]
|
||||
time_psutil = psutil.Process(self.pid).create_time()
|
||||
time_psutil_tstamp = datetime.datetime.fromtimestamp(
|
||||
time_psutil).strftime("%H:%M:%S")
|
||||
# sometimes ps shows the time rounded up instead of down, so we check
|
||||
# for both possible values
|
||||
round_time_psutil = round(time_psutil)
|
||||
round_time_psutil_tstamp = datetime.datetime.fromtimestamp(
|
||||
round_time_psutil).strftime("%H:%M:%S")
|
||||
self.assertIn(time_ps, [time_psutil_tstamp, round_time_psutil_tstamp])
|
||||
|
||||
def test_exe(self):
|
||||
ps_pathname = ps_name(self.pid)
|
||||
psutil_pathname = psutil.Process(self.pid).exe()
|
||||
try:
|
||||
self.assertEqual(ps_pathname, psutil_pathname)
|
||||
except AssertionError:
|
||||
# certain platforms such as BSD are more accurate returning:
|
||||
# "/usr/local/bin/python2.7"
|
||||
# ...instead of:
|
||||
# "/usr/local/bin/python"
|
||||
# We do not want to consider this difference in accuracy
|
||||
# an error.
|
||||
adjusted_ps_pathname = ps_pathname[:len(ps_pathname)]
|
||||
self.assertEqual(ps_pathname, adjusted_ps_pathname)
|
||||
|
||||
def test_cmdline(self):
|
||||
ps_cmdline = ps_args(self.pid)
|
||||
psutil_cmdline = " ".join(psutil.Process(self.pid).cmdline())
|
||||
self.assertEqual(ps_cmdline, psutil_cmdline)
|
||||
|
||||
# On SUNOS "ps" reads niceness /proc/pid/psinfo which returns an
|
||||
# incorrect value (20); the real deal is getpriority(2) which
|
||||
# returns 0; psutil relies on it, see:
|
||||
# https://github.com/giampaolo/psutil/issues/1082
|
||||
# AIX has the same issue
|
||||
@unittest.skipIf(SUNOS, "not reliable on SUNOS")
|
||||
@unittest.skipIf(AIX, "not reliable on AIX")
|
||||
def test_nice(self):
|
||||
ps_nice = ps("ps --no-headers -o nice -p %s" % self.pid)
|
||||
psutil_nice = psutil.Process().nice()
|
||||
self.assertEqual(ps_nice, psutil_nice)
|
||||
|
||||
def test_num_fds(self):
|
||||
# Note: this fails from time to time; I'm keen on thinking
|
||||
# it doesn't mean something is broken
|
||||
def call(p, attr):
|
||||
args = ()
|
||||
attr = getattr(p, name, None)
|
||||
if attr is not None and callable(attr):
|
||||
if name == 'rlimit':
|
||||
args = (psutil.RLIMIT_NOFILE,)
|
||||
attr(*args)
|
||||
else:
|
||||
attr
|
||||
|
||||
p = psutil.Process(os.getpid())
|
||||
failures = []
|
||||
ignored_names = ['terminate', 'kill', 'suspend', 'resume', 'nice',
|
||||
'send_signal', 'wait', 'children', 'as_dict',
|
||||
'memory_info_ex']
|
||||
if LINUX and get_kernel_version() < (2, 6, 36):
|
||||
ignored_names.append('rlimit')
|
||||
if LINUX and get_kernel_version() < (2, 6, 23):
|
||||
ignored_names.append('num_ctx_switches')
|
||||
for name in dir(psutil.Process):
|
||||
if (name.startswith('_') or name in ignored_names):
|
||||
continue
|
||||
else:
|
||||
try:
|
||||
num1 = p.num_fds()
|
||||
for x in range(2):
|
||||
call(p, name)
|
||||
num2 = p.num_fds()
|
||||
except psutil.AccessDenied:
|
||||
pass
|
||||
else:
|
||||
if abs(num2 - num1) > 1:
|
||||
fail = "failure while processing Process.%s method " \
|
||||
"(before=%s, after=%s)" % (name, num1, num2)
|
||||
failures.append(fail)
|
||||
if failures:
|
||||
self.fail('\n' + '\n'.join(failures))
|
||||
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
class TestSystemAPIs(unittest.TestCase):
|
||||
"""Test some system APIs."""
|
||||
|
||||
@retry_before_failing()
|
||||
def test_pids(self):
|
||||
# Note: this test might fail if the OS is starting/killing
|
||||
# other processes in the meantime
|
||||
if SUNOS or AIX:
|
||||
cmd = ["ps", "-A", "-o", "pid"]
|
||||
else:
|
||||
cmd = ["ps", "ax", "-o", "pid"]
|
||||
p = get_test_subprocess(cmd, stdout=subprocess.PIPE)
|
||||
output = p.communicate()[0].strip()
|
||||
assert p.poll() == 0
|
||||
if PY3:
|
||||
output = str(output, sys.stdout.encoding)
|
||||
pids_ps = []
|
||||
for line in output.split('\n')[1:]:
|
||||
if line:
|
||||
pid = int(line.split()[0].strip())
|
||||
pids_ps.append(pid)
|
||||
# remove ps subprocess pid which is supposed to be dead in meantime
|
||||
pids_ps.remove(p.pid)
|
||||
pids_psutil = psutil.pids()
|
||||
pids_ps.sort()
|
||||
pids_psutil.sort()
|
||||
|
||||
# on OSX and OPENBSD ps doesn't show pid 0
|
||||
if OSX or OPENBSD and 0 not in pids_ps:
|
||||
pids_ps.insert(0, 0)
|
||||
self.assertEqual(pids_ps, pids_psutil)
|
||||
|
||||
# for some reason ifconfig -a does not report all interfaces
|
||||
# returned by psutil
|
||||
@unittest.skipIf(SUNOS, "unreliable on SUNOS")
|
||||
@unittest.skipIf(TRAVIS, "unreliable on TRAVIS")
|
||||
@unittest.skipIf(not which('ifconfig'), "no ifconfig cmd")
|
||||
def test_nic_names(self):
|
||||
output = sh("ifconfig -a")
|
||||
for nic in psutil.net_io_counters(pernic=True).keys():
|
||||
for line in output.split():
|
||||
if line.startswith(nic):
|
||||
break
|
||||
else:
|
||||
self.fail(
|
||||
"couldn't find %s nic in 'ifconfig -a' output\n%s" % (
|
||||
nic, output))
|
||||
|
||||
# can't find users on APPVEYOR or TRAVIS
|
||||
@unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(),
|
||||
"unreliable on APPVEYOR or TRAVIS")
|
||||
@retry_before_failing()
|
||||
def test_users(self):
|
||||
out = sh("who")
|
||||
lines = out.split('\n')
|
||||
users = [x.split()[0] for x in lines]
|
||||
terminals = [x.split()[1] for x in lines]
|
||||
self.assertEqual(len(users), len(psutil.users()))
|
||||
for u in psutil.users():
|
||||
self.assertIn(u.name, users)
|
||||
self.assertIn(u.terminal, terminals)
|
||||
|
||||
def test_pid_exists_let_raise(self):
|
||||
# According to "man 2 kill" possible error values for kill
|
||||
# are (EINVAL, EPERM, ESRCH). Test that any other errno
|
||||
# results in an exception.
|
||||
with mock.patch("psutil._psposix.os.kill",
|
||||
side_effect=OSError(errno.EBADF, "")) as m:
|
||||
self.assertRaises(OSError, psutil._psposix.pid_exists, os.getpid())
|
||||
assert m.called
|
||||
|
||||
def test_os_waitpid_let_raise(self):
|
||||
# os.waitpid() is supposed to catch EINTR and ECHILD only.
|
||||
# Test that any other errno results in an exception.
|
||||
with mock.patch("psutil._psposix.os.waitpid",
|
||||
side_effect=OSError(errno.EBADF, "")) as m:
|
||||
self.assertRaises(OSError, psutil._psposix.wait_pid, os.getpid())
|
||||
assert m.called
|
||||
|
||||
def test_os_waitpid_eintr(self):
|
||||
# os.waitpid() is supposed to "retry" on EINTR.
|
||||
with mock.patch("psutil._psposix.os.waitpid",
|
||||
side_effect=OSError(errno.EINTR, "")) as m:
|
||||
self.assertRaises(
|
||||
psutil._psposix.TimeoutExpired,
|
||||
psutil._psposix.wait_pid, os.getpid(), timeout=0.01)
|
||||
assert m.called
|
||||
|
||||
def test_os_waitpid_bad_ret_status(self):
|
||||
# Simulate os.waitpid() returning a bad status.
|
||||
with mock.patch("psutil._psposix.os.waitpid",
|
||||
return_value=(1, -1)) as m:
|
||||
self.assertRaises(ValueError,
|
||||
psutil._psposix.wait_pid, os.getpid())
|
||||
assert m.called
|
||||
|
||||
# AIX can return '-' in df output instead of numbers, e.g. for /proc
|
||||
@unittest.skipIf(AIX, "unreliable on AIX")
|
||||
def test_disk_usage(self):
|
||||
def df(device):
|
||||
out = sh("df -k %s" % device).strip()
|
||||
line = out.split('\n')[1]
|
||||
fields = line.split()
|
||||
total = int(fields[1]) * 1024
|
||||
used = int(fields[2]) * 1024
|
||||
free = int(fields[3]) * 1024
|
||||
percent = float(fields[4].replace('%', ''))
|
||||
return (total, used, free, percent)
|
||||
|
||||
tolerance = 4 * 1024 * 1024 # 4MB
|
||||
for part in psutil.disk_partitions(all=False):
|
||||
usage = psutil.disk_usage(part.mountpoint)
|
||||
try:
|
||||
total, used, free, percent = df(part.device)
|
||||
except RuntimeError as err:
|
||||
# see:
|
||||
# https://travis-ci.org/giampaolo/psutil/jobs/138338464
|
||||
# https://travis-ci.org/giampaolo/psutil/jobs/138343361
|
||||
err = str(err).lower()
|
||||
if "no such file or directory" in err or \
|
||||
"raw devices not supported" in err or \
|
||||
"permission denied" in err:
|
||||
continue
|
||||
else:
|
||||
raise
|
||||
else:
|
||||
self.assertAlmostEqual(usage.total, total, delta=tolerance)
|
||||
self.assertAlmostEqual(usage.used, used, delta=tolerance)
|
||||
self.assertAlmostEqual(usage.free, free, delta=tolerance)
|
||||
self.assertAlmostEqual(usage.percent, percent, delta=1)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
1565
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_process.py
поставляемый
Normal file
1565
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_process.py
поставляемый
Normal file
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
45
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_sunos.py
поставляемый
Normal file
45
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_sunos.py
поставляемый
Normal file
|
@ -0,0 +1,45 @@
|
|||
#!/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."""
|
||||
|
||||
import os
|
||||
|
||||
import psutil
|
||||
from psutil import SUNOS
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import sh
|
||||
from psutil.tests import unittest
|
||||
|
||||
|
||||
@unittest.skipIf(not SUNOS, "SUNOS only")
|
||||
class SunOSSpecificTestCase(unittest.TestCase):
|
||||
|
||||
def test_swap_memory(self):
|
||||
out = sh('env PATH=/usr/sbin:/sbin:%s swap -l' % os.environ['PATH'])
|
||||
lines = out.strip().split('\n')[1:]
|
||||
if not lines:
|
||||
raise ValueError('no swap device(s) configured')
|
||||
total = free = 0
|
||||
for line in lines:
|
||||
line = line.split()
|
||||
t, f = line[-2:]
|
||||
total += int(int(t) * 512)
|
||||
free += int(int(f) * 512)
|
||||
used = total - free
|
||||
|
||||
psutil_swap = psutil.swap_memory()
|
||||
self.assertEqual(psutil_swap.total, total)
|
||||
self.assertEqual(psutil_swap.used, used)
|
||||
self.assertEqual(psutil_swap.free, free)
|
||||
|
||||
def test_cpu_count(self):
|
||||
out = sh("/usr/sbin/psrinfo")
|
||||
self.assertEqual(psutil.cpu_count(), len(out.split('\n')))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
862
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_system.py
поставляемый
Normal file
862
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_system.py
поставляемый
Normal file
|
@ -0,0 +1,862 @@
|
|||
#!/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.
|
||||
|
||||
"""Tests for system APIS."""
|
||||
|
||||
import contextlib
|
||||
import datetime
|
||||
import errno
|
||||
import os
|
||||
import pprint
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
import psutil
|
||||
from psutil import AIX
|
||||
from psutil import BSD
|
||||
from psutil import FREEBSD
|
||||
from psutil import LINUX
|
||||
from psutil import NETBSD
|
||||
from psutil import OPENBSD
|
||||
from psutil import OSX
|
||||
from psutil import POSIX
|
||||
from psutil import SUNOS
|
||||
from psutil import WINDOWS
|
||||
from psutil._compat import long
|
||||
from psutil.tests import APPVEYOR
|
||||
from psutil.tests import ASCII_FS
|
||||
from psutil.tests import check_net_address
|
||||
from psutil.tests import DEVNULL
|
||||
from psutil.tests import enum
|
||||
from psutil.tests import get_test_subprocess
|
||||
from psutil.tests import HAS_BATTERY
|
||||
from psutil.tests import HAS_CPU_FREQ
|
||||
from psutil.tests import HAS_SENSORS_BATTERY
|
||||
from psutil.tests import HAS_SENSORS_FANS
|
||||
from psutil.tests import HAS_SENSORS_TEMPERATURES
|
||||
from psutil.tests import mock
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import retry_before_failing
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import safe_rmpath
|
||||
from psutil.tests import TESTFN
|
||||
from psutil.tests import TESTFN_UNICODE
|
||||
from psutil.tests import TRAVIS
|
||||
from psutil.tests import unittest
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# --- System-related API tests
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestSystemAPIs(unittest.TestCase):
|
||||
"""Tests for system-related APIs."""
|
||||
|
||||
def setUp(self):
|
||||
safe_rmpath(TESTFN)
|
||||
|
||||
def tearDown(self):
|
||||
reap_children()
|
||||
|
||||
def test_process_iter(self):
|
||||
self.assertIn(os.getpid(), [x.pid for x in psutil.process_iter()])
|
||||
sproc = get_test_subprocess()
|
||||
self.assertIn(sproc.pid, [x.pid for x in psutil.process_iter()])
|
||||
p = psutil.Process(sproc.pid)
|
||||
p.kill()
|
||||
p.wait()
|
||||
self.assertNotIn(sproc.pid, [x.pid for x in psutil.process_iter()])
|
||||
|
||||
with mock.patch('psutil.Process',
|
||||
side_effect=psutil.NoSuchProcess(os.getpid())):
|
||||
self.assertEqual(list(psutil.process_iter()), [])
|
||||
with mock.patch('psutil.Process',
|
||||
side_effect=psutil.AccessDenied(os.getpid())):
|
||||
with self.assertRaises(psutil.AccessDenied):
|
||||
list(psutil.process_iter())
|
||||
|
||||
def test_prcess_iter_w_params(self):
|
||||
for p in psutil.process_iter(attrs=['pid']):
|
||||
self.assertEqual(list(p.info.keys()), ['pid'])
|
||||
with self.assertRaises(ValueError):
|
||||
list(psutil.process_iter(attrs=['foo']))
|
||||
with mock.patch("psutil._psplatform.Process.cpu_times",
|
||||
side_effect=psutil.AccessDenied(0, "")) as m:
|
||||
for p in psutil.process_iter(attrs=["pid", "cpu_times"]):
|
||||
self.assertIsNone(p.info['cpu_times'])
|
||||
self.assertGreaterEqual(p.info['pid'], 0)
|
||||
assert m.called
|
||||
with mock.patch("psutil._psplatform.Process.cpu_times",
|
||||
side_effect=psutil.AccessDenied(0, "")) as m:
|
||||
flag = object()
|
||||
for p in psutil.process_iter(
|
||||
attrs=["pid", "cpu_times"], ad_value=flag):
|
||||
self.assertIs(p.info['cpu_times'], flag)
|
||||
self.assertGreaterEqual(p.info['pid'], 0)
|
||||
assert m.called
|
||||
|
||||
def test_wait_procs(self):
|
||||
def callback(p):
|
||||
pids.append(p.pid)
|
||||
|
||||
pids = []
|
||||
sproc1 = get_test_subprocess()
|
||||
sproc2 = get_test_subprocess()
|
||||
sproc3 = get_test_subprocess()
|
||||
procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)]
|
||||
self.assertRaises(ValueError, psutil.wait_procs, procs, timeout=-1)
|
||||
self.assertRaises(TypeError, psutil.wait_procs, procs, callback=1)
|
||||
t = time.time()
|
||||
gone, alive = psutil.wait_procs(procs, timeout=0.01, callback=callback)
|
||||
|
||||
self.assertLess(time.time() - t, 0.5)
|
||||
self.assertEqual(gone, [])
|
||||
self.assertEqual(len(alive), 3)
|
||||
self.assertEqual(pids, [])
|
||||
for p in alive:
|
||||
self.assertFalse(hasattr(p, 'returncode'))
|
||||
|
||||
@retry_before_failing(30)
|
||||
def test(procs, callback):
|
||||
gone, alive = psutil.wait_procs(procs, timeout=0.03,
|
||||
callback=callback)
|
||||
self.assertEqual(len(gone), 1)
|
||||
self.assertEqual(len(alive), 2)
|
||||
return gone, alive
|
||||
|
||||
sproc3.terminate()
|
||||
gone, alive = test(procs, callback)
|
||||
self.assertIn(sproc3.pid, [x.pid for x in gone])
|
||||
if POSIX:
|
||||
self.assertEqual(gone.pop().returncode, -signal.SIGTERM)
|
||||
else:
|
||||
self.assertEqual(gone.pop().returncode, 1)
|
||||
self.assertEqual(pids, [sproc3.pid])
|
||||
for p in alive:
|
||||
self.assertFalse(hasattr(p, 'returncode'))
|
||||
|
||||
@retry_before_failing(30)
|
||||
def test(procs, callback):
|
||||
gone, alive = psutil.wait_procs(procs, timeout=0.03,
|
||||
callback=callback)
|
||||
self.assertEqual(len(gone), 3)
|
||||
self.assertEqual(len(alive), 0)
|
||||
return gone, alive
|
||||
|
||||
sproc1.terminate()
|
||||
sproc2.terminate()
|
||||
gone, alive = test(procs, callback)
|
||||
self.assertEqual(set(pids), set([sproc1.pid, sproc2.pid, sproc3.pid]))
|
||||
for p in gone:
|
||||
self.assertTrue(hasattr(p, 'returncode'))
|
||||
|
||||
def test_wait_procs_no_timeout(self):
|
||||
sproc1 = get_test_subprocess()
|
||||
sproc2 = get_test_subprocess()
|
||||
sproc3 = get_test_subprocess()
|
||||
procs = [psutil.Process(x.pid) for x in (sproc1, sproc2, sproc3)]
|
||||
for p in procs:
|
||||
p.terminate()
|
||||
gone, alive = psutil.wait_procs(procs)
|
||||
|
||||
def test_boot_time(self):
|
||||
bt = psutil.boot_time()
|
||||
self.assertIsInstance(bt, float)
|
||||
self.assertGreater(bt, 0)
|
||||
self.assertLess(bt, time.time())
|
||||
|
||||
@unittest.skipIf(not POSIX, 'POSIX only')
|
||||
def test_PAGESIZE(self):
|
||||
# pagesize is used internally to perform different calculations
|
||||
# and it's determined by using SC_PAGE_SIZE; make sure
|
||||
# getpagesize() returns the same value.
|
||||
import resource
|
||||
self.assertEqual(os.sysconf("SC_PAGE_SIZE"), resource.getpagesize())
|
||||
|
||||
def test_virtual_memory(self):
|
||||
mem = psutil.virtual_memory()
|
||||
assert mem.total > 0, mem
|
||||
assert mem.available > 0, mem
|
||||
assert 0 <= mem.percent <= 100, mem
|
||||
assert mem.used > 0, mem
|
||||
assert mem.free >= 0, mem
|
||||
for name in mem._fields:
|
||||
value = getattr(mem, name)
|
||||
if name != 'percent':
|
||||
self.assertIsInstance(value, (int, long))
|
||||
if name != 'total':
|
||||
if not value >= 0:
|
||||
self.fail("%r < 0 (%s)" % (name, value))
|
||||
if value > mem.total:
|
||||
self.fail("%r > total (total=%s, %s=%s)"
|
||||
% (name, mem.total, name, value))
|
||||
|
||||
def test_swap_memory(self):
|
||||
mem = psutil.swap_memory()
|
||||
self.assertEqual(
|
||||
mem._fields, ('total', 'used', 'free', 'percent', 'sin', 'sout'))
|
||||
|
||||
assert mem.total >= 0, mem
|
||||
assert mem.used >= 0, mem
|
||||
if mem.total > 0:
|
||||
# likely a system with no swap partition
|
||||
assert mem.free > 0, mem
|
||||
else:
|
||||
assert mem.free == 0, mem
|
||||
assert 0 <= mem.percent <= 100, mem
|
||||
assert mem.sin >= 0, mem
|
||||
assert mem.sout >= 0, mem
|
||||
|
||||
def test_pid_exists(self):
|
||||
sproc = get_test_subprocess()
|
||||
self.assertTrue(psutil.pid_exists(sproc.pid))
|
||||
p = psutil.Process(sproc.pid)
|
||||
p.kill()
|
||||
p.wait()
|
||||
self.assertFalse(psutil.pid_exists(sproc.pid))
|
||||
self.assertFalse(psutil.pid_exists(-1))
|
||||
self.assertEqual(psutil.pid_exists(0), 0 in psutil.pids())
|
||||
|
||||
def test_pid_exists_2(self):
|
||||
reap_children()
|
||||
pids = psutil.pids()
|
||||
for pid in pids:
|
||||
try:
|
||||
assert psutil.pid_exists(pid)
|
||||
except AssertionError:
|
||||
# in case the process disappeared in meantime fail only
|
||||
# if it is no longer in psutil.pids()
|
||||
time.sleep(.1)
|
||||
if pid in psutil.pids():
|
||||
self.fail(pid)
|
||||
pids = range(max(pids) + 5000, max(pids) + 6000)
|
||||
for pid in pids:
|
||||
self.assertFalse(psutil.pid_exists(pid), msg=pid)
|
||||
|
||||
def test_pids(self):
|
||||
plist = [x.pid for x in psutil.process_iter()]
|
||||
pidlist = psutil.pids()
|
||||
self.assertEqual(plist.sort(), pidlist.sort())
|
||||
# make sure every pid is unique
|
||||
self.assertEqual(len(pidlist), len(set(pidlist)))
|
||||
|
||||
def test_test(self):
|
||||
# test for psutil.test() function
|
||||
stdout = sys.stdout
|
||||
sys.stdout = DEVNULL
|
||||
try:
|
||||
psutil.test()
|
||||
finally:
|
||||
sys.stdout = stdout
|
||||
|
||||
def test_cpu_count(self):
|
||||
logical = psutil.cpu_count()
|
||||
self.assertEqual(logical, len(psutil.cpu_times(percpu=True)))
|
||||
self.assertGreaterEqual(logical, 1)
|
||||
#
|
||||
if os.path.exists("/proc/cpuinfo"):
|
||||
with open("/proc/cpuinfo") as fd:
|
||||
cpuinfo_data = fd.read()
|
||||
if "physical id" not in cpuinfo_data:
|
||||
raise unittest.SkipTest("cpuinfo doesn't include physical id")
|
||||
physical = psutil.cpu_count(logical=False)
|
||||
self.assertGreaterEqual(physical, 1)
|
||||
self.assertGreaterEqual(logical, physical)
|
||||
|
||||
def test_cpu_count_none(self):
|
||||
# https://github.com/giampaolo/psutil/issues/1085
|
||||
for val in (-1, 0, None):
|
||||
with mock.patch('psutil._psplatform.cpu_count_logical',
|
||||
return_value=val) as m:
|
||||
self.assertIsNone(psutil.cpu_count())
|
||||
assert m.called
|
||||
with mock.patch('psutil._psplatform.cpu_count_physical',
|
||||
return_value=val) as m:
|
||||
self.assertIsNone(psutil.cpu_count(logical=False))
|
||||
assert m.called
|
||||
|
||||
def test_cpu_times(self):
|
||||
# Check type, value >= 0, str().
|
||||
total = 0
|
||||
times = psutil.cpu_times()
|
||||
sum(times)
|
||||
for cp_time in times:
|
||||
self.assertIsInstance(cp_time, float)
|
||||
self.assertGreaterEqual(cp_time, 0.0)
|
||||
total += cp_time
|
||||
self.assertEqual(total, sum(times))
|
||||
str(times)
|
||||
# CPU times are always supposed to increase over time
|
||||
# or at least remain the same and that's because time
|
||||
# cannot go backwards.
|
||||
# Surprisingly sometimes this might not be the case (at
|
||||
# least on Windows and Linux), see:
|
||||
# https://github.com/giampaolo/psutil/issues/392
|
||||
# https://github.com/giampaolo/psutil/issues/645
|
||||
# if not WINDOWS:
|
||||
# last = psutil.cpu_times()
|
||||
# for x in range(100):
|
||||
# new = psutil.cpu_times()
|
||||
# for field in new._fields:
|
||||
# new_t = getattr(new, field)
|
||||
# last_t = getattr(last, field)
|
||||
# self.assertGreaterEqual(new_t, last_t,
|
||||
# msg="%s %s" % (new_t, last_t))
|
||||
# last = new
|
||||
|
||||
def test_cpu_times_time_increases(self):
|
||||
# Make sure time increases between calls.
|
||||
t1 = sum(psutil.cpu_times())
|
||||
time.sleep(0.1)
|
||||
t2 = sum(psutil.cpu_times())
|
||||
difference = t2 - t1
|
||||
if not difference >= 0.05:
|
||||
self.fail("difference %s" % difference)
|
||||
|
||||
def test_per_cpu_times(self):
|
||||
# Check type, value >= 0, str().
|
||||
for times in psutil.cpu_times(percpu=True):
|
||||
total = 0
|
||||
sum(times)
|
||||
for cp_time in times:
|
||||
self.assertIsInstance(cp_time, float)
|
||||
self.assertGreaterEqual(cp_time, 0.0)
|
||||
total += cp_time
|
||||
self.assertEqual(total, sum(times))
|
||||
str(times)
|
||||
self.assertEqual(len(psutil.cpu_times(percpu=True)[0]),
|
||||
len(psutil.cpu_times(percpu=False)))
|
||||
|
||||
# Note: in theory CPU times are always supposed to increase over
|
||||
# time or remain the same but never go backwards. In practice
|
||||
# sometimes this is not the case.
|
||||
# This issue seemd to be afflict Windows:
|
||||
# https://github.com/giampaolo/psutil/issues/392
|
||||
# ...but it turns out also Linux (rarely) behaves the same.
|
||||
# last = psutil.cpu_times(percpu=True)
|
||||
# for x in range(100):
|
||||
# new = psutil.cpu_times(percpu=True)
|
||||
# for index in range(len(new)):
|
||||
# newcpu = new[index]
|
||||
# lastcpu = last[index]
|
||||
# for field in newcpu._fields:
|
||||
# new_t = getattr(newcpu, field)
|
||||
# last_t = getattr(lastcpu, field)
|
||||
# self.assertGreaterEqual(
|
||||
# new_t, last_t, msg="%s %s" % (lastcpu, newcpu))
|
||||
# last = new
|
||||
|
||||
def test_per_cpu_times_2(self):
|
||||
# Simulate some work load then make sure time have increased
|
||||
# between calls.
|
||||
tot1 = psutil.cpu_times(percpu=True)
|
||||
stop_at = time.time() + 0.1
|
||||
while True:
|
||||
if time.time() >= stop_at:
|
||||
break
|
||||
tot2 = psutil.cpu_times(percpu=True)
|
||||
for t1, t2 in zip(tot1, tot2):
|
||||
t1, t2 = sum(t1), sum(t2)
|
||||
difference = t2 - t1
|
||||
if difference >= 0.05:
|
||||
return
|
||||
self.fail()
|
||||
|
||||
def test_cpu_times_comparison(self):
|
||||
# Make sure the sum of all per cpu times is almost equal to
|
||||
# base "one cpu" times.
|
||||
base = psutil.cpu_times()
|
||||
per_cpu = psutil.cpu_times(percpu=True)
|
||||
summed_values = base._make([sum(num) for num in zip(*per_cpu)])
|
||||
for field in base._fields:
|
||||
self.assertAlmostEqual(
|
||||
getattr(base, field), getattr(summed_values, field), delta=1)
|
||||
|
||||
def _test_cpu_percent(self, percent, last_ret, new_ret):
|
||||
try:
|
||||
self.assertIsInstance(percent, float)
|
||||
self.assertGreaterEqual(percent, 0.0)
|
||||
self.assertIsNot(percent, -0.0)
|
||||
self.assertLessEqual(percent, 100.0 * psutil.cpu_count())
|
||||
except AssertionError as err:
|
||||
raise AssertionError("\n%s\nlast=%s\nnew=%s" % (
|
||||
err, pprint.pformat(last_ret), pprint.pformat(new_ret)))
|
||||
|
||||
def test_cpu_percent(self):
|
||||
last = psutil.cpu_percent(interval=0.001)
|
||||
for x in range(100):
|
||||
new = psutil.cpu_percent(interval=None)
|
||||
self._test_cpu_percent(new, last, new)
|
||||
last = new
|
||||
with self.assertRaises(ValueError):
|
||||
psutil.cpu_percent(interval=-1)
|
||||
|
||||
def test_per_cpu_percent(self):
|
||||
last = psutil.cpu_percent(interval=0.001, percpu=True)
|
||||
self.assertEqual(len(last), psutil.cpu_count())
|
||||
for x in range(100):
|
||||
new = psutil.cpu_percent(interval=None, percpu=True)
|
||||
for percent in new:
|
||||
self._test_cpu_percent(percent, last, new)
|
||||
last = new
|
||||
with self.assertRaises(ValueError):
|
||||
psutil.cpu_percent(interval=-1, percpu=True)
|
||||
|
||||
def test_cpu_times_percent(self):
|
||||
last = psutil.cpu_times_percent(interval=0.001)
|
||||
for x in range(100):
|
||||
new = psutil.cpu_times_percent(interval=None)
|
||||
for percent in new:
|
||||
self._test_cpu_percent(percent, last, new)
|
||||
self._test_cpu_percent(sum(new), last, new)
|
||||
last = new
|
||||
|
||||
def test_per_cpu_times_percent(self):
|
||||
last = psutil.cpu_times_percent(interval=0.001, percpu=True)
|
||||
self.assertEqual(len(last), psutil.cpu_count())
|
||||
for x in range(100):
|
||||
new = psutil.cpu_times_percent(interval=None, percpu=True)
|
||||
for cpu in new:
|
||||
for percent in cpu:
|
||||
self._test_cpu_percent(percent, last, new)
|
||||
self._test_cpu_percent(sum(cpu), last, new)
|
||||
last = new
|
||||
|
||||
def test_per_cpu_times_percent_negative(self):
|
||||
# see: https://github.com/giampaolo/psutil/issues/645
|
||||
psutil.cpu_times_percent(percpu=True)
|
||||
zero_times = [x._make([0 for x in range(len(x._fields))])
|
||||
for x in psutil.cpu_times(percpu=True)]
|
||||
with mock.patch('psutil.cpu_times', return_value=zero_times):
|
||||
for cpu in psutil.cpu_times_percent(percpu=True):
|
||||
for percent in cpu:
|
||||
self._test_cpu_percent(percent, None, None)
|
||||
|
||||
def test_disk_usage(self):
|
||||
usage = psutil.disk_usage(os.getcwd())
|
||||
self.assertEqual(usage._fields, ('total', 'used', 'free', 'percent'))
|
||||
|
||||
assert usage.total > 0, usage
|
||||
assert usage.used > 0, usage
|
||||
assert usage.free > 0, usage
|
||||
assert usage.total > usage.used, usage
|
||||
assert usage.total > usage.free, usage
|
||||
assert 0 <= usage.percent <= 100, usage.percent
|
||||
if hasattr(shutil, 'disk_usage'):
|
||||
# py >= 3.3, see: http://bugs.python.org/issue12442
|
||||
shutil_usage = shutil.disk_usage(os.getcwd())
|
||||
tolerance = 5 * 1024 * 1024 # 5MB
|
||||
self.assertEqual(usage.total, shutil_usage.total)
|
||||
self.assertAlmostEqual(usage.free, shutil_usage.free,
|
||||
delta=tolerance)
|
||||
self.assertAlmostEqual(usage.used, shutil_usage.used,
|
||||
delta=tolerance)
|
||||
|
||||
# if path does not exist OSError ENOENT is expected across
|
||||
# all platforms
|
||||
fname = tempfile.mktemp()
|
||||
with self.assertRaises(OSError) as exc:
|
||||
psutil.disk_usage(fname)
|
||||
self.assertEqual(exc.exception.errno, errno.ENOENT)
|
||||
|
||||
def test_disk_usage_unicode(self):
|
||||
# See: https://github.com/giampaolo/psutil/issues/416
|
||||
if ASCII_FS:
|
||||
with self.assertRaises(UnicodeEncodeError):
|
||||
psutil.disk_usage(TESTFN_UNICODE)
|
||||
|
||||
def test_disk_usage_bytes(self):
|
||||
psutil.disk_usage(b'.')
|
||||
|
||||
def test_disk_partitions(self):
|
||||
# all = False
|
||||
ls = psutil.disk_partitions(all=False)
|
||||
# on travis we get:
|
||||
# self.assertEqual(p.cpu_affinity(), [n])
|
||||
# AssertionError: Lists differ: [0, 1, 2, 3, 4, 5, 6, 7,... != [0]
|
||||
self.assertTrue(ls, msg=ls)
|
||||
for disk in ls:
|
||||
self.assertIsInstance(disk.device, str)
|
||||
self.assertIsInstance(disk.mountpoint, str)
|
||||
self.assertIsInstance(disk.fstype, str)
|
||||
self.assertIsInstance(disk.opts, str)
|
||||
if WINDOWS and 'cdrom' in disk.opts:
|
||||
continue
|
||||
if not POSIX:
|
||||
assert os.path.exists(disk.device), disk
|
||||
else:
|
||||
# we cannot make any assumption about this, see:
|
||||
# http://goo.gl/p9c43
|
||||
disk.device
|
||||
if SUNOS or TRAVIS:
|
||||
# on solaris apparently mount points can also be files
|
||||
assert os.path.exists(disk.mountpoint), disk
|
||||
else:
|
||||
assert os.path.isdir(disk.mountpoint), disk
|
||||
assert disk.fstype, disk
|
||||
|
||||
# all = True
|
||||
ls = psutil.disk_partitions(all=True)
|
||||
self.assertTrue(ls, msg=ls)
|
||||
for disk in psutil.disk_partitions(all=True):
|
||||
if not WINDOWS:
|
||||
try:
|
||||
os.stat(disk.mountpoint)
|
||||
except OSError as err:
|
||||
if TRAVIS and OSX and err.errno == errno.EIO:
|
||||
continue
|
||||
# http://mail.python.org/pipermail/python-dev/
|
||||
# 2012-June/120787.html
|
||||
if err.errno not in (errno.EPERM, errno.EACCES):
|
||||
raise
|
||||
else:
|
||||
if SUNOS or TRAVIS:
|
||||
# on solaris apparently mount points can also be files
|
||||
assert os.path.exists(disk.mountpoint), disk
|
||||
else:
|
||||
assert os.path.isdir(disk.mountpoint), disk
|
||||
self.assertIsInstance(disk.fstype, str)
|
||||
self.assertIsInstance(disk.opts, str)
|
||||
|
||||
def find_mount_point(path):
|
||||
path = os.path.abspath(path)
|
||||
while not os.path.ismount(path):
|
||||
path = os.path.dirname(path)
|
||||
return path.lower()
|
||||
|
||||
mount = find_mount_point(__file__)
|
||||
mounts = [x.mountpoint.lower() for x in
|
||||
psutil.disk_partitions(all=True)]
|
||||
self.assertIn(mount, mounts)
|
||||
psutil.disk_usage(mount)
|
||||
|
||||
def test_net_io_counters(self):
|
||||
def check_ntuple(nt):
|
||||
self.assertEqual(nt[0], nt.bytes_sent)
|
||||
self.assertEqual(nt[1], nt.bytes_recv)
|
||||
self.assertEqual(nt[2], nt.packets_sent)
|
||||
self.assertEqual(nt[3], nt.packets_recv)
|
||||
self.assertEqual(nt[4], nt.errin)
|
||||
self.assertEqual(nt[5], nt.errout)
|
||||
self.assertEqual(nt[6], nt.dropin)
|
||||
self.assertEqual(nt[7], nt.dropout)
|
||||
assert nt.bytes_sent >= 0, nt
|
||||
assert nt.bytes_recv >= 0, nt
|
||||
assert nt.packets_sent >= 0, nt
|
||||
assert nt.packets_recv >= 0, nt
|
||||
assert nt.errin >= 0, nt
|
||||
assert nt.errout >= 0, nt
|
||||
assert nt.dropin >= 0, nt
|
||||
assert nt.dropout >= 0, nt
|
||||
|
||||
ret = psutil.net_io_counters(pernic=False)
|
||||
check_ntuple(ret)
|
||||
ret = psutil.net_io_counters(pernic=True)
|
||||
self.assertNotEqual(ret, [])
|
||||
for key in ret:
|
||||
self.assertTrue(key)
|
||||
self.assertIsInstance(key, str)
|
||||
check_ntuple(ret[key])
|
||||
|
||||
def test_net_io_counters_no_nics(self):
|
||||
# Emulate a case where no NICs are installed, see:
|
||||
# https://github.com/giampaolo/psutil/issues/1062
|
||||
with mock.patch('psutil._psplatform.net_io_counters',
|
||||
return_value={}) as m:
|
||||
self.assertIsNone(psutil.net_io_counters(pernic=False))
|
||||
self.assertEqual(psutil.net_io_counters(pernic=True), {})
|
||||
assert m.called
|
||||
|
||||
def test_net_if_addrs(self):
|
||||
nics = psutil.net_if_addrs()
|
||||
assert nics, nics
|
||||
|
||||
nic_stats = psutil.net_if_stats()
|
||||
|
||||
# Not reliable on all platforms (net_if_addrs() reports more
|
||||
# interfaces).
|
||||
# self.assertEqual(sorted(nics.keys()),
|
||||
# sorted(psutil.net_io_counters(pernic=True).keys()))
|
||||
|
||||
families = set([socket.AF_INET, socket.AF_INET6, psutil.AF_LINK])
|
||||
for nic, addrs in nics.items():
|
||||
self.assertIsInstance(nic, str)
|
||||
self.assertEqual(len(set(addrs)), len(addrs))
|
||||
for addr in addrs:
|
||||
self.assertIsInstance(addr.family, int)
|
||||
self.assertIsInstance(addr.address, str)
|
||||
self.assertIsInstance(addr.netmask, (str, type(None)))
|
||||
self.assertIsInstance(addr.broadcast, (str, type(None)))
|
||||
self.assertIn(addr.family, families)
|
||||
if sys.version_info >= (3, 4):
|
||||
self.assertIsInstance(addr.family, enum.IntEnum)
|
||||
if nic_stats[nic].isup:
|
||||
# Do not test binding to addresses of interfaces
|
||||
# that are down
|
||||
if addr.family == socket.AF_INET:
|
||||
s = socket.socket(addr.family)
|
||||
with contextlib.closing(s):
|
||||
s.bind((addr.address, 0))
|
||||
elif addr.family == socket.AF_INET6:
|
||||
info = socket.getaddrinfo(
|
||||
addr.address, 0, socket.AF_INET6,
|
||||
socket.SOCK_STREAM, 0, socket.AI_PASSIVE)[0]
|
||||
af, socktype, proto, canonname, sa = info
|
||||
s = socket.socket(af, socktype, proto)
|
||||
with contextlib.closing(s):
|
||||
s.bind(sa)
|
||||
for ip in (addr.address, addr.netmask, addr.broadcast,
|
||||
addr.ptp):
|
||||
if ip is not None:
|
||||
# TODO: skip AF_INET6 for now because I get:
|
||||
# AddressValueError: Only hex digits permitted in
|
||||
# u'c6f3%lxcbr0' in u'fe80::c8e0:fff:fe54:c6f3%lxcbr0'
|
||||
if addr.family != socket.AF_INET6:
|
||||
check_net_address(ip, addr.family)
|
||||
# broadcast and ptp addresses are mutually exclusive
|
||||
if addr.broadcast:
|
||||
self.assertIsNone(addr.ptp)
|
||||
elif addr.ptp:
|
||||
self.assertIsNone(addr.broadcast)
|
||||
|
||||
if BSD or OSX or SUNOS:
|
||||
if hasattr(socket, "AF_LINK"):
|
||||
self.assertEqual(psutil.AF_LINK, socket.AF_LINK)
|
||||
elif LINUX:
|
||||
self.assertEqual(psutil.AF_LINK, socket.AF_PACKET)
|
||||
elif WINDOWS:
|
||||
self.assertEqual(psutil.AF_LINK, -1)
|
||||
|
||||
def test_net_if_addrs_mac_null_bytes(self):
|
||||
# Simulate that the underlying C function returns an incomplete
|
||||
# MAC address. psutil is supposed to fill it with null bytes.
|
||||
# https://github.com/giampaolo/psutil/issues/786
|
||||
if POSIX:
|
||||
ret = [('em1', psutil.AF_LINK, '06:3d:29', None, None, None)]
|
||||
else:
|
||||
ret = [('em1', -1, '06-3d-29', None, None, None)]
|
||||
with mock.patch('psutil._psplatform.net_if_addrs',
|
||||
return_value=ret) as m:
|
||||
addr = psutil.net_if_addrs()['em1'][0]
|
||||
assert m.called
|
||||
if POSIX:
|
||||
self.assertEqual(addr.address, '06:3d:29:00:00:00')
|
||||
else:
|
||||
self.assertEqual(addr.address, '06-3d-29-00-00-00')
|
||||
|
||||
@unittest.skipIf(TRAVIS, "unreliable on TRAVIS") # raises EPERM
|
||||
def test_net_if_stats(self):
|
||||
nics = psutil.net_if_stats()
|
||||
assert nics, nics
|
||||
all_duplexes = (psutil.NIC_DUPLEX_FULL,
|
||||
psutil.NIC_DUPLEX_HALF,
|
||||
psutil.NIC_DUPLEX_UNKNOWN)
|
||||
for name, stats in nics.items():
|
||||
self.assertIsInstance(name, str)
|
||||
isup, duplex, speed, mtu = stats
|
||||
self.assertIsInstance(isup, bool)
|
||||
self.assertIn(duplex, all_duplexes)
|
||||
self.assertIn(duplex, all_duplexes)
|
||||
self.assertGreaterEqual(speed, 0)
|
||||
self.assertGreaterEqual(mtu, 0)
|
||||
|
||||
@unittest.skipIf(LINUX and not os.path.exists('/proc/diskstats'),
|
||||
'/proc/diskstats not available on this linux version')
|
||||
@unittest.skipIf(APPVEYOR and psutil.disk_io_counters() is None,
|
||||
"unreliable on APPVEYOR") # no visible disks
|
||||
def test_disk_io_counters(self):
|
||||
def check_ntuple(nt):
|
||||
self.assertEqual(nt[0], nt.read_count)
|
||||
self.assertEqual(nt[1], nt.write_count)
|
||||
self.assertEqual(nt[2], nt.read_bytes)
|
||||
self.assertEqual(nt[3], nt.write_bytes)
|
||||
if not (OPENBSD or NETBSD):
|
||||
self.assertEqual(nt[4], nt.read_time)
|
||||
self.assertEqual(nt[5], nt.write_time)
|
||||
if LINUX:
|
||||
self.assertEqual(nt[6], nt.read_merged_count)
|
||||
self.assertEqual(nt[7], nt.write_merged_count)
|
||||
self.assertEqual(nt[8], nt.busy_time)
|
||||
elif FREEBSD:
|
||||
self.assertEqual(nt[6], nt.busy_time)
|
||||
for name in nt._fields:
|
||||
assert getattr(nt, name) >= 0, nt
|
||||
|
||||
ret = psutil.disk_io_counters(perdisk=False)
|
||||
assert ret is not None, "no disks on this system?"
|
||||
check_ntuple(ret)
|
||||
ret = psutil.disk_io_counters(perdisk=True)
|
||||
# make sure there are no duplicates
|
||||
self.assertEqual(len(ret), len(set(ret)))
|
||||
for key in ret:
|
||||
assert key, key
|
||||
check_ntuple(ret[key])
|
||||
if LINUX and key[-1].isdigit():
|
||||
# if 'sda1' is listed 'sda' shouldn't, see:
|
||||
# https://github.com/giampaolo/psutil/issues/338
|
||||
while key[-1].isdigit():
|
||||
key = key[:-1]
|
||||
self.assertNotIn(key, ret.keys())
|
||||
|
||||
def test_disk_io_counters_no_disks(self):
|
||||
# Emulate a case where no disks are installed, see:
|
||||
# https://github.com/giampaolo/psutil/issues/1062
|
||||
with mock.patch('psutil._psplatform.disk_io_counters',
|
||||
return_value={}) as m:
|
||||
self.assertIsNone(psutil.disk_io_counters(perdisk=False))
|
||||
self.assertEqual(psutil.disk_io_counters(perdisk=True), {})
|
||||
assert m.called
|
||||
|
||||
# can't find users on APPVEYOR or TRAVIS
|
||||
@unittest.skipIf(APPVEYOR or TRAVIS and not psutil.users(),
|
||||
"unreliable on APPVEYOR or TRAVIS")
|
||||
def test_users(self):
|
||||
users = psutil.users()
|
||||
self.assertNotEqual(users, [])
|
||||
for user in users:
|
||||
assert user.name, user
|
||||
self.assertIsInstance(user.name, str)
|
||||
self.assertIsInstance(user.terminal, (str, type(None)))
|
||||
if user.host is not None:
|
||||
self.assertIsInstance(user.host, (str, type(None)))
|
||||
user.terminal
|
||||
user.host
|
||||
assert user.started > 0.0, user
|
||||
datetime.datetime.fromtimestamp(user.started)
|
||||
if WINDOWS or OPENBSD:
|
||||
self.assertIsNone(user.pid)
|
||||
else:
|
||||
psutil.Process(user.pid)
|
||||
|
||||
def test_cpu_stats(self):
|
||||
# Tested more extensively in per-platform test modules.
|
||||
infos = psutil.cpu_stats()
|
||||
self.assertEqual(
|
||||
infos._fields,
|
||||
('ctx_switches', 'interrupts', 'soft_interrupts', 'syscalls'))
|
||||
for name in infos._fields:
|
||||
value = getattr(infos, name)
|
||||
self.assertGreaterEqual(value, 0)
|
||||
# on AIX, ctx_switches is always 0
|
||||
if not AIX and name in ('ctx_switches', 'interrupts'):
|
||||
self.assertGreater(value, 0)
|
||||
|
||||
@unittest.skipIf(not HAS_CPU_FREQ, "not suported")
|
||||
def test_cpu_freq(self):
|
||||
def check_ls(ls):
|
||||
for nt in ls:
|
||||
self.assertEqual(nt._fields, ('current', 'min', 'max'))
|
||||
self.assertLessEqual(nt.current, nt.max)
|
||||
for name in nt._fields:
|
||||
value = getattr(nt, name)
|
||||
self.assertIsInstance(value, (int, long, float))
|
||||
self.assertGreaterEqual(value, 0)
|
||||
|
||||
ls = psutil.cpu_freq(percpu=True)
|
||||
if TRAVIS and not ls:
|
||||
return
|
||||
|
||||
assert ls, ls
|
||||
check_ls([psutil.cpu_freq(percpu=False)])
|
||||
|
||||
if LINUX:
|
||||
self.assertEqual(len(ls), psutil.cpu_count())
|
||||
|
||||
def test_os_constants(self):
|
||||
names = ["POSIX", "WINDOWS", "LINUX", "OSX", "FREEBSD", "OPENBSD",
|
||||
"NETBSD", "BSD", "SUNOS"]
|
||||
for name in names:
|
||||
self.assertIsInstance(getattr(psutil, name), bool, msg=name)
|
||||
|
||||
if os.name == 'posix':
|
||||
assert psutil.POSIX
|
||||
assert not psutil.WINDOWS
|
||||
names.remove("POSIX")
|
||||
if "linux" in sys.platform.lower():
|
||||
assert psutil.LINUX
|
||||
names.remove("LINUX")
|
||||
elif "bsd" in sys.platform.lower():
|
||||
assert psutil.BSD
|
||||
self.assertEqual([psutil.FREEBSD, psutil.OPENBSD,
|
||||
psutil.NETBSD].count(True), 1)
|
||||
names.remove("BSD")
|
||||
names.remove("FREEBSD")
|
||||
names.remove("OPENBSD")
|
||||
names.remove("NETBSD")
|
||||
elif "sunos" in sys.platform.lower() or \
|
||||
"solaris" in sys.platform.lower():
|
||||
assert psutil.SUNOS
|
||||
names.remove("SUNOS")
|
||||
elif "darwin" in sys.platform.lower():
|
||||
assert psutil.OSX
|
||||
names.remove("OSX")
|
||||
else:
|
||||
assert psutil.WINDOWS
|
||||
assert not psutil.POSIX
|
||||
names.remove("WINDOWS")
|
||||
|
||||
# assert all other constants are set to False
|
||||
for name in names:
|
||||
self.assertIs(getattr(psutil, name), False, msg=name)
|
||||
|
||||
@unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
|
||||
def test_sensors_temperatures(self):
|
||||
temps = psutil.sensors_temperatures()
|
||||
for name, entries in temps.items():
|
||||
self.assertIsInstance(name, str)
|
||||
for entry in entries:
|
||||
self.assertIsInstance(entry.label, str)
|
||||
if entry.current is not None:
|
||||
self.assertGreaterEqual(entry.current, 0)
|
||||
if entry.high is not None:
|
||||
self.assertGreaterEqual(entry.high, 0)
|
||||
if entry.critical is not None:
|
||||
self.assertGreaterEqual(entry.critical, 0)
|
||||
|
||||
@unittest.skipIf(not HAS_SENSORS_TEMPERATURES, "not supported")
|
||||
def test_sensors_temperatures_fahreneit(self):
|
||||
d = {'coretemp': [('label', 50.0, 60.0, 70.0)]}
|
||||
with mock.patch("psutil._psplatform.sensors_temperatures",
|
||||
return_value=d) as m:
|
||||
temps = psutil.sensors_temperatures(
|
||||
fahrenheit=True)['coretemp'][0]
|
||||
assert m.called
|
||||
self.assertEqual(temps.current, 122.0)
|
||||
self.assertEqual(temps.high, 140.0)
|
||||
self.assertEqual(temps.critical, 158.0)
|
||||
|
||||
@unittest.skipIf(not HAS_SENSORS_BATTERY, "not supported")
|
||||
@unittest.skipIf(not HAS_BATTERY, "no battery")
|
||||
def test_sensors_battery(self):
|
||||
ret = psutil.sensors_battery()
|
||||
self.assertGreaterEqual(ret.percent, 0)
|
||||
self.assertLessEqual(ret.percent, 100)
|
||||
if ret.secsleft not in (psutil.POWER_TIME_UNKNOWN,
|
||||
psutil.POWER_TIME_UNLIMITED):
|
||||
self.assertGreaterEqual(ret.secsleft, 0)
|
||||
else:
|
||||
if ret.secsleft == psutil.POWER_TIME_UNLIMITED:
|
||||
self.assertTrue(ret.power_plugged)
|
||||
self.assertIsInstance(ret.power_plugged, bool)
|
||||
|
||||
@unittest.skipIf(not HAS_SENSORS_FANS, "not supported")
|
||||
def test_sensors_fans(self):
|
||||
fans = psutil.sensors_fans()
|
||||
for name, entries in fans.items():
|
||||
self.assertIsInstance(name, str)
|
||||
for entry in entries:
|
||||
self.assertIsInstance(entry.label, str)
|
||||
self.assertIsInstance(entry.current, (int, long))
|
||||
self.assertGreaterEqual(entry.current, 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
367
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_unicode.py
поставляемый
Normal file
367
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_unicode.py
поставляемый
Normal file
|
@ -0,0 +1,367 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""
|
||||
Notes about unicode handling in psutil
|
||||
======================================
|
||||
|
||||
In psutil these are the APIs returning or dealing with a string
|
||||
('not tested' means they are not tested to deal with non-ASCII strings):
|
||||
|
||||
* Process.cmdline()
|
||||
* Process.connections('unix')
|
||||
* Process.cwd()
|
||||
* Process.environ()
|
||||
* Process.exe()
|
||||
* Process.memory_maps()
|
||||
* Process.name()
|
||||
* Process.open_files()
|
||||
* Process.username() (not tested)
|
||||
|
||||
* disk_io_counters() (not tested)
|
||||
* disk_partitions() (not tested)
|
||||
* disk_usage(str)
|
||||
* net_connections('unix')
|
||||
* net_if_addrs() (not tested)
|
||||
* net_if_stats() (not tested)
|
||||
* net_io_counters() (not tested)
|
||||
* sensors_fans() (not tested)
|
||||
* sensors_temperatures() (not tested)
|
||||
* users() (not tested)
|
||||
|
||||
* WindowsService.binpath() (not tested)
|
||||
* WindowsService.description() (not tested)
|
||||
* WindowsService.display_name() (not tested)
|
||||
* WindowsService.name() (not tested)
|
||||
* WindowsService.status() (not tested)
|
||||
* WindowsService.username() (not tested)
|
||||
|
||||
In here we create a unicode path with a funky non-ASCII name and (where
|
||||
possible) make psutil return it back (e.g. on name(), exe(), open_files(),
|
||||
etc.) and make sure that:
|
||||
|
||||
* psutil never crashes with UnicodeDecodeError
|
||||
* the returned path matches
|
||||
|
||||
For a detailed explanation of how psutil handles unicode see:
|
||||
- https://github.com/giampaolo/psutil/issues/1040
|
||||
- http://psutil.readthedocs.io/#unicode
|
||||
"""
|
||||
|
||||
import os
|
||||
import traceback
|
||||
import warnings
|
||||
from contextlib import closing
|
||||
|
||||
from psutil import BSD
|
||||
from psutil import OPENBSD
|
||||
from psutil import OSX
|
||||
from psutil import POSIX
|
||||
from psutil import WINDOWS
|
||||
from psutil._compat import PY3
|
||||
from psutil._compat import u
|
||||
from psutil.tests import APPVEYOR
|
||||
from psutil.tests import ASCII_FS
|
||||
from psutil.tests import bind_unix_socket
|
||||
from psutil.tests import chdir
|
||||
from psutil.tests import copyload_shared_lib
|
||||
from psutil.tests import create_exe
|
||||
from psutil.tests import get_test_subprocess
|
||||
from psutil.tests import HAS_CONNECTIONS_UNIX
|
||||
from psutil.tests import HAS_ENVIRON
|
||||
from psutil.tests import HAS_MEMORY_MAPS
|
||||
from psutil.tests import mock
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import safe_mkdir
|
||||
from psutil.tests import safe_rmpath as _safe_rmpath
|
||||
from psutil.tests import skip_on_access_denied
|
||||
from psutil.tests import TESTFILE_PREFIX
|
||||
from psutil.tests import TESTFN
|
||||
from psutil.tests import TESTFN_UNICODE
|
||||
from psutil.tests import TRAVIS
|
||||
from psutil.tests import unittest
|
||||
from psutil.tests import unix_socket_path
|
||||
import psutil
|
||||
import psutil.tests
|
||||
|
||||
|
||||
def safe_rmpath(path):
|
||||
if APPVEYOR:
|
||||
# TODO - this is quite random and I'm not sure why it happens,
|
||||
# nor I can reproduce it locally:
|
||||
# https://ci.appveyor.com/project/giampaolo/psutil/build/job/
|
||||
# jiq2cgd6stsbtn60
|
||||
# safe_rmpath() happens after reap_children() so this is weird
|
||||
# Perhaps wait_procs() on Windows is broken? Maybe because
|
||||
# of STILL_ACTIVE?
|
||||
# https://github.com/giampaolo/psutil/blob/
|
||||
# 68c7a70728a31d8b8b58f4be6c4c0baa2f449eda/psutil/arch/
|
||||
# windows/process_info.c#L146
|
||||
try:
|
||||
return _safe_rmpath(path)
|
||||
except WindowsError:
|
||||
traceback.print_exc()
|
||||
else:
|
||||
return _safe_rmpath(path)
|
||||
|
||||
|
||||
def subprocess_supports_unicode(name):
|
||||
"""Return True if both the fs and the subprocess module can
|
||||
deal with a unicode file name.
|
||||
"""
|
||||
if PY3:
|
||||
return True
|
||||
try:
|
||||
safe_rmpath(name)
|
||||
create_exe(name)
|
||||
get_test_subprocess(cmd=[name])
|
||||
except UnicodeEncodeError:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
finally:
|
||||
reap_children()
|
||||
|
||||
|
||||
# An invalid unicode string.
|
||||
if PY3:
|
||||
INVALID_NAME = (TESTFN.encode('utf8') + b"f\xc0\x80").decode(
|
||||
'utf8', 'surrogateescape')
|
||||
else:
|
||||
INVALID_NAME = TESTFN + "f\xc0\x80"
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# FS APIs
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class _BaseFSAPIsTests(object):
|
||||
funky_name = None
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
safe_rmpath(cls.funky_name)
|
||||
create_exe(cls.funky_name)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
safe_rmpath(cls.funky_name)
|
||||
|
||||
def tearDown(self):
|
||||
reap_children()
|
||||
|
||||
def expect_exact_path_match(self):
|
||||
raise NotImplementedError("must be implemented in subclass")
|
||||
|
||||
def test_proc_exe(self):
|
||||
subp = get_test_subprocess(cmd=[self.funky_name])
|
||||
p = psutil.Process(subp.pid)
|
||||
exe = p.exe()
|
||||
self.assertIsInstance(exe, str)
|
||||
if self.expect_exact_path_match():
|
||||
self.assertEqual(exe, self.funky_name)
|
||||
|
||||
def test_proc_name(self):
|
||||
subp = get_test_subprocess(cmd=[self.funky_name])
|
||||
if WINDOWS:
|
||||
# On Windows name() is determined from exe() first, because
|
||||
# it's faster; we want to overcome the internal optimization
|
||||
# and test name() instead of exe().
|
||||
with mock.patch("psutil._psplatform.cext.proc_exe",
|
||||
side_effect=psutil.AccessDenied(os.getpid())) as m:
|
||||
name = psutil.Process(subp.pid).name()
|
||||
assert m.called
|
||||
else:
|
||||
name = psutil.Process(subp.pid).name()
|
||||
self.assertIsInstance(name, str)
|
||||
if self.expect_exact_path_match():
|
||||
self.assertEqual(name, os.path.basename(self.funky_name))
|
||||
|
||||
def test_proc_cmdline(self):
|
||||
subp = get_test_subprocess(cmd=[self.funky_name])
|
||||
p = psutil.Process(subp.pid)
|
||||
cmdline = p.cmdline()
|
||||
for part in cmdline:
|
||||
self.assertIsInstance(part, str)
|
||||
if self.expect_exact_path_match():
|
||||
self.assertEqual(cmdline, [self.funky_name])
|
||||
|
||||
def test_proc_cwd(self):
|
||||
dname = self.funky_name + "2"
|
||||
self.addCleanup(safe_rmpath, dname)
|
||||
safe_mkdir(dname)
|
||||
with chdir(dname):
|
||||
p = psutil.Process()
|
||||
cwd = p.cwd()
|
||||
self.assertIsInstance(p.cwd(), str)
|
||||
if self.expect_exact_path_match():
|
||||
self.assertEqual(cwd, dname)
|
||||
|
||||
def test_proc_open_files(self):
|
||||
p = psutil.Process()
|
||||
start = set(p.open_files())
|
||||
with open(self.funky_name, 'rb'):
|
||||
new = set(p.open_files())
|
||||
path = (new - start).pop().path
|
||||
self.assertIsInstance(path, str)
|
||||
if BSD and not path:
|
||||
# XXX - see https://github.com/giampaolo/psutil/issues/595
|
||||
return self.skipTest("open_files on BSD is broken")
|
||||
if self.expect_exact_path_match():
|
||||
self.assertEqual(os.path.normcase(path),
|
||||
os.path.normcase(self.funky_name))
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
def test_proc_connections(self):
|
||||
suffix = os.path.basename(self.funky_name)
|
||||
with unix_socket_path(suffix=suffix) as name:
|
||||
try:
|
||||
sock = bind_unix_socket(name)
|
||||
except UnicodeEncodeError:
|
||||
if PY3:
|
||||
raise
|
||||
else:
|
||||
raise unittest.SkipTest("not supported")
|
||||
with closing(sock):
|
||||
conn = psutil.Process().connections('unix')[0]
|
||||
self.assertIsInstance(conn.laddr, str)
|
||||
# AF_UNIX addr not set on OpenBSD
|
||||
if not OPENBSD:
|
||||
self.assertEqual(conn.laddr, name)
|
||||
|
||||
@unittest.skipIf(not POSIX, "POSIX only")
|
||||
@unittest.skipIf(not HAS_CONNECTIONS_UNIX, "can't list UNIX sockets")
|
||||
@skip_on_access_denied()
|
||||
def test_net_connections(self):
|
||||
def find_sock(cons):
|
||||
for conn in cons:
|
||||
if os.path.basename(conn.laddr).startswith(TESTFILE_PREFIX):
|
||||
return conn
|
||||
raise ValueError("connection not found")
|
||||
|
||||
suffix = os.path.basename(self.funky_name)
|
||||
with unix_socket_path(suffix=suffix) as name:
|
||||
try:
|
||||
sock = bind_unix_socket(name)
|
||||
except UnicodeEncodeError:
|
||||
if PY3:
|
||||
raise
|
||||
else:
|
||||
raise unittest.SkipTest("not supported")
|
||||
with closing(sock):
|
||||
cons = psutil.net_connections(kind='unix')
|
||||
# AF_UNIX addr not set on OpenBSD
|
||||
if not OPENBSD:
|
||||
conn = find_sock(cons)
|
||||
self.assertIsInstance(conn.laddr, str)
|
||||
self.assertEqual(conn.laddr, name)
|
||||
|
||||
def test_disk_usage(self):
|
||||
dname = self.funky_name + "2"
|
||||
self.addCleanup(safe_rmpath, dname)
|
||||
safe_mkdir(dname)
|
||||
psutil.disk_usage(dname)
|
||||
|
||||
@unittest.skipIf(not HAS_MEMORY_MAPS, "not supported")
|
||||
@unittest.skipIf(not PY3, "ctypes does not support unicode on PY2")
|
||||
def test_memory_maps(self):
|
||||
# XXX: on Python 2, using ctypes.CDLL with a unicode path
|
||||
# opens a message box which blocks the test run.
|
||||
with copyload_shared_lib(dst_prefix=self.funky_name) as funky_path:
|
||||
def normpath(p):
|
||||
return os.path.realpath(os.path.normcase(p))
|
||||
libpaths = [normpath(x.path)
|
||||
for x in psutil.Process().memory_maps()]
|
||||
# ...just to have a clearer msg in case of failure
|
||||
libpaths = [x for x in libpaths if TESTFILE_PREFIX in x]
|
||||
self.assertIn(normpath(funky_path), libpaths)
|
||||
for path in libpaths:
|
||||
self.assertIsInstance(path, str)
|
||||
|
||||
|
||||
@unittest.skipIf(OSX and TRAVIS, "unreliable on TRAVIS") # TODO
|
||||
@unittest.skipIf(ASCII_FS, "ASCII fs")
|
||||
@unittest.skipIf(not subprocess_supports_unicode(TESTFN_UNICODE),
|
||||
"subprocess can't deal with unicode")
|
||||
class TestFSAPIs(_BaseFSAPIsTests, unittest.TestCase):
|
||||
"""Test FS APIs with a funky, valid, UTF8 path name."""
|
||||
funky_name = TESTFN_UNICODE
|
||||
|
||||
@classmethod
|
||||
def expect_exact_path_match(cls):
|
||||
# Do not expect psutil to correctly handle unicode paths on
|
||||
# Python 2 if os.listdir() is not able either.
|
||||
if PY3:
|
||||
return True
|
||||
else:
|
||||
here = '.' if isinstance(cls.funky_name, str) else u('.')
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
return cls.funky_name in os.listdir(here)
|
||||
|
||||
|
||||
@unittest.skipIf(OSX and TRAVIS, "unreliable on TRAVIS") # TODO
|
||||
@unittest.skipIf(not subprocess_supports_unicode(INVALID_NAME),
|
||||
"subprocess can't deal with invalid unicode")
|
||||
class TestFSAPIsWithInvalidPath(_BaseFSAPIsTests, unittest.TestCase):
|
||||
"""Test FS APIs with a funky, invalid path name."""
|
||||
funky_name = INVALID_NAME
|
||||
|
||||
@classmethod
|
||||
def expect_exact_path_match(cls):
|
||||
# Invalid unicode names are supposed to work on Python 2.
|
||||
return True
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class TestWinProcessName(unittest.TestCase):
|
||||
|
||||
def test_name_type(self):
|
||||
# On Windows name() is determined from exe() first, because
|
||||
# it's faster; we want to overcome the internal optimization
|
||||
# and test name() instead of exe().
|
||||
with mock.patch("psutil._psplatform.cext.proc_exe",
|
||||
side_effect=psutil.AccessDenied(os.getpid())) as m:
|
||||
self.assertIsInstance(psutil.Process().name(), str)
|
||||
assert m.called
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Non fs APIs
|
||||
# ===================================================================
|
||||
|
||||
|
||||
class TestNonFSAPIS(unittest.TestCase):
|
||||
"""Unicode tests for non fs-related APIs."""
|
||||
|
||||
def tearDown(self):
|
||||
reap_children()
|
||||
|
||||
@unittest.skipIf(not HAS_ENVIRON, "not supported")
|
||||
def test_proc_environ(self):
|
||||
# Note: differently from others, this test does not deal
|
||||
# with fs paths. On Python 2 subprocess module is broken as
|
||||
# it's not able to handle with non-ASCII env vars, so
|
||||
# we use "è", which is part of the extended ASCII table
|
||||
# (unicode point <= 255).
|
||||
env = os.environ.copy()
|
||||
funky_str = TESTFN_UNICODE if PY3 else 'è'
|
||||
env['FUNNY_ARG'] = funky_str
|
||||
sproc = get_test_subprocess(env=env)
|
||||
p = psutil.Process(sproc.pid)
|
||||
env = p.environ()
|
||||
for k, v in env.items():
|
||||
self.assertIsInstance(k, str)
|
||||
self.assertIsInstance(v, str)
|
||||
self.assertEqual(env['FUNNY_ARG'], funky_str)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
838
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_windows.py
поставляемый
Normal file
838
third_party/python/psutil-cp27-none-win_amd64/psutil/tests/test_windows.py
поставляемый
Normal file
|
@ -0,0 +1,838 @@
|
|||
#!/usr/bin/env python
|
||||
# -*- coding: UTF-8 -*
|
||||
|
||||
# Copyright (c) 2009, Giampaolo Rodola'. All rights reserved.
|
||||
# Use of this source code is governed by a BSD-style license that can be
|
||||
# found in the LICENSE file.
|
||||
|
||||
"""Windows specific tests."""
|
||||
|
||||
import datetime
|
||||
import errno
|
||||
import glob
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
|
||||
import psutil
|
||||
from psutil import WINDOWS
|
||||
from psutil._compat import callable
|
||||
from psutil.tests import APPVEYOR
|
||||
from psutil.tests import get_test_subprocess
|
||||
from psutil.tests import HAS_BATTERY
|
||||
from psutil.tests import mock
|
||||
from psutil.tests import reap_children
|
||||
from psutil.tests import retry_before_failing
|
||||
from psutil.tests import run_test_module_by_name
|
||||
from psutil.tests import sh
|
||||
from psutil.tests import unittest
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
try:
|
||||
import win32api # requires "pip install pypiwin32"
|
||||
import win32con
|
||||
import win32process
|
||||
import wmi # requires "pip install wmi" / "make setup-dev-env"
|
||||
except ImportError:
|
||||
if os.name == 'nt':
|
||||
raise
|
||||
|
||||
|
||||
cext = psutil._psplatform.cext
|
||||
|
||||
# are we a 64 bit process
|
||||
IS_64_BIT = sys.maxsize > 2**32
|
||||
|
||||
|
||||
def wrap_exceptions(fun):
|
||||
def wrapper(self, *args, **kwargs):
|
||||
try:
|
||||
return fun(self, *args, **kwargs)
|
||||
except OSError as err:
|
||||
from psutil._pswindows import ACCESS_DENIED_SET
|
||||
if err.errno in ACCESS_DENIED_SET:
|
||||
raise psutil.AccessDenied(None, None)
|
||||
if err.errno == errno.ESRCH:
|
||||
raise psutil.NoSuchProcess(None, None)
|
||||
raise
|
||||
return wrapper
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# System APIs
|
||||
# ===================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class TestSystemAPIs(unittest.TestCase):
|
||||
|
||||
def test_nic_names(self):
|
||||
out = sh('ipconfig /all')
|
||||
nics = psutil.net_io_counters(pernic=True).keys()
|
||||
for nic in nics:
|
||||
if "pseudo-interface" in nic.replace(' ', '-').lower():
|
||||
continue
|
||||
if nic not in out:
|
||||
self.fail(
|
||||
"%r nic wasn't found in 'ipconfig /all' output" % nic)
|
||||
|
||||
@unittest.skipIf('NUMBER_OF_PROCESSORS' not in os.environ,
|
||||
'NUMBER_OF_PROCESSORS env var is not available')
|
||||
def test_cpu_count(self):
|
||||
num_cpus = int(os.environ['NUMBER_OF_PROCESSORS'])
|
||||
self.assertEqual(num_cpus, psutil.cpu_count())
|
||||
|
||||
def test_cpu_count_2(self):
|
||||
sys_value = win32api.GetSystemInfo()[5]
|
||||
psutil_value = psutil.cpu_count()
|
||||
self.assertEqual(sys_value, psutil_value)
|
||||
|
||||
def test_cpu_freq(self):
|
||||
w = wmi.WMI()
|
||||
proc = w.Win32_Processor()[0]
|
||||
self.assertEqual(proc.CurrentClockSpeed, psutil.cpu_freq().current)
|
||||
self.assertEqual(proc.MaxClockSpeed, psutil.cpu_freq().max)
|
||||
|
||||
def test_total_phymem(self):
|
||||
w = wmi.WMI().Win32_ComputerSystem()[0]
|
||||
self.assertEqual(int(w.TotalPhysicalMemory),
|
||||
psutil.virtual_memory().total)
|
||||
|
||||
# @unittest.skipIf(wmi is None, "wmi module is not installed")
|
||||
# def test__UPTIME(self):
|
||||
# # _UPTIME constant is not public but it is used internally
|
||||
# # as value to return for pid 0 creation time.
|
||||
# # WMI behaves the same.
|
||||
# w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
# p = psutil.Process(0)
|
||||
# wmic_create = str(w.CreationDate.split('.')[0])
|
||||
# psutil_create = time.strftime("%Y%m%d%H%M%S",
|
||||
# time.localtime(p.create_time()))
|
||||
|
||||
# Note: this test is not very reliable
|
||||
@unittest.skipIf(APPVEYOR, "test not relieable on appveyor")
|
||||
@retry_before_failing()
|
||||
def test_pids(self):
|
||||
# Note: this test might fail if the OS is starting/killing
|
||||
# other processes in the meantime
|
||||
w = wmi.WMI().Win32_Process()
|
||||
wmi_pids = set([x.ProcessId for x in w])
|
||||
psutil_pids = set(psutil.pids())
|
||||
self.assertEqual(wmi_pids, psutil_pids)
|
||||
|
||||
@retry_before_failing()
|
||||
def test_disks(self):
|
||||
ps_parts = psutil.disk_partitions(all=True)
|
||||
wmi_parts = wmi.WMI().Win32_LogicalDisk()
|
||||
for ps_part in ps_parts:
|
||||
for wmi_part in wmi_parts:
|
||||
if ps_part.device.replace('\\', '') == wmi_part.DeviceID:
|
||||
if not ps_part.mountpoint:
|
||||
# this is usually a CD-ROM with no disk inserted
|
||||
break
|
||||
try:
|
||||
usage = psutil.disk_usage(ps_part.mountpoint)
|
||||
except OSError as err:
|
||||
if err.errno == errno.ENOENT:
|
||||
# usually this is the floppy
|
||||
break
|
||||
else:
|
||||
raise
|
||||
self.assertEqual(usage.total, int(wmi_part.Size))
|
||||
wmi_free = int(wmi_part.FreeSpace)
|
||||
self.assertEqual(usage.free, wmi_free)
|
||||
# 10 MB tollerance
|
||||
if abs(usage.free - wmi_free) > 10 * 1024 * 1024:
|
||||
self.fail("psutil=%s, wmi=%s" % (
|
||||
usage.free, wmi_free))
|
||||
break
|
||||
else:
|
||||
self.fail("can't find partition %s" % repr(ps_part))
|
||||
|
||||
def test_disk_usage(self):
|
||||
for disk in psutil.disk_partitions():
|
||||
sys_value = win32api.GetDiskFreeSpaceEx(disk.mountpoint)
|
||||
psutil_value = psutil.disk_usage(disk.mountpoint)
|
||||
self.assertAlmostEqual(sys_value[0], psutil_value.free,
|
||||
delta=1024 * 1024)
|
||||
self.assertAlmostEqual(sys_value[1], psutil_value.total,
|
||||
delta=1024 * 1024)
|
||||
self.assertEqual(psutil_value.used,
|
||||
psutil_value.total - psutil_value.free)
|
||||
|
||||
def test_disk_partitions(self):
|
||||
sys_value = [
|
||||
x + '\\' for x in win32api.GetLogicalDriveStrings().split("\\\x00")
|
||||
if x and not x.startswith('A:')]
|
||||
psutil_value = [x.mountpoint for x in psutil.disk_partitions(all=True)]
|
||||
self.assertEqual(sys_value, psutil_value)
|
||||
|
||||
def test_net_if_stats(self):
|
||||
ps_names = set(cext.net_if_stats())
|
||||
wmi_adapters = wmi.WMI().Win32_NetworkAdapter()
|
||||
wmi_names = set()
|
||||
for wmi_adapter in wmi_adapters:
|
||||
wmi_names.add(wmi_adapter.Name)
|
||||
wmi_names.add(wmi_adapter.NetConnectionID)
|
||||
self.assertTrue(ps_names & wmi_names,
|
||||
"no common entries in %s, %s" % (ps_names, wmi_names))
|
||||
|
||||
def test_boot_time(self):
|
||||
wmi_os = wmi.WMI().Win32_OperatingSystem()
|
||||
wmi_btime_str = wmi_os[0].LastBootUpTime.split('.')[0]
|
||||
wmi_btime_dt = datetime.datetime.strptime(
|
||||
wmi_btime_str, "%Y%m%d%H%M%S")
|
||||
psutil_dt = datetime.datetime.fromtimestamp(psutil.boot_time())
|
||||
diff = abs((wmi_btime_dt - psutil_dt).total_seconds())
|
||||
# Wmic time is 2-3 secs lower for some reason; that's OK.
|
||||
self.assertLessEqual(diff, 3)
|
||||
|
||||
def test_boot_time_fluctuation(self):
|
||||
# https://github.com/giampaolo/psutil/issues/1007
|
||||
with mock.patch('psutil._pswindows.cext.boot_time', return_value=5):
|
||||
self.assertEqual(psutil.boot_time(), 5)
|
||||
with mock.patch('psutil._pswindows.cext.boot_time', return_value=4):
|
||||
self.assertEqual(psutil.boot_time(), 5)
|
||||
with mock.patch('psutil._pswindows.cext.boot_time', return_value=6):
|
||||
self.assertEqual(psutil.boot_time(), 5)
|
||||
with mock.patch('psutil._pswindows.cext.boot_time', return_value=333):
|
||||
self.assertEqual(psutil.boot_time(), 333)
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# sensors_battery()
|
||||
# ===================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class TestSensorsBattery(unittest.TestCase):
|
||||
|
||||
def test_has_battery(self):
|
||||
if win32api.GetPwrCapabilities()['SystemBatteriesPresent']:
|
||||
self.assertIsNotNone(psutil.sensors_battery())
|
||||
else:
|
||||
self.assertIsNone(psutil.sensors_battery())
|
||||
|
||||
@unittest.skipIf(not HAS_BATTERY, "no battery")
|
||||
def test_percent(self):
|
||||
w = wmi.WMI()
|
||||
battery_wmi = w.query('select * from Win32_Battery')[0]
|
||||
battery_psutil = psutil.sensors_battery()
|
||||
self.assertAlmostEqual(
|
||||
battery_psutil.percent, battery_wmi.EstimatedChargeRemaining,
|
||||
delta=1)
|
||||
|
||||
@unittest.skipIf(not HAS_BATTERY, "no battery")
|
||||
def test_power_plugged(self):
|
||||
w = wmi.WMI()
|
||||
battery_wmi = w.query('select * from Win32_Battery')[0]
|
||||
battery_psutil = psutil.sensors_battery()
|
||||
# Status codes:
|
||||
# https://msdn.microsoft.com/en-us/library/aa394074(v=vs.85).aspx
|
||||
self.assertEqual(battery_psutil.power_plugged,
|
||||
battery_wmi.BatteryStatus == 2)
|
||||
|
||||
def test_emulate_no_battery(self):
|
||||
with mock.patch("psutil._pswindows.cext.sensors_battery",
|
||||
return_value=(0, 128, 0, 0)) as m:
|
||||
self.assertIsNone(psutil.sensors_battery())
|
||||
assert m.called
|
||||
|
||||
def test_emulate_power_connected(self):
|
||||
with mock.patch("psutil._pswindows.cext.sensors_battery",
|
||||
return_value=(1, 0, 0, 0)) as m:
|
||||
self.assertEqual(psutil.sensors_battery().secsleft,
|
||||
psutil.POWER_TIME_UNLIMITED)
|
||||
assert m.called
|
||||
|
||||
def test_emulate_power_charging(self):
|
||||
with mock.patch("psutil._pswindows.cext.sensors_battery",
|
||||
return_value=(0, 8, 0, 0)) as m:
|
||||
self.assertEqual(psutil.sensors_battery().secsleft,
|
||||
psutil.POWER_TIME_UNLIMITED)
|
||||
assert m.called
|
||||
|
||||
def test_emulate_secs_left_unknown(self):
|
||||
with mock.patch("psutil._pswindows.cext.sensors_battery",
|
||||
return_value=(0, 0, 0, -1)) as m:
|
||||
self.assertEqual(psutil.sensors_battery().secsleft,
|
||||
psutil.POWER_TIME_UNKNOWN)
|
||||
assert m.called
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Process APIs
|
||||
# ===================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class TestProcess(unittest.TestCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.pid = get_test_subprocess().pid
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
|
||||
def test_issue_24(self):
|
||||
p = psutil.Process(0)
|
||||
self.assertRaises(psutil.AccessDenied, p.kill)
|
||||
|
||||
def test_special_pid(self):
|
||||
p = psutil.Process(4)
|
||||
self.assertEqual(p.name(), 'System')
|
||||
# use __str__ to access all common Process properties to check
|
||||
# that nothing strange happens
|
||||
str(p)
|
||||
p.username()
|
||||
self.assertTrue(p.create_time() >= 0.0)
|
||||
try:
|
||||
rss, vms = p.memory_info()[:2]
|
||||
except psutil.AccessDenied:
|
||||
# expected on Windows Vista and Windows 7
|
||||
if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
|
||||
raise
|
||||
else:
|
||||
self.assertTrue(rss > 0)
|
||||
|
||||
def test_send_signal(self):
|
||||
p = psutil.Process(self.pid)
|
||||
self.assertRaises(ValueError, p.send_signal, signal.SIGINT)
|
||||
|
||||
def test_exe(self):
|
||||
for p in psutil.process_iter():
|
||||
try:
|
||||
self.assertEqual(os.path.basename(p.exe()), p.name())
|
||||
except psutil.Error:
|
||||
pass
|
||||
|
||||
def test_num_handles_increment(self):
|
||||
p = psutil.Process(os.getpid())
|
||||
before = p.num_handles()
|
||||
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
|
||||
win32con.FALSE, os.getpid())
|
||||
after = p.num_handles()
|
||||
self.assertEqual(after, before + 1)
|
||||
win32api.CloseHandle(handle)
|
||||
self.assertEqual(p.num_handles(), before)
|
||||
|
||||
def test_handles_leak(self):
|
||||
# Call all Process methods and make sure no handles are left
|
||||
# open. This is here mainly to make sure functions using
|
||||
# OpenProcess() always call CloseHandle().
|
||||
def call(p, attr):
|
||||
attr = getattr(p, name, None)
|
||||
if attr is not None and callable(attr):
|
||||
attr()
|
||||
else:
|
||||
attr
|
||||
|
||||
p = psutil.Process(self.pid)
|
||||
failures = []
|
||||
for name in dir(psutil.Process):
|
||||
if name.startswith('_') \
|
||||
or name in ('terminate', 'kill', 'suspend', 'resume',
|
||||
'nice', 'send_signal', 'wait', 'children',
|
||||
'as_dict', 'memory_info_ex'):
|
||||
continue
|
||||
else:
|
||||
try:
|
||||
call(p, name)
|
||||
num1 = p.num_handles()
|
||||
call(p, name)
|
||||
num2 = p.num_handles()
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
||||
pass
|
||||
else:
|
||||
if num2 > num1:
|
||||
fail = \
|
||||
"failure while processing Process.%s method " \
|
||||
"(before=%s, after=%s)" % (name, num1, num2)
|
||||
failures.append(fail)
|
||||
if failures:
|
||||
self.fail('\n' + '\n'.join(failures))
|
||||
|
||||
def test_name_always_available(self):
|
||||
# On Windows name() is never supposed to raise AccessDenied,
|
||||
# see https://github.com/giampaolo/psutil/issues/627
|
||||
for p in psutil.process_iter():
|
||||
try:
|
||||
p.name()
|
||||
except psutil.NoSuchProcess:
|
||||
pass
|
||||
|
||||
@unittest.skipIf(not sys.version_info >= (2, 7),
|
||||
"CTRL_* signals not supported")
|
||||
def test_ctrl_signals(self):
|
||||
p = psutil.Process(get_test_subprocess().pid)
|
||||
p.send_signal(signal.CTRL_C_EVENT)
|
||||
p.send_signal(signal.CTRL_BREAK_EVENT)
|
||||
p.kill()
|
||||
p.wait()
|
||||
self.assertRaises(psutil.NoSuchProcess,
|
||||
p.send_signal, signal.CTRL_C_EVENT)
|
||||
self.assertRaises(psutil.NoSuchProcess,
|
||||
p.send_signal, signal.CTRL_BREAK_EVENT)
|
||||
|
||||
def test_compare_name_exe(self):
|
||||
for p in psutil.process_iter():
|
||||
try:
|
||||
a = os.path.basename(p.exe())
|
||||
b = p.name()
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied):
|
||||
pass
|
||||
else:
|
||||
self.assertEqual(a, b)
|
||||
|
||||
def test_username(self):
|
||||
self.assertEqual(psutil.Process().username(),
|
||||
win32api.GetUserNameEx(win32con.NameSamCompatible))
|
||||
|
||||
def test_cmdline(self):
|
||||
sys_value = re.sub(' +', ' ', win32api.GetCommandLine()).strip()
|
||||
psutil_value = ' '.join(psutil.Process().cmdline())
|
||||
self.assertEqual(sys_value, psutil_value)
|
||||
|
||||
# XXX - occasional failures
|
||||
|
||||
# def test_cpu_times(self):
|
||||
# handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
|
||||
# win32con.FALSE, os.getpid())
|
||||
# self.addCleanup(win32api.CloseHandle, handle)
|
||||
# sys_value = win32process.GetProcessTimes(handle)
|
||||
# psutil_value = psutil.Process().cpu_times()
|
||||
# self.assertAlmostEqual(
|
||||
# psutil_value.user, sys_value['UserTime'] / 10000000.0,
|
||||
# delta=0.2)
|
||||
# self.assertAlmostEqual(
|
||||
# psutil_value.user, sys_value['KernelTime'] / 10000000.0,
|
||||
# delta=0.2)
|
||||
|
||||
def test_nice(self):
|
||||
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
|
||||
win32con.FALSE, os.getpid())
|
||||
self.addCleanup(win32api.CloseHandle, handle)
|
||||
sys_value = win32process.GetPriorityClass(handle)
|
||||
psutil_value = psutil.Process().nice()
|
||||
self.assertEqual(psutil_value, sys_value)
|
||||
|
||||
def test_memory_info(self):
|
||||
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
|
||||
win32con.FALSE, self.pid)
|
||||
self.addCleanup(win32api.CloseHandle, handle)
|
||||
sys_value = win32process.GetProcessMemoryInfo(handle)
|
||||
psutil_value = psutil.Process(self.pid).memory_info()
|
||||
self.assertEqual(
|
||||
sys_value['PeakWorkingSetSize'], psutil_value.peak_wset)
|
||||
self.assertEqual(
|
||||
sys_value['WorkingSetSize'], psutil_value.wset)
|
||||
self.assertEqual(
|
||||
sys_value['QuotaPeakPagedPoolUsage'], psutil_value.peak_paged_pool)
|
||||
self.assertEqual(
|
||||
sys_value['QuotaPagedPoolUsage'], psutil_value.paged_pool)
|
||||
self.assertEqual(
|
||||
sys_value['QuotaPeakNonPagedPoolUsage'],
|
||||
psutil_value.peak_nonpaged_pool)
|
||||
self.assertEqual(
|
||||
sys_value['QuotaNonPagedPoolUsage'], psutil_value.nonpaged_pool)
|
||||
self.assertEqual(
|
||||
sys_value['PagefileUsage'], psutil_value.pagefile)
|
||||
self.assertEqual(
|
||||
sys_value['PeakPagefileUsage'], psutil_value.peak_pagefile)
|
||||
|
||||
self.assertEqual(psutil_value.rss, psutil_value.wset)
|
||||
self.assertEqual(psutil_value.vms, psutil_value.pagefile)
|
||||
|
||||
def test_wait(self):
|
||||
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
|
||||
win32con.FALSE, self.pid)
|
||||
self.addCleanup(win32api.CloseHandle, handle)
|
||||
p = psutil.Process(self.pid)
|
||||
p.terminate()
|
||||
psutil_value = p.wait()
|
||||
sys_value = win32process.GetExitCodeProcess(handle)
|
||||
self.assertEqual(psutil_value, sys_value)
|
||||
|
||||
def test_cpu_affinity(self):
|
||||
def from_bitmask(x):
|
||||
return [i for i in range(64) if (1 << i) & x]
|
||||
|
||||
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
|
||||
win32con.FALSE, self.pid)
|
||||
self.addCleanup(win32api.CloseHandle, handle)
|
||||
sys_value = from_bitmask(
|
||||
win32process.GetProcessAffinityMask(handle)[0])
|
||||
psutil_value = psutil.Process(self.pid).cpu_affinity()
|
||||
self.assertEqual(psutil_value, sys_value)
|
||||
|
||||
def test_io_counters(self):
|
||||
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION,
|
||||
win32con.FALSE, os.getpid())
|
||||
self.addCleanup(win32api.CloseHandle, handle)
|
||||
sys_value = win32process.GetProcessIoCounters(handle)
|
||||
psutil_value = psutil.Process().io_counters()
|
||||
self.assertEqual(
|
||||
psutil_value.read_count, sys_value['ReadOperationCount'])
|
||||
self.assertEqual(
|
||||
psutil_value.write_count, sys_value['WriteOperationCount'])
|
||||
self.assertEqual(
|
||||
psutil_value.read_bytes, sys_value['ReadTransferCount'])
|
||||
self.assertEqual(
|
||||
psutil_value.write_bytes, sys_value['WriteTransferCount'])
|
||||
self.assertEqual(
|
||||
psutil_value.other_count, sys_value['OtherOperationCount'])
|
||||
self.assertEqual(
|
||||
psutil_value.other_bytes, sys_value['OtherTransferCount'])
|
||||
|
||||
def test_num_handles(self):
|
||||
import ctypes
|
||||
import ctypes.wintypes
|
||||
PROCESS_QUERY_INFORMATION = 0x400
|
||||
handle = ctypes.windll.kernel32.OpenProcess(
|
||||
PROCESS_QUERY_INFORMATION, 0, os.getpid())
|
||||
self.addCleanup(ctypes.windll.kernel32.CloseHandle, handle)
|
||||
hndcnt = ctypes.wintypes.DWORD()
|
||||
ctypes.windll.kernel32.GetProcessHandleCount(
|
||||
handle, ctypes.byref(hndcnt))
|
||||
sys_value = hndcnt.value
|
||||
psutil_value = psutil.Process().num_handles()
|
||||
ctypes.windll.kernel32.CloseHandle(handle)
|
||||
self.assertEqual(psutil_value, sys_value + 1)
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class TestProcessWMI(unittest.TestCase):
|
||||
"""Compare Process API results with WMI."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.pid = get_test_subprocess().pid
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
|
||||
def test_name(self):
|
||||
w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
p = psutil.Process(self.pid)
|
||||
self.assertEqual(p.name(), w.Caption)
|
||||
|
||||
def test_exe(self):
|
||||
w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
p = psutil.Process(self.pid)
|
||||
# Note: wmi reports the exe as a lower case string.
|
||||
# Being Windows paths case-insensitive we ignore that.
|
||||
self.assertEqual(p.exe().lower(), w.ExecutablePath.lower())
|
||||
|
||||
def test_cmdline(self):
|
||||
w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
p = psutil.Process(self.pid)
|
||||
self.assertEqual(' '.join(p.cmdline()),
|
||||
w.CommandLine.replace('"', ''))
|
||||
|
||||
def test_username(self):
|
||||
w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
p = psutil.Process(self.pid)
|
||||
domain, _, username = w.GetOwner()
|
||||
username = "%s\\%s" % (domain, username)
|
||||
self.assertEqual(p.username(), username)
|
||||
|
||||
def test_memory_rss(self):
|
||||
time.sleep(0.1)
|
||||
w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
p = psutil.Process(self.pid)
|
||||
rss = p.memory_info().rss
|
||||
self.assertEqual(rss, int(w.WorkingSetSize))
|
||||
|
||||
def test_memory_vms(self):
|
||||
time.sleep(0.1)
|
||||
w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
p = psutil.Process(self.pid)
|
||||
vms = p.memory_info().vms
|
||||
# http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx
|
||||
# ...claims that PageFileUsage is represented in Kilo
|
||||
# bytes but funnily enough on certain platforms bytes are
|
||||
# returned instead.
|
||||
wmi_usage = int(w.PageFileUsage)
|
||||
if (vms != wmi_usage) and (vms != wmi_usage * 1024):
|
||||
self.fail("wmi=%s, psutil=%s" % (wmi_usage, vms))
|
||||
|
||||
def test_create_time(self):
|
||||
w = wmi.WMI().Win32_Process(ProcessId=self.pid)[0]
|
||||
p = psutil.Process(self.pid)
|
||||
wmic_create = str(w.CreationDate.split('.')[0])
|
||||
psutil_create = time.strftime("%Y%m%d%H%M%S",
|
||||
time.localtime(p.create_time()))
|
||||
self.assertEqual(wmic_create, psutil_create)
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class TestDualProcessImplementation(unittest.TestCase):
|
||||
"""
|
||||
Certain APIs on Windows have 2 internal implementations, one
|
||||
based on documented Windows APIs, another one based
|
||||
NtQuerySystemInformation() which gets called as fallback in
|
||||
case the first fails because of limited permission error.
|
||||
Here we test that the two methods return the exact same value,
|
||||
see:
|
||||
https://github.com/giampaolo/psutil/issues/304
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.pid = get_test_subprocess().pid
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
# ---
|
||||
# same tests as above but mimicks the AccessDenied failure of
|
||||
# the first (fast) method failing with AD.
|
||||
|
||||
def test_name(self):
|
||||
name = psutil.Process(self.pid).name()
|
||||
with mock.patch("psutil._psplatform.cext.proc_exe",
|
||||
side_effect=psutil.AccessDenied(os.getpid())) as fun:
|
||||
self.assertEqual(psutil.Process(self.pid).name(), name)
|
||||
assert fun.called
|
||||
|
||||
def test_memory_info(self):
|
||||
mem_1 = psutil.Process(self.pid).memory_info()
|
||||
with mock.patch("psutil._psplatform.cext.proc_memory_info",
|
||||
side_effect=OSError(errno.EPERM, "msg")) as fun:
|
||||
mem_2 = psutil.Process(self.pid).memory_info()
|
||||
self.assertEqual(len(mem_1), len(mem_2))
|
||||
for i in range(len(mem_1)):
|
||||
self.assertGreaterEqual(mem_1[i], 0)
|
||||
self.assertGreaterEqual(mem_2[i], 0)
|
||||
self.assertAlmostEqual(mem_1[i], mem_2[i], delta=512)
|
||||
assert fun.called
|
||||
|
||||
def test_create_time(self):
|
||||
ctime = psutil.Process(self.pid).create_time()
|
||||
with mock.patch("psutil._psplatform.cext.proc_create_time",
|
||||
side_effect=OSError(errno.EPERM, "msg")) as fun:
|
||||
self.assertEqual(psutil.Process(self.pid).create_time(), ctime)
|
||||
assert fun.called
|
||||
|
||||
def test_cpu_times(self):
|
||||
cpu_times_1 = psutil.Process(self.pid).cpu_times()
|
||||
with mock.patch("psutil._psplatform.cext.proc_cpu_times",
|
||||
side_effect=OSError(errno.EPERM, "msg")) as fun:
|
||||
cpu_times_2 = psutil.Process(self.pid).cpu_times()
|
||||
assert fun.called
|
||||
self.assertAlmostEqual(
|
||||
cpu_times_1.user, cpu_times_2.user, delta=0.01)
|
||||
self.assertAlmostEqual(
|
||||
cpu_times_1.system, cpu_times_2.system, delta=0.01)
|
||||
|
||||
def test_io_counters(self):
|
||||
io_counters_1 = psutil.Process(self.pid).io_counters()
|
||||
with mock.patch("psutil._psplatform.cext.proc_io_counters",
|
||||
side_effect=OSError(errno.EPERM, "msg")) as fun:
|
||||
io_counters_2 = psutil.Process(self.pid).io_counters()
|
||||
for i in range(len(io_counters_1)):
|
||||
self.assertAlmostEqual(
|
||||
io_counters_1[i], io_counters_2[i], delta=5)
|
||||
assert fun.called
|
||||
|
||||
def test_num_handles(self):
|
||||
num_handles = psutil.Process(self.pid).num_handles()
|
||||
with mock.patch("psutil._psplatform.cext.proc_num_handles",
|
||||
side_effect=OSError(errno.EPERM, "msg")) as fun:
|
||||
self.assertEqual(psutil.Process(self.pid).num_handles(),
|
||||
num_handles)
|
||||
assert fun.called
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class RemoteProcessTestCase(unittest.TestCase):
|
||||
"""Certain functions require calling ReadProcessMemory.
|
||||
This trivially works when called on the current process.
|
||||
Check that this works on other processes, especially when they
|
||||
have a different bitness.
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def find_other_interpreter():
|
||||
# find a python interpreter that is of the opposite bitness from us
|
||||
code = "import sys; sys.stdout.write(str(sys.maxsize > 2**32))"
|
||||
|
||||
# XXX: a different and probably more stable approach might be to access
|
||||
# the registry but accessing 64 bit paths from a 32 bit process
|
||||
for filename in glob.glob(r"C:\Python*\python.exe"):
|
||||
proc = subprocess.Popen(args=[filename, "-c", code],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT)
|
||||
output, _ = proc.communicate()
|
||||
if output == str(not IS_64_BIT):
|
||||
return filename
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
other_python = cls.find_other_interpreter()
|
||||
|
||||
if other_python is None:
|
||||
raise unittest.SkipTest(
|
||||
"could not find interpreter with opposite bitness")
|
||||
|
||||
if IS_64_BIT:
|
||||
cls.python64 = sys.executable
|
||||
cls.python32 = other_python
|
||||
else:
|
||||
cls.python64 = other_python
|
||||
cls.python32 = sys.executable
|
||||
|
||||
test_args = ["-c", "import sys; sys.stdin.read()"]
|
||||
|
||||
def setUp(self):
|
||||
env = os.environ.copy()
|
||||
env["THINK_OF_A_NUMBER"] = str(os.getpid())
|
||||
self.proc32 = get_test_subprocess([self.python32] + self.test_args,
|
||||
env=env,
|
||||
stdin=subprocess.PIPE)
|
||||
self.proc64 = get_test_subprocess([self.python64] + self.test_args,
|
||||
env=env,
|
||||
stdin=subprocess.PIPE)
|
||||
|
||||
def tearDown(self):
|
||||
self.proc32.communicate()
|
||||
self.proc64.communicate()
|
||||
reap_children()
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
reap_children()
|
||||
|
||||
def test_cmdline_32(self):
|
||||
p = psutil.Process(self.proc32.pid)
|
||||
self.assertEqual(len(p.cmdline()), 3)
|
||||
self.assertEqual(p.cmdline()[1:], self.test_args)
|
||||
|
||||
def test_cmdline_64(self):
|
||||
p = psutil.Process(self.proc64.pid)
|
||||
self.assertEqual(len(p.cmdline()), 3)
|
||||
self.assertEqual(p.cmdline()[1:], self.test_args)
|
||||
|
||||
def test_cwd_32(self):
|
||||
p = psutil.Process(self.proc32.pid)
|
||||
self.assertEqual(p.cwd(), os.getcwd())
|
||||
|
||||
def test_cwd_64(self):
|
||||
p = psutil.Process(self.proc64.pid)
|
||||
self.assertEqual(p.cwd(), os.getcwd())
|
||||
|
||||
def test_environ_32(self):
|
||||
p = psutil.Process(self.proc32.pid)
|
||||
e = p.environ()
|
||||
self.assertIn("THINK_OF_A_NUMBER", e)
|
||||
self.assertEquals(e["THINK_OF_A_NUMBER"], str(os.getpid()))
|
||||
|
||||
def test_environ_64(self):
|
||||
p = psutil.Process(self.proc64.pid)
|
||||
e = p.environ()
|
||||
self.assertIn("THINK_OF_A_NUMBER", e)
|
||||
self.assertEquals(e["THINK_OF_A_NUMBER"], str(os.getpid()))
|
||||
|
||||
|
||||
# ===================================================================
|
||||
# Windows services
|
||||
# ===================================================================
|
||||
|
||||
|
||||
@unittest.skipIf(not WINDOWS, "WINDOWS only")
|
||||
class TestServices(unittest.TestCase):
|
||||
|
||||
def test_win_service_iter(self):
|
||||
valid_statuses = set([
|
||||
"running",
|
||||
"paused",
|
||||
"start",
|
||||
"pause",
|
||||
"continue",
|
||||
"stop",
|
||||
"stopped",
|
||||
])
|
||||
valid_start_types = set([
|
||||
"automatic",
|
||||
"manual",
|
||||
"disabled",
|
||||
])
|
||||
valid_statuses = set([
|
||||
"running",
|
||||
"paused",
|
||||
"start_pending",
|
||||
"pause_pending",
|
||||
"continue_pending",
|
||||
"stop_pending",
|
||||
"stopped"
|
||||
])
|
||||
for serv in psutil.win_service_iter():
|
||||
data = serv.as_dict()
|
||||
self.assertIsInstance(data['name'], str)
|
||||
self.assertNotEqual(data['name'].strip(), "")
|
||||
self.assertIsInstance(data['display_name'], str)
|
||||
self.assertIsInstance(data['username'], str)
|
||||
self.assertIn(data['status'], valid_statuses)
|
||||
if data['pid'] is not None:
|
||||
psutil.Process(data['pid'])
|
||||
self.assertIsInstance(data['binpath'], str)
|
||||
self.assertIsInstance(data['username'], str)
|
||||
self.assertIsInstance(data['start_type'], str)
|
||||
self.assertIn(data['start_type'], valid_start_types)
|
||||
self.assertIn(data['status'], valid_statuses)
|
||||
self.assertIsInstance(data['description'], str)
|
||||
pid = serv.pid()
|
||||
if pid is not None:
|
||||
p = psutil.Process(pid)
|
||||
self.assertTrue(p.is_running())
|
||||
# win_service_get
|
||||
s = psutil.win_service_get(serv.name())
|
||||
# test __eq__
|
||||
self.assertEqual(serv, s)
|
||||
|
||||
def test_win_service_get(self):
|
||||
name = next(psutil.win_service_iter()).name()
|
||||
|
||||
with self.assertRaises(psutil.NoSuchProcess) as cm:
|
||||
psutil.win_service_get(name + '???')
|
||||
self.assertEqual(cm.exception.name, name + '???')
|
||||
|
||||
# test NoSuchProcess
|
||||
service = psutil.win_service_get(name)
|
||||
exc = WindowsError(
|
||||
psutil._psplatform.cext.ERROR_SERVICE_DOES_NOT_EXIST, "")
|
||||
with mock.patch("psutil._psplatform.cext.winservice_query_status",
|
||||
side_effect=exc):
|
||||
self.assertRaises(psutil.NoSuchProcess, service.status)
|
||||
with mock.patch("psutil._psplatform.cext.winservice_query_config",
|
||||
side_effect=exc):
|
||||
self.assertRaises(psutil.NoSuchProcess, service.username)
|
||||
|
||||
# test AccessDenied
|
||||
exc = WindowsError(
|
||||
psutil._psplatform.cext.ERROR_ACCESS_DENIED, "")
|
||||
with mock.patch("psutil._psplatform.cext.winservice_query_status",
|
||||
side_effect=exc):
|
||||
self.assertRaises(psutil.AccessDenied, service.status)
|
||||
with mock.patch("psutil._psplatform.cext.winservice_query_config",
|
||||
side_effect=exc):
|
||||
self.assertRaises(psutil.AccessDenied, service.username)
|
||||
|
||||
# test __str__ and __repr__
|
||||
self.assertIn(service.name(), str(service))
|
||||
self.assertIn(service.display_name(), str(service))
|
||||
self.assertIn(service.name(), repr(service))
|
||||
self.assertIn(service.display_name(), repr(service))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run_test_module_by_name(__file__)
|
Загрузка…
Ссылка в новой задаче